Files
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

229 lines
6.6 KiB
Go

package paths
import "os"
// SearchResult describes one directory in a search/priority hierarchy,
// with enough metadata for Explain/doctor-style introspection (spec
// section 48).
type SearchResult struct {
Path string
Source Source
Priority int
Exists bool
Selected bool
}
// statExists reports whether path exists (any type), swallowing the
// distinction between "does not exist" and other stat errors (permission
// issues etc. are surfaced as "does not exist" here -- a resolver's job
// is to compute and search paths, not diagnose filesystem permissions).
func statExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// resultsFromLayers converts layers (already in priority order) into
// SearchResults, checking each directory's existence and marking the
// first existing one Selected -- i.e. "the layer that would be used if
// resolving by first match over directories alone", consistent with
// FindConfig/FindData's file-level first-match semantics.
func resultsFromLayers(layers []layer) []SearchResult {
results := make([]SearchResult, len(layers))
selected := false
for i, l := range layers {
exists := statExists(l.path)
results[i] = SearchResult{
Path: l.path,
Source: l.source,
Priority: l.priority,
Exists: exists,
Selected: exists && !selected,
}
if exists {
selected = true
}
}
return results
}
// statInfo is a small, deliberately approximate writability check used
// only by Explain: it looks at the owner-write permission bit rather
// than performing a real access check (which would require platform-
// specific syscalls, and Explain must never create/delete a probe file
// to test writability -- see spec section 47's "no implicit mutation").
type writabilityProbe struct {
writable bool
}
func statInfo(path string) (writabilityProbe, error) {
info, err := os.Stat(path)
if err != nil {
return writabilityProbe{}, err
}
return writabilityProbe{writable: info.Mode().Perm()&0o200 != 0}, nil
}
// FindFile searches dirs (as returned by ConfigSearchDirs/DataSearchDirs/
// ExecutableSearchDirs, or any caller-built list in priority order) for
// name, returning the first directory that contains it. found is false
// if name exists in none of them; this is not an error.
func FindFile(dirs []SearchResult, name string) (result SearchResult, found bool, err error) {
for _, d := range dirs {
candidate := d
joined := JoinDirFile(d.Path, name)
if statExists(joined) {
candidate.Path = joined
candidate.Exists = true
candidate.Selected = true
return candidate, true, nil
}
}
return SearchResult{}, false, nil
}
// FindConfig searches ConfigSearchDirs for a file named name.
func (r *Resolver) FindConfig(name string) (SearchResult, bool, error) {
dirs, err := r.ConfigSearchDirs()
if err != nil {
return SearchResult{}, false, err
}
return FindFile(dirs, name)
}
// FindData searches DataSearchDirs for a file named name.
func (r *Resolver) FindData(name string) (SearchResult, bool, error) {
dirs, err := r.DataSearchDirs()
if err != nil {
return SearchResult{}, false, err
}
return FindFile(dirs, name)
}
// FindExecutable searches ExecutableSearchDirs for a file named name.
func (r *Resolver) FindExecutable(name string) (SearchResult, bool, error) {
dirs, err := r.ExecutableSearchDirs()
if err != nil {
return SearchResult{}, false, err
}
return FindFile(dirs, name)
}
// ensure creates dir (and any missing parents) with perm, matching the
// durable-write conventions used across the Yetano family (AGENTS.md).
// It is a no-op if dir already exists.
func ensure(dir string, perm os.FileMode) (string, error) {
if err := os.MkdirAll(dir, perm); err != nil {
return "", err
}
return dir, nil
}
// EnsureConfigDir creates ConfigDir() (mode 0700) if it does not exist
// and returns its path.
func (r *Resolver) EnsureConfigDir() (string, error) {
dir, err := r.ConfigDir()
if err != nil {
return "", err
}
return ensure(dir, 0o700)
}
// EnsureDataDir creates DataDir() (mode 0700) if it does not exist and
// returns its path.
func (r *Resolver) EnsureDataDir() (string, error) {
dir, err := r.DataDir()
if err != nil {
return "", err
}
return ensure(dir, 0o700)
}
// EnsureStateDir creates StateDir() (mode 0700) if it does not exist and
// returns its path.
func (r *Resolver) EnsureStateDir() (string, error) {
dir, err := r.StateDir()
if err != nil {
return "", err
}
return ensure(dir, 0o700)
}
// EnsureCacheDir creates CacheDir() (mode 0700) if it does not exist and
// returns its path.
func (r *Resolver) EnsureCacheDir() (string, error) {
dir, err := r.CacheDir()
if err != nil {
return "", err
}
return ensure(dir, 0o700)
}
// EnsureRuntimeDir creates RuntimeDir() (mode 0700) if it does not exist
// and returns its path. On Unix, this still fails with
// ErrRuntimeDirUnavailable when no runtime directory could be resolved --
// it does not itself fabricate one.
func (r *Resolver) EnsureRuntimeDir() (string, error) {
dir, err := r.RuntimeDir()
if err != nil {
return "", err
}
return ensure(dir, 0o700)
}
// EnsureLogDir creates LogDir() (mode 0700) if it does not exist and
// returns its path.
func (r *Resolver) EnsureLogDir() (string, error) {
dir, err := r.LogDir()
if err != nil {
return "", err
}
return ensure(dir, 0o700)
}
// EnsureBinDir creates BinDir() (mode 0755, since it holds executables
// meant to be reached via PATH) if it does not exist and returns its
// path.
func (r *Resolver) EnsureBinDir() (string, error) {
dir, err := r.BinDir()
if err != nil {
return "", err
}
return ensure(dir, 0o755)
}
// EnsureLogAlias creates the optional Unix convenience symlink
// LogAliasDir() -> LogDir() (spec section 39), first ensuring LogDir()
// itself exists, and returns LogAliasDir()'s path. On Windows and macOS
// Desktop, LogAliasDir() already equals LogDir() (there is nothing to
// alias), so this is equivalent to EnsureLogDir() there.
//
// A pre-existing entry at LogAliasDir() -- file, directory, or another
// symlink -- is left untouched and reported as success: this method only
// ever creates a genuinely missing alias, never overwrites one (spec
// section 47's "no implicit destructive mutation").
func (r *Resolver) EnsureLogAlias() (string, error) {
logDir, err := r.EnsureLogDir()
if err != nil {
return "", err
}
alias, err := r.LogAliasDir()
if err != nil {
return "", err
}
if alias == logDir {
return logDir, nil
}
if _, err := os.Lstat(alias); err == nil {
return alias, nil
} else if !os.IsNotExist(err) {
return "", err
}
if err := os.MkdirAll(dirName(alias), 0o700); err != nil {
return "", err
}
if err := os.Symlink(logDir, alias); err != nil {
return "", err
}
return alias, nil
}