Files
core/paths/unix.go
T
terminarandClaude Sonnet 5 da2ec85381 Refine macOS/LogAlias platform tuning, fix a real WithRoot bug found on Windows
Platform tuning:
- macOS Desktop's RuntimeDir() now prefers $TMPDIR (the OS-managed,
  per-user ephemeral directory NSTemporaryDirectory() returns) over
  the previous ~/Library/Application Support/<App>/Runtime placeholder.
- Resolver.EnsureLogAlias() creates the optional LogAliasDir() symlink
  to LogDir(), idempotently, leaving any pre-existing entry alone.

Verified the SHGetKnownFolderPath fallback (knownfolders_windows.go)
on a real Windows host for the first time: with APPDATA/LOCALAPPDATA/
PROGRAMDATA all unset, it correctly resolves the real known folders.
go vet's one unsafeptr finding there is a documented, permanent,
unavoidable characteristic of this raw-syscall pattern, not a bug.

That same real-Windows run surfaced a genuine, previously-invisible
bug: WithRoot assumed root's own address family always matched the
*simulated* platform's, which silently broke (mixed separators, or an
outright invalid mid-path drive letter) whenever the real host's
native family differed from what WithPlatform was simulating -- e.g.
WithPlatform("linux") with WithRoot(t.TempDir()) on a real Windows
host. This was invisible on macOS/Linux, where t.TempDir() happens to
already share the simulated Unix family.

Fixed applyRoot (now applyRootRebase) to decompose the resolved path
into segments and re-join them onto root using root's own family,
inferred from its content like JoinDirFile already does, not from the
simulated platform. Two call sites chaining onto an already-rooted
value (logDirUnix, darwin.go's State/Runtime fallback) switched from a
hardcoded unixJoin to JoinDirFile for the same reason. core/config's
working-directory layer had the identical bug one level up; fixed via
a new paths.JoinDirFileFamily.

TODO.md/ARCHITECTURE.md/README.md updated accordingly; core/TODO.md's
remaining items are now all explicitly out-of-scope or deliberately
deprioritized, not open work.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 16:37:30 +02:00

260 lines
9.3 KiB
Go

package paths
import (
"strings"
"yetano.dev/yetano/core"
)
// unixFlavor holds the small set of system-wide (SystemScope) location
// conventions that differ between Unix-family operating systems. The
// per-user, XDG-driven side of the layout is identical across all of
// them (see spec section 12: macOS CLI/Service intentionally uses the
// same layout as Linux, for consistent cross-platform administration).
type unixFlavor struct {
systemConfigDirs []string // e.g. ["/etc"] or ["/usr/local/etc"]
systemDataDirs []string // default XDG_DATA_DIRS search list (read-only, vendor data), e.g. ["/usr/local/share", "/usr/share"]
systemDataBase string // canonical, writable system DataDir base, e.g. "/var/lib" or "/var/db"
systemStateBase string // e.g. "/var/lib"
systemCacheBase string // e.g. "/var/cache"
systemRuntimeBase string // e.g. "/run"
systemLogBase string // e.g. "/var/log"
systemBinDir string // e.g. "/usr/local/bin" -- shared, not namespaced per app
}
// flavor selects the unixFlavor for r.platform. darwin (in CLI/Service
// kind) and any GOOS not otherwise recognized fall back to the Linux
// flavor as a documented, sane default -- see AGENTS.md TODO for tuning
// individual BSDs later without a redesign.
func (r *Resolver) flavor() unixFlavor {
switch r.platform {
case "freebsd":
return freebsdFlavor
default:
return linuxFlavor
}
}
// homeDir resolves the current user's home directory: $HOME on Unix,
// %USERPROFILE% on Windows. It never falls back to a guessed value --
// spec section 51 requires a clean error for a missing home directory.
func (r *Resolver) homeDir() (string, error) {
if r.isWindows() {
if v, ok := lookup(r.env, "USERPROFILE"); ok {
return v, nil
}
return "", ErrNoHomeDirectory
}
if v, ok := lookup(r.env, "HOME"); ok {
return v, nil
}
return "", ErrNoHomeDirectory
}
// xdgBase resolves one XDG_*_HOME-shaped base directory: envVar's value
// if set, else $HOME joined with defaultRelParts.
func (r *Resolver) xdgBase(envVar string, defaultRelParts ...string) (value, error) {
if v, ok := lookup(r.env, envVar); ok {
return value{path: v, source: XDGEnvironment}, nil
}
home, err := r.homeDir()
if err != nil {
return value{}, err
}
return value{path: unixJoin(append([]string{home}, defaultRelParts...)...), source: PlatformDefault}, nil
}
// xdgDataDirs resolves the XDG_DATA_DIRS list: its colon-separated value
// if set (non-empty entries only), else the flavor's system defaults.
func (r *Resolver) xdgDataDirs() ([]string, Source) {
if v, ok := lookup(r.env, "XDG_DATA_DIRS"); ok {
var dirs []string
for d := range strings.SplitSeq(v, ":") {
if d != "" {
dirs = append(dirs, d)
}
}
if len(dirs) > 0 {
return dirs, XDGEnvironment
}
}
return r.flavor().systemDataDirs, PlatformDefault
}
// unixCanonical implements the shared override-chain + XDG/system
// resolution used by StateDir, CacheDir, RuntimeDir's "available" branch,
// and (via configDirUnix/dataDirUnix) Config/DataDir: tiers 1-3 (API,
// app env, YETANO env) first, then SystemScope's fixed system directory,
// then the XDG base (tier 4) with tier 5's default baked in.
func (r *Resolver) unixCanonical(kind PathKind, xdgVar string, systemBase string, defaultRelParts ...string) (value, error) {
if v, ok := r.overrideValue(kind); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
if r.app.Scope == core.SystemScope {
return value{path: r.applyRoot(unixJoin(systemBase, r.app.Name)), source: SystemDirectory}, nil
}
base, err := r.xdgBase(xdgVar, defaultRelParts...)
if err != nil {
return value{}, err
}
return value{path: r.applyRoot(unixJoin(base.path, r.app.Name)), source: base.source}, nil
}
func (r *Resolver) configDirUnix() (value, error) {
return r.unixCanonical(ConfigPath, "XDG_CONFIG_HOME", r.flavor().systemConfigDirs[0], ".config")
}
func (r *Resolver) dataDirUnix() (value, error) {
return r.unixCanonical(DataPath, "XDG_DATA_HOME", r.flavor().systemDataBase, ".local", "share")
}
func (r *Resolver) stateDirUnix() (value, error) {
return r.unixCanonical(StatePath, "XDG_STATE_HOME", r.flavor().systemStateBase, ".local", "state")
}
func (r *Resolver) cacheDirUnix() (value, error) {
return r.unixCanonical(CachePath, "XDG_CACHE_HOME", r.flavor().systemCacheBase, ".cache")
}
// runtimeDirUnix implements spec section 8: XDG_RUNTIME_DIR is never
// synthesized from a fallback like ~/.local/run. Without an explicit
// override (tiers 1-3) or an XDG_RUNTIME_DIR set in the environment,
// the runtime directory is reported unavailable.
func (r *Resolver) runtimeDirUnix() (value, error) {
if v, ok := r.overrideValue(RuntimePath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
if r.app.Scope == core.SystemScope {
return value{path: r.applyRoot(unixJoin(r.flavor().systemRuntimeBase, r.app.Name)), source: SystemDirectory}, nil
}
if v, ok := lookup(r.env, "XDG_RUNTIME_DIR"); ok {
return value{path: r.applyRoot(unixJoin(v, r.app.Name)), source: XDGEnvironment}, nil
}
return value{}, ErrRuntimeDirUnavailable
}
// logDirUnix has no XDG variable of its own; its tier-5 default nests
// under StateDir (spec section 39's "canonical: ~/.local/state/<app>/log/").
func (r *Resolver) logDirUnix() (value, error) {
if v, ok := r.overrideValue(LogPath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
if r.app.Scope == core.SystemScope {
return value{path: r.applyRoot(unixJoin(r.flavor().systemLogBase, r.app.Name)), source: SystemDirectory}, nil
}
state, err := r.stateDirUnix()
if err != nil {
return value{}, err
}
// stateDirUnix already applied the root, so joining the "log" suffix
// must use JoinDirFile (not unixJoin) rather than rebasing again:
// WithRoot's root can be in a different address family than this
// simulated platform (see applyRootRebase), so the already-rooted
// state.path may itself be Windows-separated even here.
return value{path: JoinDirFile(state.path, "log"), source: state.source}, nil
}
// logAliasDirUnix is the optional convenience location spec section 39
// discusses (~/.local/log/<app>) -- never created automatically, and
// only ever a suggestion surfaced via Explain/LogAliasDir.
func (r *Resolver) logAliasDirUnix() (value, error) {
home, err := r.homeDir()
if err != nil {
return value{}, err
}
return value{path: r.applyRoot(unixJoin(home, ".local", "log", r.app.Name)), source: PlatformDefault}, nil
}
// binDirUnix: a bin directory is conventionally shared across every
// application (like ~/.local/bin), never namespaced per app -- see
// appendsAppName.
func (r *Resolver) binDirUnix() (value, error) {
if v, ok := r.overrideValue(BinPath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
if r.app.Scope == core.SystemScope {
return value{path: r.applyRoot(r.flavor().systemBinDir), source: SystemDirectory}, nil
}
home, err := r.homeDir()
if err != nil {
return value{}, err
}
return value{path: r.applyRoot(unixJoin(home, ".local", "bin")), source: PlatformDefault}, nil
}
func (r *Resolver) configLayersUnix() ([]layer, error) {
if v, ok := r.overrideValue(ConfigPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
userVal, err := r.xdgBase("XDG_CONFIG_HOME", ".config")
if err != nil {
return nil, err
}
user := []layer{{
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
source: userVal.source,
priority: PriorityUser,
canonical: true,
}}
system := make([]layer, len(r.flavor().systemConfigDirs))
for i, dir := range r.flavor().systemConfigDirs {
system[i] = layer{
path: r.applyRoot(unixJoin(dir, r.app.Name)),
source: SystemDirectory,
priority: PrioritySystem - i,
canonical: i == 0 && r.app.Scope == core.SystemScope,
}
}
return composeSearch(user, system, r.app.Scope), nil
}
func (r *Resolver) dataLayersUnix() ([]layer, error) {
if v, ok := r.overrideValue(DataPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
userVal, err := r.xdgBase("XDG_DATA_HOME", ".local", "share")
if err != nil {
return nil, err
}
user := []layer{{
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
source: userVal.source,
priority: PriorityUser,
canonical: true,
}}
dirs, source := r.xdgDataDirs()
system := make([]layer, len(dirs))
for i, dir := range dirs {
system[i] = layer{
path: r.applyRoot(unixJoin(dir, r.app.Name)),
source: source,
priority: PrioritySystem - i,
canonical: i == 0 && r.app.Scope == core.SystemScope,
}
}
return composeSearch(user, system, r.app.Scope), nil
}
func (r *Resolver) executableLayersUnix() ([]layer, error) {
if v, ok := r.overrideValue(BinPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
home, err := r.homeDir()
if err != nil {
return nil, err
}
user := []layer{{
path: r.applyRoot(unixJoin(home, ".local", "bin")),
source: PlatformDefault,
priority: PriorityUser,
canonical: true,
}}
system := []layer{{
path: r.applyRoot(r.flavor().systemBinDir),
source: SystemDirectory,
priority: PrioritySystem,
canonical: r.app.Scope == core.SystemScope,
}}
return composeSearch(user, system, r.app.Scope), nil
}