Add platform-independent path/config resolution library

Implements core/paths (Config/Data/State/Cache/Runtime/Log/Bin
directory resolution with canonical-vs-search-dir separation, XDG on
Unix, native APPDATA/LOCALAPPDATA/PROGRAMDATA layering on Windows,
~/Library on macOS Desktop, injectable environment/platform for
deterministic cross-platform tests) and core/config (file search,
first-match resolution, layered YAML merging, safe ${VAR} expansion,
Explain/doctor introspection) on top of the shared Application/
Kind/Scope model in the core package.
This commit is contained in:
terminar committed 2026-09-19 16:26:01 +02:00
1 parent 027b327c3d
commit 13801bec11
41 files changed
+4834 -2

No files matched your search

+238
View File
@@ -0,0 +1,238 @@
package paths
import "yetano.dev/yetano/core"
// isDarwinDesktop reports whether r resolves for a native macOS GUI
// application, the one combination that diverges from the Unix-family
// (XDG-flavored) layout used everywhere else (spec section 12).
func (r *Resolver) isDarwinDesktop() bool {
return r.isDarwin() && r.app.Kind == core.Desktop
}
// ConfigDir returns the preferred location to write a new user (or,
// under SystemScope, system) configuration file for this application.
// It never creates the directory -- see EnsureConfigDir.
func (r *Resolver) ConfigDir() (string, error) {
v, err := r.configDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) configDirValue() (value, error) {
switch {
case r.isWindows():
return r.configDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopConfigDir()
default:
return r.configDirUnix()
}
}
// DataDir returns the preferred location to write new application data.
func (r *Resolver) DataDir() (string, error) {
v, err := r.dataDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) dataDirValue() (value, error) {
switch {
case r.isWindows():
return r.dataDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopDataDir()
default:
return r.dataDirUnix()
}
}
// StateDir returns the preferred location for application state that
// should persist but is not user-facing configuration (spec section 39).
func (r *Resolver) StateDir() (string, error) {
v, err := r.stateDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) stateDirValue() (value, error) {
switch {
case r.isWindows():
return r.stateDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopStateDir()
default:
return r.stateDirUnix()
}
}
// CacheDir returns the preferred location for disposable cache data.
func (r *Resolver) CacheDir() (string, error) {
v, err := r.cacheDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) cacheDirValue() (value, error) {
switch {
case r.isWindows():
return r.cacheDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopCacheDir()
default:
return r.cacheDirUnix()
}
}
// RuntimeDir returns the preferred location for ephemeral runtime data
// (sockets, PID files, ...). On Unix, without an override and without
// XDG_RUNTIME_DIR set, it returns ErrRuntimeDirUnavailable rather than
// fabricating a fallback (spec section 8) -- callers decide what to do.
func (r *Resolver) RuntimeDir() (string, error) {
v, err := r.runtimeDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) runtimeDirValue() (value, error) {
switch {
case r.isWindows():
return r.runtimeDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopRuntimeDir()
default:
return r.runtimeDirUnix()
}
}
// LogDir returns the preferred location for log files.
func (r *Resolver) LogDir() (string, error) {
v, err := r.logDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) logDirValue() (value, error) {
switch {
case r.isWindows():
return r.logDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopLogDir()
default:
return r.logDirUnix()
}
}
// LogAliasDir returns the optional Unix convenience location
// ~/.local/log/<app> (spec section 39). It is never created
// automatically; nothing else in this package treats it as canonical.
// On Windows and macOS Desktop it is the same as LogDir (there is no
// separate alias convention there).
func (r *Resolver) LogAliasDir() (string, error) {
if r.isWindows() || r.isDarwinDesktop() {
return r.LogDir()
}
v, err := r.logAliasDirUnix()
if err != nil {
return "", err
}
return v.path, nil
}
// BinDir returns the preferred location for installed executables. This
// directory is shared across every Yetano application (spec sections
// 19/38), not namespaced per-app like the other categories.
func (r *Resolver) BinDir() (string, error) {
v, err := r.binDirValue()
if err != nil {
return "", err
}
return v.path, nil
}
func (r *Resolver) binDirValue() (value, error) {
switch {
case r.isWindows():
return r.binDirWindows()
case r.isDarwinDesktop():
return r.darwinDesktopBinDir()
default:
return r.binDirUnix()
}
}
// ConfigSearchDirs returns every location that should be searched for an
// existing configuration *directory*, highest priority first. See
// core/config for turning this into a search over configuration
// *files*.
func (r *Resolver) ConfigSearchDirs() ([]SearchResult, error) {
layers, err := r.configLayers()
if err != nil {
return nil, err
}
return resultsFromLayers(layers), nil
}
func (r *Resolver) configLayers() ([]layer, error) {
switch {
case r.isWindows():
return r.configLayersWindows()
case r.isDarwinDesktop():
return r.darwinDesktopConfigLayers()
default:
return r.configLayersUnix()
}
}
// DataSearchDirs returns every location that should be searched for
// existing application data, highest priority first.
func (r *Resolver) DataSearchDirs() ([]SearchResult, error) {
layers, err := r.dataLayers()
if err != nil {
return nil, err
}
return resultsFromLayers(layers), nil
}
func (r *Resolver) dataLayers() ([]layer, error) {
switch {
case r.isWindows():
return r.dataLayersWindows()
case r.isDarwinDesktop():
return r.darwinDesktopDataLayers()
default:
return r.dataLayersUnix()
}
}
// ExecutableSearchDirs returns every location that should be searched
// for an installed executable, highest priority first -- always
// including both the user and system bin directories under UserScope,
// so a user-scope lookup can find (and prefer) a user install that
// shadows a system-wide one (spec section 36).
func (r *Resolver) ExecutableSearchDirs() ([]SearchResult, error) {
layers, err := r.executableLayers()
if err != nil {
return nil, err
}
return resultsFromLayers(layers), nil
}
func (r *Resolver) executableLayers() ([]layer, error) {
if r.isWindows() {
return r.executableLayersWindows()
}
return r.executableLayersUnix()
}
+213
View File
@@ -0,0 +1,213 @@
package paths
import (
"os"
"testing"
"yetano.dev/yetano/core"
)
func TestResolverAccessors(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(map[string]string{"HOME": "/home/test"}))
if r.Application().Name != "yet" {
t.Errorf("Application().Name = %q, want yet", r.Application().Name)
}
if r.Platform() != "linux" {
t.Errorf("Platform() = %q, want linux", r.Platform())
}
r2, err := For(yetApp(), WithPlatform("linux"), WithEnvironment(map[string]string{"HOME": "/home/test"}))
if err != nil {
t.Fatalf("For: %v", err)
}
if r2.Platform() != "linux" {
t.Errorf("For(...).Platform() = %q, want linux", r2.Platform())
}
}
func TestOSEnvironmentLookup(t *testing.T) {
t.Setenv("YETANO_CORE_TEST_VAR", "hello")
if v, ok := OSEnvironment.Lookup("YETANO_CORE_TEST_VAR"); !ok || v != "hello" {
t.Errorf("OSEnvironment.Lookup() = (%q, %v), want (hello, true)", v, ok)
}
if _, ok := OSEnvironment.Lookup("YETANO_CORE_TEST_VAR_UNSET"); ok {
t.Errorf("OSEnvironment.Lookup() of an unset var returned ok=true")
}
}
func TestAllWithOverrides(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env),
WithDataDir("/api/data"),
WithStateDir("/api/state"),
WithCacheDir("/api/cache"),
WithRuntimeDir("/api/runtime"),
WithLogDir("/api/log"),
WithBinDir("/api/bin"),
)
checks := map[string]func() (string, error){
"/api/data": r.DataDir,
"/api/state": r.StateDir,
"/api/cache": r.CacheDir,
"/api/runtime": r.RuntimeDir,
"/api/log": r.LogDir,
"/api/bin": r.BinDir,
}
for want, fn := range checks {
got, err := fn()
if err != nil {
t.Fatalf("%v", err)
}
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
}
func TestWithEnvPrefixAndEnvironmentProvider(t *testing.T) {
env := MapEnvironment{"HOME": "/home/test", "CUSTOM_CONFIG_HOME": "/custom-prefix/config"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironmentProvider(env), WithEnvPrefix("CUSTOM"))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/custom-prefix/config"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestLogAliasDirUnix(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
got, err := r.LogAliasDir()
if err != nil {
t.Fatalf("LogAliasDir: %v", err)
}
if want := "/home/test/.local/log/yet"; got != want {
t.Errorf("LogAliasDir() = %q, want %q", got, want)
}
}
func TestLogAliasDirWindowsFallsBackToLogDir(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()))
alias, err := r.LogAliasDir()
if err != nil {
t.Fatalf("LogAliasDir: %v", err)
}
log, err := r.LogDir()
if err != nil {
t.Fatalf("LogDir: %v", err)
}
if alias != log {
t.Errorf("LogAliasDir() = %q, want equal to LogDir() = %q", alias, log)
}
}
func TestEnsureAllCategories(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root),
WithRuntimeDir(root+"/runtime-override"))
ensures := []func() (string, error){
r.EnsureConfigDir, r.EnsureDataDir, r.EnsureStateDir,
r.EnsureCacheDir, r.EnsureRuntimeDir, r.EnsureLogDir, r.EnsureBinDir,
}
for _, fn := range ensures {
dir, err := fn()
if err != nil {
t.Fatalf("Ensure: %v", err)
}
info, err := os.Stat(dir)
if err != nil || !info.IsDir() {
t.Errorf("%s was not created as a directory (err=%v)", dir, err)
}
}
}
func TestFindDataAndFindExecutable(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
if _, found, err := r.FindData("plugin.so"); err != nil || found {
t.Fatalf("FindData() = found=%v err=%v, want false", found, err)
}
if _, found, err := r.FindExecutable("yet"); err != nil || found {
t.Fatalf("FindExecutable() = found=%v err=%v, want false", found, err)
}
if _, err := r.EnsureDataDir(); err != nil {
t.Fatal(err)
}
dataDir, _ := r.DataDir()
if err := os.WriteFile(dataDir+"/plugin.so", []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if _, found, err := r.FindData("plugin.so"); err != nil || !found {
t.Fatalf("FindData() = found=%v err=%v, want true", found, err)
}
if _, err := r.EnsureBinDir(); err != nil {
t.Fatal(err)
}
binDir, _ := r.BinDir()
if err := os.WriteFile(binDir+"/yet", []byte("x"), 0o755); err != nil {
t.Fatal(err)
}
if _, found, err := r.FindExecutable("yet"); err != nil || !found {
t.Fatalf("FindExecutable() = found=%v err=%v, want true", found, err)
}
}
func TestDarwinDesktopRemainingCategories(t *testing.T) {
env := map[string]string{"HOME": "/Users/test"}
app := core.Application{Name: "yapama", Kind: core.Desktop}
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(env))
if got, err := r.RuntimeDir(); err != nil || got != "/Users/test/Library/Application Support/yapama/Runtime" {
t.Errorf("RuntimeDir() = (%q, %v)", got, err)
}
if got, err := r.BinDir(); err != nil || got != "/Users/test/.local/bin" {
t.Errorf("BinDir() = (%q, %v)", got, err)
}
dirs, err := r.DataSearchDirs()
if err != nil {
t.Fatalf("DataSearchDirs: %v", err)
}
want := []string{
"/Users/test/Library/Application Support/yapama",
"/Library/Application Support/yapama",
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("DataSearchDirs()[%d] = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestWindowsExecutableSearchDirs(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()))
dirs, err := r.ExecutableSearchDirs()
if err != nil {
t.Fatalf("ExecutableSearchDirs: %v", err)
}
want := []string{
`C:\Users\test\AppData\Local\Yetano\bin`,
`C:\ProgramData\Yetano\bin`,
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("ExecutableSearchDirs()[%d] = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestJoinFamily(t *testing.T) {
if got, want := JoinFamily("windows", ".", "yet.yaml"), `.\yet.yaml`; got != want {
t.Errorf("JoinFamily(windows) = %q, want %q", got, want)
}
if got, want := JoinFamily("linux", ".", "yet.yaml"), "./yet.yaml"; got != want {
t.Errorf("JoinFamily(linux) = %q, want %q", got, want)
}
}
+163
View File
@@ -0,0 +1,163 @@
package paths
import "yetano.dev/yetano/core"
// macOS is deliberately split by ApplicationKind (spec section 12): CLI
// and Service applications use the same XDG-flavored layout as Linux
// (unix.go, via flavor()'s default case) for consistent cross-platform
// administration; only Desktop (native GUI) applications use these
// ~/Library-based conventions.
//
// Config and Data intentionally share one canonical directory (a native
// macOS app's Application Support directory commonly holds both its
// preferences-adjacent files and its bulk data side by side); State gets
// its own subdirectory so it doesn't collide with either.
func darwinAppSupportBase(scope core.Scope, home string) string {
if scope == core.SystemScope {
return "/Library/Application Support"
}
return unixJoin(home, "Library", "Application Support")
}
func darwinCachesBase(scope core.Scope, home string) string {
if scope == core.SystemScope {
return "/Library/Caches"
}
return unixJoin(home, "Library", "Caches")
}
func darwinLogsBase(scope core.Scope, home string) string {
if scope == core.SystemScope {
return "/Library/Logs"
}
return unixJoin(home, "Library", "Logs")
}
// darwinHomeIfNeeded returns "" (unused) for SystemScope, else the real
// home directory -- avoiding a spurious ErrNoHomeDirectory when
// SystemScope is resolved without HOME set.
func (r *Resolver) darwinHomeIfNeeded() (string, error) {
if r.app.Scope == core.SystemScope {
return "", nil
}
return r.homeDir()
}
func (r *Resolver) darwinDesktopAppDir() (value, error) {
if v, ok := r.overrideValue(ConfigPath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
home, err := r.darwinHomeIfNeeded()
if err != nil {
return value{}, err
}
source := MacOSNative
if r.app.Scope == core.SystemScope {
source = SystemDirectory
}
return value{path: r.applyRoot(unixJoin(darwinAppSupportBase(r.app.Scope, home), r.app.Name)), source: source}, nil
}
func (r *Resolver) darwinDesktopConfigDir() (value, error) {
return r.darwinDesktopAppDir()
}
func (r *Resolver) darwinDesktopDataDir() (value, error) {
// Config overrides (WithConfigDir) must not leak into DataDir, so
// DataDir consults its own override tier first.
if v, ok := r.overrideValue(DataPath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
return r.darwinDesktopAppDir()
}
func (r *Resolver) darwinDesktopStateDir() (value, error) {
if v, ok := r.overrideValue(StatePath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
app, err := r.darwinDesktopAppDir()
if err != nil {
return value{}, err
}
return value{path: unixJoin(app.path, "State"), source: app.source}, nil
}
func (r *Resolver) darwinDesktopCacheDir() (value, error) {
if v, ok := r.overrideValue(CachePath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
home, err := r.darwinHomeIfNeeded()
if err != nil {
return value{}, err
}
source := MacOSNative
if r.app.Scope == core.SystemScope {
source = SystemDirectory
}
return value{path: r.applyRoot(unixJoin(darwinCachesBase(r.app.Scope, home), r.app.Name)), source: source}, nil
}
func (r *Resolver) darwinDesktopLogDir() (value, error) {
if v, ok := r.overrideValue(LogPath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
home, err := r.darwinHomeIfNeeded()
if err != nil {
return value{}, err
}
source := MacOSNative
if r.app.Scope == core.SystemScope {
source = SystemDirectory
}
return value{path: r.applyRoot(unixJoin(darwinLogsBase(r.app.Scope, home), r.app.Name)), source: source}, nil
}
func (r *Resolver) darwinDesktopRuntimeDir() (value, error) {
if v, ok := r.overrideValue(RuntimePath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
app, err := r.darwinDesktopAppDir()
if err != nil {
return value{}, err
}
return value{path: unixJoin(app.path, "Runtime"), source: app.source}, nil
}
// darwinDesktopBinDir has no native GUI-app convention; it reuses the
// shared Unix bin directory so a Desktop app that also ships a CLI shim
// still has a sensible, documented answer.
func (r *Resolver) darwinDesktopBinDir() (value, error) {
return r.binDirUnix()
}
func (r *Resolver) darwinDesktopConfigLayers() ([]layer, error) {
return r.darwinDesktopLayers(ConfigPath, darwinAppSupportBase)
}
func (r *Resolver) darwinDesktopDataLayers() ([]layer, error) {
return r.darwinDesktopLayers(DataPath, darwinAppSupportBase)
}
func (r *Resolver) darwinDesktopLayers(kind PathKind, base func(core.Scope, string) string) ([]layer, error) {
if v, ok := r.overrideValue(kind); 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(base(core.UserScope, home), r.app.Name)),
source: MacOSNative,
priority: PriorityUser,
canonical: true,
}}
system := []layer{{
path: r.applyRoot(unixJoin(base(core.SystemScope, ""), r.app.Name)),
source: SystemDirectory,
priority: PrioritySystem,
canonical: r.app.Scope == core.SystemScope,
}}
return composeSearch(user, system, r.app.Scope), nil
}
+95
View File
@@ -0,0 +1,95 @@
package paths
import (
"testing"
"yetano.dev/yetano/core"
)
func TestDarwinCLIUsesXDGLikeLayout(t *testing.T) {
env := map[string]string{"HOME": "/Users/test"}
r := mustResolver(t, yetApp(), WithPlatform("darwin"), WithEnvironment(env))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/Users/test/.config/yet"; got != want {
t.Errorf("ConfigDir() = %q, want %q (macOS CLI should match Linux layout)", got, want)
}
}
func TestDarwinDesktopUsesNativeLayout(t *testing.T) {
env := map[string]string{"HOME": "/Users/test"}
app := core.Application{Name: "yapama", Kind: core.Desktop}
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(env))
checks := []struct {
name string
fn func() (string, error)
want string
}{
{"ConfigDir", r.ConfigDir, "/Users/test/Library/Application Support/yapama"},
{"DataDir", r.DataDir, "/Users/test/Library/Application Support/yapama"},
{"StateDir", r.StateDir, "/Users/test/Library/Application Support/yapama/State"},
{"CacheDir", r.CacheDir, "/Users/test/Library/Caches/yapama"},
{"LogDir", r.LogDir, "/Users/test/Library/Logs/yapama"},
}
for _, c := range checks {
got, err := c.fn()
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if got != c.want {
t.Errorf("%s = %q, want %q", c.name, got, c.want)
}
}
}
func TestDarwinDesktopSystemScope(t *testing.T) {
app := core.Application{Name: "yapama", Kind: core.Desktop, Scope: core.SystemScope}
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(map[string]string{}))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/Library/Application Support/yapama"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestDarwinDesktopConfigSearchDirsUserOverridesSystem(t *testing.T) {
env := map[string]string{"HOME": "/Users/test"}
app := core.Application{Name: "yapama", Kind: core.Desktop}
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(env))
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
want := []string{
"/Users/test/Library/Application Support/yapama",
"/Library/Application Support/yapama",
}
if len(dirs) != len(want) {
t.Fatalf("ConfigSearchDirs() = %v, want %v", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("ConfigSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestDarwinServiceUsesXDGLikeLayout(t *testing.T) {
env := map[string]string{"HOME": "/Users/test"}
app := core.Application{Name: "yasta", Kind: core.Service}
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(env))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/Users/test/.config/yasta"; got != want {
t.Errorf("ConfigDir() = %q, want %q (macOS Service should match Linux layout)", got, want)
}
}
+51
View File
@@ -0,0 +1,51 @@
package paths
import "os"
// Environment provides environment-variable lookups to a Resolver. The
// default (osEnvironment) reads the real process environment; tests (and
// callers simulating another platform) should inject a MapEnvironment
// instead via WithEnvironment, per AGENTS.md's "no unchecked os.Getenv"
// rule for anything that needs deterministic tests.
type Environment interface {
// Lookup returns the environment variable's value and whether it was
// set at all (mirrors os.LookupEnv: unset and set-to-empty are
// distinguishable).
Lookup(key string) (value string, ok bool)
}
// MapEnvironment is an Environment backed by a fixed map, for tests and
// for simulating a platform's environment (e.g. Windows variables while
// running on Linux/macOS).
type MapEnvironment map[string]string
// Lookup implements Environment.
func (m MapEnvironment) Lookup(key string) (string, bool) {
v, ok := m[key]
return v, ok
}
// osEnvironment is the default Environment: the real process environment.
type osEnvironment struct{}
func (osEnvironment) Lookup(key string) (string, bool) {
return os.LookupEnv(key)
}
// OSEnvironment is the real process environment, exported so other
// yetano.dev/yetano/core packages (e.g. core/config) can share the exact
// same default Environment paths.New uses, without reaching for
// os.Getenv themselves.
var OSEnvironment Environment = osEnvironment{}
// lookup is a small convenience over Environment.Lookup that treats a
// set-but-empty variable as "not set", matching how shells and most CLI
// tools treat empty environment overrides (an empty YET_CONFIG_HOME should
// not silently resolve to the filesystem root/current directory).
func lookup(env Environment, key string) (string, bool) {
v, ok := env.Lookup(key)
if !ok || v == "" {
return "", false
}
return v, true
}
+16
View File
@@ -0,0 +1,16 @@
package paths
import "errors"
// ErrRuntimeDirUnavailable is returned by Resolver.RuntimeDir when no
// runtime directory override is set and the platform's native runtime
// directory mechanism (XDG_RUNTIME_DIR on Unix) is not available. Per
// AGENTS.md/spec section 8, this must never be silently papered over with
// a fabricated fallback location -- callers decide what to do (fall back
// to a temp dir themselves, error out, ...).
var ErrRuntimeDirUnavailable = errors.New("paths: runtime directory not available")
// ErrNoHomeDirectory is returned when a computation needs the user's home
// directory (HOME on Unix, USERPROFILE on Windows) and it is not set in
// the Resolver's Environment.
var ErrNoHomeDirectory = errors.New("paths: home directory not available")
+136
View File
@@ -0,0 +1,136 @@
package paths
import (
"fmt"
"strings"
"yetano.dev/yetano/core"
)
// PathInfo is one resolved category in an Explanation (spec section 42).
type PathInfo struct {
Kind PathKind
Path string
Source Source
Scope core.Scope
Exists bool
Writable bool
}
// Explanation is the full, structured report produced by Explain: every
// canonical category this Resolver computed, plus each category's search
// directories. Resolving it never mutates the filesystem (spec section
// 47) beyond the read-only os.Stat calls needed to fill Exists/Writable.
type Explanation struct {
Application core.Application
Platform string
Paths []PathInfo
Search map[PathKind][]SearchResult
}
// writable reports whether dir is writable by attempting to stat it and
// checking a conservative permission bit; a missing directory is
// reported as not writable rather than attempting to create one
// (Explain must never mutate the filesystem).
func writable(dir string) bool {
info, err := statInfo(dir)
if err != nil {
return false
}
return info.writable
}
// Explain resolves every category and returns a structured report
// suitable for a `doctor`-style command. It never creates directories.
func (r *Resolver) Explain() (Explanation, error) {
ex := Explanation{
Application: r.app,
Platform: r.platform,
Search: map[PathKind][]SearchResult{},
}
kinds := []struct {
kind PathKind
fn func() (value, error)
}{
{ConfigPath, r.configDirValue},
{DataPath, r.dataDirValue},
{StatePath, r.stateDirValue},
{CachePath, r.cacheDirValue},
{RuntimePath, r.runtimeDirValue},
{LogPath, r.logDirValue},
{BinPath, r.binDirValue},
}
for _, k := range kinds {
v, err := k.fn()
if err != nil {
if k.kind == RuntimePath && err == ErrRuntimeDirUnavailable {
ex.Paths = append(ex.Paths, PathInfo{Kind: k.kind, Scope: r.app.Scope})
continue
}
return Explanation{}, fmt.Errorf("explain %s: %w", k.kind, err)
}
ex.Paths = append(ex.Paths, PathInfo{
Kind: k.kind,
Path: v.path,
Source: v.source,
Scope: r.app.Scope,
Exists: statExists(v.path),
Writable: writable(v.path),
})
}
searchKinds := []struct {
kind PathKind
fn func() ([]SearchResult, error)
}{
{ConfigPath, r.ConfigSearchDirs},
{DataPath, r.DataSearchDirs},
{BinPath, r.ExecutableSearchDirs},
}
for _, k := range searchKinds {
results, err := k.fn()
if err != nil {
return Explanation{}, fmt.Errorf("explain %s search dirs: %w", k.kind, err)
}
ex.Search[k.kind] = results
}
return ex, nil
}
// String renders a human-readable report similar to spec sections 44/45.
func (e Explanation) String() string {
var b strings.Builder
fmt.Fprintf(&b, "Application: %s\n", e.Application.Name)
fmt.Fprintf(&b, "Kind: %s\n", e.Application.Kind)
fmt.Fprintf(&b, "Scope: %s\n", e.Application.Scope)
fmt.Fprintf(&b, "Platform: %s\n\n", e.Platform)
for _, p := range e.Paths {
if p.Path == "" {
fmt.Fprintf(&b, "%s:\n unavailable\n\n", p.Kind)
continue
}
fmt.Fprintf(&b, "%s:\n %s\n source: %s\n exists: %t\n writable: %t\n\n",
p.Kind, p.Path, p.Source, p.Exists, p.Writable)
}
for _, kind := range []PathKind{ConfigPath, DataPath, BinPath} {
results, ok := e.Search[kind]
if !ok {
continue
}
fmt.Fprintf(&b, "%s search:\n", kind)
for _, res := range results {
marker := " "
if res.Selected {
marker = "*"
}
fmt.Fprintf(&b, " %s %s (source: %s, exists: %t)\n", marker, res.Path, res.Source, res.Exists)
}
b.WriteString("\n")
}
return b.String()
}
+55
View File
@@ -0,0 +1,55 @@
package paths
import (
"os"
"strings"
"testing"
)
func TestExplainLinux(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
ex, err := r.Explain()
if err != nil {
t.Fatalf("Explain: %v", err)
}
if ex.Application.Name != "yet" {
t.Errorf("Explain().Application.Name = %q, want yet", ex.Application.Name)
}
var configPath string
for _, p := range ex.Paths {
if p.Kind == ConfigPath {
configPath = p.Path
}
if p.Kind == RuntimePath && p.Path != "" {
t.Errorf("expected RuntimePath to be unavailable (no XDG_RUNTIME_DIR), got %q", p.Path)
}
}
if configPath != "/home/test/.config/yet" {
t.Errorf("Explain() config path = %q, want /home/test/.config/yet", configPath)
}
text := ex.String()
if !strings.Contains(text, "yet") || !strings.Contains(text, "config") {
t.Errorf("Explain().String() missing expected content:\n%s", text)
}
}
func TestExplainNeverMutatesFilesystem(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
if _, err := r.Explain(); err != nil {
t.Fatalf("Explain: %v", err)
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Errorf("Explain() created filesystem entries under root: %v", entries)
}
}
+17
View File
@@ -0,0 +1,17 @@
package paths
// freebsdFlavor follows FreeBSD/ports conventions rather than blindly
// reusing Linux's FHS layout (spec section 33/56): system configuration
// and locally-installed data live under /usr/local, not /etc or
// /usr/share, and system-writable application data conventionally lives
// under /var/db rather than /var/lib.
var freebsdFlavor = unixFlavor{
systemConfigDirs: []string{"/usr/local/etc"},
systemDataDirs: []string{"/usr/local/share", "/usr/share"},
systemDataBase: "/var/db",
systemStateBase: "/var/db",
systemCacheBase: "/var/cache",
systemRuntimeBase: "/var/run",
systemLogBase: "/var/log",
systemBinDir: "/usr/local/bin",
}
+136
View File
@@ -0,0 +1,136 @@
package paths
import "strings"
// Path joining is implemented per address-family (unix "/" vs. windows
// "\") rather than via package path/filepath, deliberately: filepath's
// behavior depends on the host GOOS, but a Resolver must be able to
// compute Windows paths while running on Linux/macOS (and vice versa) so
// that platform logic is unit-testable on every host -- see
// WithPlatform and AGENTS.md's "OS specific logic isolated" rule.
// unixJoin joins elements with "/", collapsing empty elements and
// duplicate slashes at the seams. The first element determines whether
// the result is absolute.
func unixJoin(elems ...string) string {
parts := make([]string, 0, len(elems))
for i, e := range elems {
e = strings.Trim(e, "/")
if e == "" {
continue
}
if i == 0 && strings.HasPrefix(elems[0], "/") {
e = "/" + e
}
parts = append(parts, e)
}
joined := strings.Join(parts, "/")
if len(elems) > 0 && strings.HasPrefix(elems[0], "/") && !strings.HasPrefix(joined, "/") {
joined = "/" + joined
}
if joined == "" && len(elems) > 0 && elems[0] == "/" {
return "/"
}
return joined
}
// windowsJoin joins elements with "\", preserving a leading drive letter
// or UNC prefix on the first element.
func windowsJoin(elems ...string) string {
if len(elems) == 0 {
return ""
}
// A UNC prefix ("\\server\share") is two significant leading
// backslashes; strip and preserve it separately so the trim loop
// below (which treats a run of backslashes as a plain separator)
// doesn't collapse it down to zero, losing the UNC-ness of the path.
uncPrefix := ""
first := elems[0]
if rest, ok := strings.CutPrefix(first, `\\`); ok {
uncPrefix = `\\`
first = rest
}
nonEmpty := make([]string, 0, len(elems))
for i, e := range elems {
if i == 0 {
e = first
}
e = strings.Trim(e, `\`)
if e != "" {
nonEmpty = append(nonEmpty, e)
}
}
return uncPrefix + strings.Join(nonEmpty, `\`)
}
// JoinFamily joins elems using platform's address family ("windows":
// backslash; anything else: forward slash) rather than the *dir*-content
// heuristic JoinDirFile uses -- needed when an element (e.g. a bare ".")
// carries no separator of its own to infer a family from, such as
// core/config's default working-directory layer.
func JoinFamily(platform string, elems ...string) string {
if platform == "windows" {
return windowsJoin(elems...)
}
return unixJoin(elems...)
}
// JoinDirFile joins a directory (as produced by ConfigSearchDirs/
// DataSearchDirs/ExecutableSearchDirs, in either address family) with a
// plain file name, picking the join style from the directory's own
// separators rather than the host OS. Exported so core/config can build
// file paths from these directories without re-implementing the
// address-family detection.
func JoinDirFile(dir, name string) string {
if strings.ContainsRune(dir, '\\') && !strings.ContainsRune(dir, '/') {
return windowsJoin(dir, name)
}
return unixJoin(dir, name)
}
// splitWindowsRoot separates a Windows absolute path's root (a drive
// letter like "C:" or a UNC share like "\\server\share") from the
// remainder, so WithRoot can rebase the remainder under a portable root.
// It returns ok=false for a path it doesn't recognize as rooted.
func splitWindowsRoot(p string) (root, rest string, ok bool) {
if trimmed, ok := strings.CutPrefix(p, `\\`); ok {
// UNC: \\server\share\rest...
parts := strings.SplitN(trimmed, `\`, 3)
switch len(parts) {
case 0, 1:
return "", "", false
case 2:
return `\\` + parts[0] + `\` + parts[1], "", true
default:
return `\\` + parts[0] + `\` + parts[1], parts[2], true
}
}
if len(p) >= 2 && p[1] == ':' {
rest := strings.TrimPrefix(p[2:], `\`)
return p[:2], rest, true
}
return "", "", false
}
// applyRootUnix rebases an absolute unix-family path under root, when
// root is set. An empty root leaves p untouched.
func applyRootUnix(root, p string) string {
if root == "" {
return p
}
return unixJoin(root, strings.TrimPrefix(p, "/"))
}
// applyRootWindows rebases an absolute windows-family path under root,
// when root is set. An empty root leaves p untouched.
func applyRootWindows(root, p string) string {
if root == "" {
return p
}
_, rest, ok := splitWindowsRoot(p)
if !ok {
return windowsJoin(root, p)
}
return windowsJoin(root, rest)
}
+89
View File
@@ -0,0 +1,89 @@
package paths
import "testing"
func TestUnixJoin(t *testing.T) {
cases := []struct {
elems []string
want string
}{
{[]string{"/etc", "yet"}, "/etc/yet"},
{[]string{"/", "etc", "yet"}, "/etc/yet"},
{[]string{"relative", "path"}, "relative/path"},
{[]string{"/a/", "/b/", "c"}, "/a/b/c"},
}
for _, c := range cases {
if got := unixJoin(c.elems...); got != c.want {
t.Errorf("unixJoin(%v) = %q, want %q", c.elems, got, c.want)
}
}
}
func TestWindowsJoin(t *testing.T) {
cases := []struct {
elems []string
want string
}{
{[]string{`C:\Users\test`, "yet"}, `C:\Users\test\yet`},
{[]string{`C:\Users\test\`, `\yet\`}, `C:\Users\test\yet`},
{[]string{`\\server\share`, "yet"}, `\\server\share\yet`},
{[]string{"relative", "path"}, `relative\path`},
}
for _, c := range cases {
if got := windowsJoin(c.elems...); got != c.want {
t.Errorf("windowsJoin(%v) = %q, want %q", c.elems, got, c.want)
}
}
}
func TestSplitWindowsRoot(t *testing.T) {
cases := []struct {
path string
wantRoot string
wantRest string
wantOK bool
}{
{`C:\Users\test\yet`, `C:`, `Users\test\yet`, true},
{`C:\`, `C:`, ``, true},
{`\\server\share\yet`, `\\server\share`, `yet`, true},
{`\\server\share`, `\\server\share`, ``, true},
{`relative\path`, "", "", false},
}
for _, c := range cases {
root, rest, ok := splitWindowsRoot(c.path)
if ok != c.wantOK || root != c.wantRoot || rest != c.wantRest {
t.Errorf("splitWindowsRoot(%q) = (%q, %q, %v), want (%q, %q, %v)",
c.path, root, rest, ok, c.wantRoot, c.wantRest, c.wantOK)
}
}
}
func TestApplyRootUnix(t *testing.T) {
if got, want := applyRootUnix("", "/etc/yet"), "/etc/yet"; got != want {
t.Errorf("applyRootUnix(\"\", ...) = %q, want %q", got, want)
}
if got, want := applyRootUnix("/tmp/root", "/etc/yet"), "/tmp/root/etc/yet"; got != want {
t.Errorf("applyRootUnix = %q, want %q", got, want)
}
}
func TestApplyRootWindows(t *testing.T) {
if got, want := applyRootWindows("", `C:\ProgramData\yet`), `C:\ProgramData\yet`; got != want {
t.Errorf("applyRootWindows(\"\", ...) = %q, want %q", got, want)
}
if got, want := applyRootWindows(`C:\sandbox`, `C:\ProgramData\yet`), `C:\sandbox\ProgramData\yet`; got != want {
t.Errorf("applyRootWindows = %q, want %q", got, want)
}
if got, want := applyRootWindows(`C:\sandbox`, `\\server\share\yet`), `C:\sandbox\yet`; got != want {
t.Errorf("applyRootWindows(UNC) = %q, want %q", got, want)
}
}
func TestJoinDirFile(t *testing.T) {
if got, want := JoinDirFile("/etc/yet", "yet.yaml"), "/etc/yet/yet.yaml"; got != want {
t.Errorf("JoinDirFile(unix) = %q, want %q", got, want)
}
if got, want := JoinDirFile(`C:\ProgramData\yet`, "yet.yaml"), `C:\ProgramData\yet\yet.yaml`; got != want {
t.Errorf("JoinDirFile(windows) = %q, want %q", got, want)
}
}
+81
View File
@@ -0,0 +1,81 @@
//go:build windows
package paths
import (
"syscall"
"unsafe"
)
// This file supplies the optional, best-effort Windows known-folder
// lookup mentioned in windows.go: it is only ever consulted when an
// environment variable (APPDATA/LOCALAPPDATA/PROGRAMDATA) is not set and
// this process is actually running on Windows (not merely simulating it
// via WithPlatform, which never sets nativeKnownFolder's caller
// condition to true on a non-Windows GOOS build in the first place).
//
// It calls SHGetKnownFolderPath directly via syscall rather than adding
// a dependency (e.g. golang.org/x/sys/windows), per AGENTS.md's "as few
// external dependencies as possible" guidance -- this is the one place
// in the module that needs it.
var (
knownFolderRoaming = syscall.GUID{Data1: 0x3EB685DB, Data2: 0x65F9, Data3: 0x4CF6, Data4: [8]byte{0xA0, 0x3A, 0xE3, 0xEF, 0x65, 0x72, 0x9F, 0x3D}}
knownFolderLocal = syscall.GUID{Data1: 0xF1B32785, Data2: 0x6FBA, Data3: 0x4FCF, Data4: [8]byte{0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91}}
knownFolderProgData = syscall.GUID{Data1: 0x62AB5D82, Data2: 0xFDC1, Data3: 0x4DC3, Data4: [8]byte{0xA9, 0xDD, 0x07, 0x0D, 0x1D, 0x49, 0x5D, 0x97}}
)
func init() {
nativeKnownFolder = lookupKnownFolder
}
func lookupKnownFolder(envVar string) (string, bool) {
var guid *syscall.GUID
switch envVar {
case "APPDATA":
guid = &knownFolderRoaming
case "LOCALAPPDATA":
guid = &knownFolderLocal
case "PROGRAMDATA":
guid = &knownFolderProgData
default:
return "", false
}
shell32 := syscall.NewLazyDLL("shell32.dll")
proc := shell32.NewProc("SHGetKnownFolderPath")
if proc.Find() != nil {
return "", false
}
ole32 := syscall.NewLazyDLL("ole32.dll")
coTaskMemFree := ole32.NewProc("CoTaskMemFree")
var pathPtr uintptr
ret, _, _ := proc.Call(
uintptr(unsafe.Pointer(guid)),
0, // dwFlags
0, // hToken (current user)
uintptr(unsafe.Pointer(&pathPtr)),
)
if ret != 0 || pathPtr == 0 {
return "", false
}
defer coTaskMemFree.Call(pathPtr)
// Manually walk the UTF-16, NUL-terminated string CoTaskMemFree owns.
// `go vet` flags this uintptr->Pointer conversion (unsafeptr): pathPtr
// is a raw address handed back by the syscall, not derived from a Go
// pointer, so vet cannot prove it safe -- this is the same accepted,
// unavoidable pattern the standard syscall package itself uses for
// manual Windows API interop without golang.org/x/sys/windows.
base := unsafe.Pointer(pathPtr) //nolint:unsafeptr
var chars []uint16
for i := 0; ; i++ {
c := *(*uint16)(unsafe.Add(base, i*2))
if c == 0 {
break
}
chars = append(chars, c)
}
return syscall.UTF16ToString(chars), true
}
+114
View File
@@ -0,0 +1,114 @@
package paths
import "yetano.dev/yetano/core"
// layer is one directory in a search/priority hierarchy (see
// AGENTS.md-style docs in paths.go: "canonical path vs. search paths").
// Search order is descending priority; merge order (used by core/config)
// is the reverse.
type layer struct {
path string
source Source
priority int
canonical bool
}
// Priority constants shared with core/config, which adds the working
// directory layer (always PriorityWorkingDirectory) on top of whatever
// paths.Resolver reports for the user/system layers.
const (
PriorityWorkingDirectory = 100
PriorityUserLocal = 90 // Windows-only machine-local override layer
PriorityUser = 80
PrioritySystem = 10
)
// composeSearch applies the one Scope rule used across every search-dir
// category (Config, Data, Executable): SystemScope resolves only the
// system tier (a system-scope process, e.g. a system service, has no
// meaningful per-user home directory); UserScope resolves the user
// tier(s) plus the system tier as a lower-priority fallback, so a
// system-wide default can still be found -- and, per spec section 36,
// a user installation overrides a system one.
func composeSearch(user, system []layer, scope core.Scope) []layer {
if scope == core.SystemScope {
return system
}
out := make([]layer, 0, len(user)+len(system))
out = append(out, user...)
out = append(out, system...)
return out
}
// envSuffix maps each category to the "_HOME" suffix used to build its
// YETANO_*/<PREFIX>_* environment variable names (e.g. ConfigPath ->
// "YETANO_CONFIG_HOME" / "YET_CONFIG_HOME").
var envSuffix = map[PathKind]string{
ConfigPath: "CONFIG_HOME",
DataPath: "DATA_HOME",
StatePath: "STATE_HOME",
CachePath: "CACHE_HOME",
RuntimePath: "RUNTIME_HOME",
LogPath: "LOG_HOME",
BinPath: "BIN_HOME",
}
// appendsAppName reports whether the YetanoEnvironment/platform-native/
// PlatformDefault tiers for kind are treated as a *base* directory that
// the application name is joined onto (true, e.g. XDG_CONFIG_HOME) or as
// an already-final, shared directory used as-is (false; only BinPath: a
// bin directory is conventionally shared across every application on the
// machine, like ~/.local/bin, not namespaced per app).
//
// APIOverride and AppEnvironment are always used as-is for every
// category, regardless of appendsAppName -- an explicit or app-specific
// override already names an exact directory; it would be surprising for
// "YET_CONFIG_HOME=/foo" to actually mean "/foo/yet".
func appendsAppName(kind PathKind) bool {
return kind != BinPath
}
// overrideValue resolves tiers 1-3 of the override chain (API override,
// app-specific environment, shared YETANO_* environment) for kind. ok is
// false if none of these tiers is set, meaning the caller must fall back
// to its own platform-native tier 4 / default tier 5.
func (r *Resolver) overrideValue(kind PathKind) (v value, ok bool) {
if explicit, set := r.overrides[kind]; set {
return value{path: explicit, source: APIOverride}, true
}
suffix := envSuffix[kind]
if r.envPrefix != "" {
if v, set := lookup(r.env, r.envPrefix+"_"+suffix); set {
return value{path: v, source: AppEnvironment}, true
}
}
if v, set := lookup(r.env, "YETANO_"+suffix); set {
base := v
if appendsAppName(kind) {
base = r.join(v, r.app.Name)
}
return value{path: base, source: YetanoEnvironment}, true
}
return value{}, false
}
// join joins path elements using the address family of r.platform
// (windows: backslash; everything else: forward slash) -- see join.go.
func (r *Resolver) join(elems ...string) string {
if r.isWindows() {
return windowsJoin(elems...)
}
return unixJoin(elems...)
}
func (r *Resolver) isWindows() bool { return r.platform == "windows" }
func (r *Resolver) isDarwin() bool { return r.platform == "darwin" }
// applyRoot rebases an absolute path under the portable root (WithRoot),
// if one is set, using the same address family as r.platform.
func (r *Resolver) applyRoot(p string) string {
if r.isWindows() {
return applyRootWindows(r.root, p)
}
return applyRootUnix(r.root, p)
}
+16
View File
@@ -0,0 +1,16 @@
package paths
// linuxFlavor implements Linux's Filesystem Hierarchy Standard
// conventions for SystemScope, and is also the fallback used for any
// other Unix-family GOOS this package does not yet tune individually
// (see AGENTS.md TODO: "further Unix/BSD platforms without a redesign").
var linuxFlavor = unixFlavor{
systemConfigDirs: []string{"/etc"},
systemDataDirs: []string{"/usr/local/share", "/usr/share"},
systemDataBase: "/var/lib",
systemStateBase: "/var/lib",
systemCacheBase: "/var/cache",
systemRuntimeBase: "/run",
systemLogBase: "/var/log",
systemBinDir: "/usr/local/bin",
}
+153
View File
@@ -0,0 +1,153 @@
// Package paths resolves the filesystem locations a Yetano application
// uses for configuration, data, state, cache, runtime, log, and
// executable files -- platform-independently, without parsing or knowing
// anything about configuration file contents (that is core/config's job).
//
// The central type is Resolver, obtained via For (or New):
//
// app := core.Application{Name: "yet", Kind: core.CLI}
// resolver := paths.For(app)
//
// dir, err := resolver.ConfigDir() // canonical write location
// dirs, err := resolver.ConfigSearchDirs() // all locations to search, in priority order
//
// # Canonical directory vs. search directories
//
// Every category (Config, Data, State, Cache, Runtime, Log, Bin) has two
// APIs:
//
// - <Category>Dir() returns the single, preferred location a new file
// in that category would be written to.
// - <Category>SearchDirs() returns every location that should be
// searched for an existing file, ordered from highest to lowest
// priority (a "first match wins" order).
//
// These are not always the same location. On Windows in particular, the
// canonical ConfigDir() is the roaming %APPDATA%\<app> directory, while
// ConfigSearchDirs() additionally includes %LOCALAPPDATA%\<app> (a
// machine-specific override layer, checked first) and %PROGRAMDATA%\<app>
// (a system-wide default layer, checked last). See the package README for
// the full priority tables.
//
// # No implicit filesystem mutation
//
// Resolving a path never creates a directory or file. To create one
// explicitly, use the Ensure* methods (e.g. EnsureConfigDir).
//
// # Environment variable priority
//
// Every canonical category is resolved through the same override chain,
// highest priority first:
//
// 1. an explicit option passed to New/For (e.g. WithConfigDir)
// 2. the application-specific environment variable (e.g. YET_CONFIG_HOME)
// 3. the shared YETANO_* environment variable (e.g. YETANO_CONFIG_HOME)
// 4. the platform-native mechanism (XDG_CONFIG_HOME, a Windows known
// folder, native macOS paths, ...)
// 5. the platform default
package paths
// PathKind identifies which directory category a PathInfo or SearchResult
// describes.
type PathKind int
const (
ConfigPath PathKind = iota
DataPath
StatePath
CachePath
RuntimePath
LogPath
BinPath
)
// String returns the lowercase category name used in Explain output.
func (k PathKind) String() string {
switch k {
case ConfigPath:
return "config"
case DataPath:
return "data"
case StatePath:
return "state"
case CachePath:
return "cache"
case RuntimePath:
return "runtime"
case LogPath:
return "log"
case BinPath:
return "bin"
default:
return "unknown"
}
}
// Source names where a resolved path's value came from, for
// Explain/doctor-style introspection.
type Source int
const (
// APIOverride: an explicit option (e.g. WithConfigDir) was passed to
// New/For.
APIOverride Source = iota
// AppEnvironment: the application-specific environment variable
// (e.g. YET_CONFIG_HOME) was set.
AppEnvironment
// YetanoEnvironment: the shared YETANO_* environment variable (e.g.
// YETANO_CONFIG_HOME) was set.
YetanoEnvironment
// XDGEnvironment: an XDG_* environment variable was set (Unix-family
// platforms only).
XDGEnvironment
// WindowsKnownFolder: resolved from a Windows known folder
// (%APPDATA%, %LOCALAPPDATA%, %PROGRAMDATA%, ...).
WindowsKnownFolder
// MacOSNative: resolved from a native macOS location (~/Library/...).
MacOSNative
// PlatformDefault: no override applied; the platform's built-in
// default was used (e.g. ~/.config on Linux with no XDG_CONFIG_HOME).
PlatformDefault
// WorkingDirectory: the process's current working directory.
WorkingDirectory
// SystemDirectory: a fixed system-wide location (e.g. /etc, /var/lib)
// used for SystemScope.
SystemDirectory
// PortableRoot: WithRoot redirected the resolved path under a
// portable/test root.
PortableRoot
)
// String returns the lowercase source name used in Explain output.
func (s Source) String() string {
switch s {
case APIOverride:
return "api-override"
case AppEnvironment:
return "app-environment"
case YetanoEnvironment:
return "yetano-environment"
case XDGEnvironment:
return "xdg-environment"
case WindowsKnownFolder:
return "windows-known-folder"
case MacOSNative:
return "macos-native"
case PlatformDefault:
return "platform-default"
case WorkingDirectory:
return "working-directory"
case SystemDirectory:
return "system-directory"
case PortableRoot:
return "portable-root"
default:
return "unknown"
}
}
// value is an internal helper: a resolved string plus where it came from.
type value struct {
path string
source Source
}
+133
View File
@@ -0,0 +1,133 @@
package paths
import (
"runtime"
"yetano.dev/yetano/core"
)
// Resolver computes filesystem paths for one Application. Obtain one with
// New or For; a Resolver is immutable and safe for concurrent use once
// constructed.
type Resolver struct {
app core.Application
env Environment
platform string // runtime.GOOS-shaped; see WithPlatform
root string
envPrefix string
overrides map[PathKind]string
}
// Option configures a Resolver constructed by New/For.
type Option func(*Resolver)
// New constructs a Resolver for app. It validates app (see
// Application.Validate) and applies opts in order.
func New(app core.Application, opts ...Option) (*Resolver, error) {
if err := app.Validate(); err != nil {
return nil, err
}
r := &Resolver{
app: app,
env: osEnvironment{},
platform: runtime.GOOS,
envPrefix: app.EnvPrefix(),
overrides: map[PathKind]string{},
}
for _, opt := range opts {
opt(r)
}
return r, nil
}
// For is an alias for New, matching the spec's `paths.For(app)` spelling.
func For(app core.Application, opts ...Option) (*Resolver, error) {
return New(app, opts...)
}
// Application returns the Application this Resolver was built for.
func (r *Resolver) Application() core.Application { return r.app }
// Platform returns the platform family this Resolver resolves paths for
// (runtime.GOOS by default; see WithPlatform).
func (r *Resolver) Platform() string { return r.platform }
// WithEnvironment injects a fixed environment variable map, for tests
// and for simulating another platform's environment. It replaces any
// previously set environment provider.
func WithEnvironment(env map[string]string) Option {
return func(r *Resolver) { r.env = MapEnvironment(env) }
}
// WithEnvironmentProvider injects a custom Environment implementation.
func WithEnvironmentProvider(env Environment) Option {
return func(r *Resolver) { r.env = env }
}
// WithPlatform overrides the platform family used for resolution
// (normally runtime.GOOS): "linux", "darwin", "freebsd", "windows", or
// any other GOOS value (treated as a generic Unix variant). This exists
// so platform logic can be unit-tested deterministically on any host --
// combine with WithEnvironment to simulate e.g. Windows env vars while
// running the tests on Linux/macOS. It only affects path *computation*;
// Ensure* methods still perform real filesystem I/O using the host's
// native os.MkdirAll, so combining WithPlatform (to a non-native
// platform) with the Ensure* methods is not meaningful and is the
// caller's responsibility to avoid.
func WithPlatform(goos string) Option {
return func(r *Resolver) { r.platform = goos }
}
// WithRoot rebases every resolved absolute path under root, stripping
// the original path's volume/leading separator first (e.g. "/etc/yet"
// under root "/tmp/sandbox" becomes "/tmp/sandbox/etc/yet"). root must be
// given in the same address family as the platform being resolved for
// (forward slashes for Unix, backslashes -- optionally with a drive
// letter or UNC prefix -- for Windows). Useful for tests, containers, and
// a future portable install mode.
func WithRoot(root string) Option {
return func(r *Resolver) { r.root = root }
}
// WithEnvPrefix overrides the application-specific environment variable
// prefix (default: Application.EnvPrefix(), e.g. "YET"). The prefix is
// used as "<PREFIX>_CONFIG_HOME", "<PREFIX>_DATA_HOME", etc.
func WithEnvPrefix(prefix string) Option {
return func(r *Resolver) { r.envPrefix = prefix }
}
// WithoutAppEnv disables the application-specific environment variable
// tier entirely, so only the shared YETANO_* variables (and below) are
// consulted.
func WithoutAppEnv() Option {
return func(r *Resolver) { r.envPrefix = "" }
}
// withOverride sets an explicit, highest-priority value for one
// category. Used by the WithConfigDir/WithDataDir/... family below.
func withOverride(kind PathKind, path string) Option {
return func(r *Resolver) { r.overrides[kind] = path }
}
// WithConfigDir explicitly overrides ConfigDir (and makes it the sole,
// highest-priority entry in ConfigSearchDirs).
func WithConfigDir(path string) Option { return withOverride(ConfigPath, path) }
// WithDataDir explicitly overrides DataDir.
func WithDataDir(path string) Option { return withOverride(DataPath, path) }
// WithStateDir explicitly overrides StateDir.
func WithStateDir(path string) Option { return withOverride(StatePath, path) }
// WithCacheDir explicitly overrides CacheDir.
func WithCacheDir(path string) Option { return withOverride(CachePath, path) }
// WithRuntimeDir explicitly overrides RuntimeDir, and makes it available
// even when the platform's native runtime directory mechanism is not.
func WithRuntimeDir(path string) Option { return withOverride(RuntimePath, path) }
// WithLogDir explicitly overrides LogDir.
func WithLogDir(path string) Option { return withOverride(LogPath, path) }
// WithBinDir explicitly overrides BinDir.
func WithBinDir(path string) Option { return withOverride(BinPath, path) }
+192
View File
@@ -0,0 +1,192 @@
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)
}
+85
View File
@@ -0,0 +1,85 @@
package paths
import (
"os"
"path/filepath"
"testing"
)
func TestFindConfigFirstMatch(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
// Nothing exists yet.
if _, found, err := r.FindConfig("yet.yaml"); err != nil || found {
t.Fatalf("FindConfig() = found=%v err=%v, want found=false", found, err)
}
if err := os.MkdirAll(filepath.Join(root, "etc", "yet"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "etc", "yet", "yet.yaml"), []byte("system: true\n"), 0o644); err != nil {
t.Fatal(err)
}
result, found, err := r.FindConfig("yet.yaml")
if err != nil || !found {
t.Fatalf("FindConfig() = found=%v err=%v, want found=true", found, err)
}
if result.Source != SystemDirectory {
t.Errorf("FindConfig() source = %v, want SystemDirectory", result.Source)
}
// Now also create the higher-priority user config; it should win.
if err := os.MkdirAll(filepath.Join(root, "home", "test", ".config", "yet"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), []byte("user: true\n"), 0o644); err != nil {
t.Fatal(err)
}
result, found, err = r.FindConfig("yet.yaml")
if err != nil || !found {
t.Fatalf("FindConfig() = found=%v err=%v, want found=true", found, err)
}
if result.Source == SystemDirectory {
t.Errorf("FindConfig() should prefer the user layer once it exists, got source=%v path=%v", result.Source, result.Path)
}
}
func TestEnsureConfigDirCreatesDirectory(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
dir, err := r.EnsureConfigDir()
if err != nil {
t.Fatalf("EnsureConfigDir: %v", err)
}
info, err := os.Stat(dir)
if err != nil {
t.Fatalf("stat %s: %v", dir, err)
}
if !info.IsDir() {
t.Errorf("%s is not a directory", dir)
}
}
func TestEnsureRuntimeDirPropagatesUnavailable(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
if _, err := r.EnsureRuntimeDir(); err != ErrRuntimeDirUnavailable {
t.Fatalf("EnsureRuntimeDir() error = %v, want ErrRuntimeDirUnavailable", err)
}
}
func TestFindFileNotFoundIsNotAnError(t *testing.T) {
dirs := []SearchResult{{Path: "/does/not/exist", Source: SystemDirectory}}
_, found, err := FindFile(dirs, "missing.yaml")
if err != nil {
t.Fatalf("FindFile() error = %v, want nil", err)
}
if found {
t.Fatalf("FindFile() found = true, want false")
}
}
+256
View File
@@ -0,0 +1,256 @@
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; join the "log" suffix onto
// the already-rooted path so it isn't rebased twice.
return value{path: unixJoin(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
}
+323
View File
@@ -0,0 +1,323 @@
package paths
import (
"testing"
"yetano.dev/yetano/core"
)
func yetApp() core.Application {
return core.Application{Name: "yet", Kind: core.CLI}
}
func mustResolver(t *testing.T, app core.Application, opts ...Option) *Resolver {
t.Helper()
r, err := New(app, opts...)
if err != nil {
t.Fatalf("New: %v", err)
}
return r
}
func TestLinuxDefaults(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
checks := []struct {
name string
fn func() (string, error)
want string
}{
{"ConfigDir", r.ConfigDir, "/home/test/.config/yet"},
{"DataDir", r.DataDir, "/home/test/.local/share/yet"},
{"StateDir", r.StateDir, "/home/test/.local/state/yet"},
{"CacheDir", r.CacheDir, "/home/test/.cache/yet"},
{"LogDir", r.LogDir, "/home/test/.local/state/yet/log"},
{"BinDir", r.BinDir, "/home/test/.local/bin"},
}
for _, c := range checks {
got, err := c.fn()
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if got != c.want {
t.Errorf("%s = %q, want %q", c.name, got, c.want)
}
}
}
func TestLinuxRuntimeDirUnavailableWithoutXDG(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
if _, err := r.RuntimeDir(); err != ErrRuntimeDirUnavailable {
t.Fatalf("RuntimeDir() error = %v, want ErrRuntimeDirUnavailable", err)
}
}
func TestLinuxRuntimeDirFromXDG(t *testing.T) {
env := map[string]string{"HOME": "/home/test", "XDG_RUNTIME_DIR": "/run/user/1000"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
got, err := r.RuntimeDir()
if err != nil {
t.Fatalf("RuntimeDir: %v", err)
}
if want := "/run/user/1000/yet"; got != want {
t.Errorf("RuntimeDir() = %q, want %q", got, want)
}
}
func TestXDGOverride(t *testing.T) {
env := map[string]string{"HOME": "/home/test", "XDG_CONFIG_HOME": "/custom/config"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/custom/config/yet"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestYetanoOverrideWinsOverXDG(t *testing.T) {
env := map[string]string{
"HOME": "/home/test",
"XDG_CONFIG_HOME": "/custom/config",
"YETANO_CONFIG_HOME": "/yetano/config",
}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/yetano/config/yet"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestAppOverrideWinsOverYetano(t *testing.T) {
env := map[string]string{
"HOME": "/home/test",
"XDG_CONFIG_HOME": "/custom/config",
"YETANO_CONFIG_HOME": "/yetano/config",
"YET_CONFIG_HOME": "/yet/config",
}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
// App-specific overrides are used as-is (no "/yet" suffix appended):
// the variable's own name already names the application.
if want := "/yet/config"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestAPIOverrideWinsOverEverything(t *testing.T) {
env := map[string]string{
"HOME": "/home/test",
"XDG_CONFIG_HOME": "/custom/config",
"YETANO_CONFIG_HOME": "/yetano/config",
"YET_CONFIG_HOME": "/yet/config",
}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithConfigDir("/api/config"))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/api/config"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestWithoutAppEnv(t *testing.T) {
env := map[string]string{"HOME": "/home/test", "YET_CONFIG_HOME": "/yet/config"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithoutAppEnv())
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/home/test/.config/yet"; got != want {
t.Errorf("ConfigDir() = %q, want %q (YET_CONFIG_HOME should be ignored)", got, want)
}
}
func TestLinuxConfigSearchDirs(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
want := []string{"/home/test/.config/yet", "/etc/yet"}
if len(dirs) != len(want) {
t.Fatalf("ConfigSearchDirs() = %v, want %v", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("ConfigSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
}
// TestSearchResultSelected uses WithRoot over a real temp directory so
// Exists/Selected (which stat the real filesystem) are meaningful.
func TestSearchResultSelected(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
if _, err := r.EnsureConfigDir(); err != nil {
t.Fatalf("EnsureConfigDir: %v", err)
}
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
if !dirs[0].Exists || !dirs[0].Selected {
t.Errorf("ConfigSearchDirs()[0] = %+v, want Exists=true Selected=true", dirs[0])
}
if dirs[1].Exists || dirs[1].Selected {
t.Errorf("ConfigSearchDirs()[1] = %+v, want Exists=false Selected=false (nothing created there)", dirs[1])
}
}
func TestLinuxDataSearchDirs(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
dirs, err := r.DataSearchDirs()
if err != nil {
t.Fatalf("DataSearchDirs: %v", err)
}
want := []string{
"/home/test/.local/share/yet",
"/usr/local/share/yet",
"/usr/share/yet",
}
if len(dirs) != len(want) {
t.Fatalf("DataSearchDirs() = %v, want %v", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("DataSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestLinuxDataSearchDirsXDGDataDirs(t *testing.T) {
env := map[string]string{"HOME": "/home/test", "XDG_DATA_DIRS": "/opt/a/share:/opt/b/share"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
dirs, err := r.DataSearchDirs()
if err != nil {
t.Fatalf("DataSearchDirs: %v", err)
}
want := []string{
"/home/test/.local/share/yet",
"/opt/a/share/yet",
"/opt/b/share/yet",
}
if len(dirs) != len(want) {
t.Fatalf("DataSearchDirs() = %v, want %v", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("DataSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestLinuxSystemScope(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
app := core.Application{Name: "yasta", Kind: core.Service, Scope: core.SystemScope}
r := mustResolver(t, app, WithPlatform("linux"), WithEnvironment(env))
checks := []struct {
name string
fn func() (string, error)
want string
}{
{"ConfigDir", r.ConfigDir, "/etc/yasta"},
{"DataDir", r.DataDir, "/var/lib/yasta"},
{"StateDir", r.StateDir, "/var/lib/yasta"},
{"CacheDir", r.CacheDir, "/var/cache/yasta"},
{"RuntimeDir", r.RuntimeDir, "/run/yasta"},
{"LogDir", r.LogDir, "/var/log/yasta"},
{"BinDir", r.BinDir, "/usr/local/bin"},
}
for _, c := range checks {
got, err := c.fn()
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if got != c.want {
t.Errorf("%s = %q, want %q", c.name, got, c.want)
}
}
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
if len(dirs) != 1 || dirs[0].Path != "/etc/yasta" {
t.Errorf("SystemScope ConfigSearchDirs() = %v, want exactly [/etc/yasta] (no user layer)", dirs)
}
}
func TestExecutableSearchDirsUserOverridesSystem(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env))
dirs, err := r.ExecutableSearchDirs()
if err != nil {
t.Fatalf("ExecutableSearchDirs: %v", err)
}
want := []string{"/home/test/.local/bin", "/usr/local/bin"}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("ExecutableSearchDirs()[%d] = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestFreeBSDFlavor(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
app := core.Application{Name: "yasta", Kind: core.Service, Scope: core.SystemScope}
r := mustResolver(t, app, WithPlatform("freebsd"), WithEnvironment(env))
checks := []struct {
name string
fn func() (string, error)
want string
}{
{"ConfigDir", r.ConfigDir, "/usr/local/etc/yasta"},
{"DataDir", r.DataDir, "/var/db/yasta"},
{"RuntimeDir", r.RuntimeDir, "/var/run/yasta"},
}
for _, c := range checks {
got, err := c.fn()
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if got != c.want {
t.Errorf("%s = %q, want %q", c.name, got, c.want)
}
}
}
func TestMissingHomeDirectoryIsCleanError(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(map[string]string{}))
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
t.Fatalf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
}
}
func TestWithRootRebasesUnixPath(t *testing.T) {
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot("/tmp/sandbox"))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := "/tmp/sandbox/home/test/.config/yet"; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
+215
View File
@@ -0,0 +1,215 @@
package paths
import (
"runtime"
"yetano.dev/yetano/core"
)
// nativeKnownFolder, when non-nil (set only on a real Windows build, see
// knownfolders_windows.go), looks up a known folder via the Windows
// SHGetKnownFolderPath API. It is consulted only as a fallback below the
// injectable environment variables, and only when actually running on
// Windows (not merely simulating it via WithPlatform) -- see spec
// section 13's "environment values must remain injectable for tests".
var nativeKnownFolder func(folder string) (string, bool)
// windowsBase resolves one Windows known-folder-shaped base directory:
// envVar's value if set, else (on a real Windows host only) the native
// known folder API, else a string-derived default.
func (r *Resolver) windowsBase(envVar string) (value, error) {
if v, ok := lookup(r.env, envVar); ok {
return value{path: v, source: WindowsKnownFolder}, nil
}
if runtime.GOOS == "windows" && r.platform == "windows" && nativeKnownFolder != nil {
if v, ok := nativeKnownFolder(envVar); ok {
return value{path: v, source: WindowsKnownFolder}, nil
}
}
switch envVar {
case "PROGRAMDATA":
return value{path: `C:\ProgramData`, source: PlatformDefault}, nil
case "APPDATA":
home, err := r.homeDir()
if err != nil {
return value{}, err
}
return value{path: windowsJoin(home, "AppData", "Roaming"), source: PlatformDefault}, nil
case "LOCALAPPDATA":
home, err := r.homeDir()
if err != nil {
return value{}, err
}
return value{path: windowsJoin(home, "AppData", "Local"), source: PlatformDefault}, nil
default:
return value{}, ErrNoHomeDirectory
}
}
// windowsCanonical implements the shared override-chain + known-folder
// resolution for one category: tiers 1-3, then SystemScope's fixed
// %PROGRAMDATA% base, then userVar (%APPDATA% or %LOCALAPPDATA%
// depending on category), with subPath (e.g. "state", "cache", "log")
// appended when non-empty.
func (r *Resolver) windowsCanonical(kind PathKind, userVar string, subPath ...string) (value, error) {
if v, ok := r.overrideValue(kind); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
var base value
var err error
if r.app.Scope == core.SystemScope {
base, err = r.windowsBase("PROGRAMDATA")
} else {
base, err = r.windowsBase(userVar)
}
if err != nil {
return value{}, err
}
elems := append([]string{base.path, r.app.Name}, subPath...)
return value{path: r.applyRoot(windowsJoin(elems...)), source: base.source}, nil
}
func (r *Resolver) configDirWindows() (value, error) {
return r.windowsCanonical(ConfigPath, "APPDATA")
}
func (r *Resolver) dataDirWindows() (value, error) {
return r.windowsCanonical(DataPath, "LOCALAPPDATA")
}
func (r *Resolver) stateDirWindows() (value, error) {
return r.windowsCanonical(StatePath, "LOCALAPPDATA", "state")
}
func (r *Resolver) cacheDirWindows() (value, error) {
return r.windowsCanonical(CachePath, "LOCALAPPDATA", "cache")
}
func (r *Resolver) logDirWindows() (value, error) {
return r.windowsCanonical(LogPath, "LOCALAPPDATA", "log")
}
// runtimeDirWindows is always available (Windows has no XDG_RUNTIME_DIR
// equivalent that can be legitimately absent).
func (r *Resolver) runtimeDirWindows() (value, error) {
return r.windowsCanonical(RuntimePath, "LOCALAPPDATA", "runtime")
}
// binDirWindows: like binDirUnix, this is a single shared directory for
// every Yetano application (spec section 19/38), not namespaced per app
// -- hence "Yetano", not r.app.Name.
func (r *Resolver) binDirWindows() (value, error) {
if v, ok := r.overrideValue(BinPath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
var base value
var err error
if r.app.Scope == core.SystemScope {
base, err = r.windowsBase("PROGRAMDATA")
} else {
base, err = r.windowsBase("LOCALAPPDATA")
}
if err != nil {
return value{}, err
}
return value{path: r.applyRoot(windowsJoin(base.path, "Yetano", "bin")), source: base.source}, nil
}
// configLayersWindows is the one category where CLI/Service and Desktop
// differ (spec sections 15-16, 46): CLI/Service get the full three-tier
// LOCALAPPDATA(machine override) > APPDATA(canonical, roaming) >
// PROGRAMDATA(system default) layering; Desktop gets the simpler native
// two-tier APPDATA(canonical) > PROGRAMDATA(system fallback), without a
// machine-local override layer.
func (r *Resolver) configLayersWindows() ([]layer, error) {
if v, ok := r.overrideValue(ConfigPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
if r.app.Kind != core.Desktop {
local, err := r.windowsBase("LOCALAPPDATA")
if err != nil {
return nil, err
}
user = append(user, layer{
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
source: local.source,
priority: PriorityUserLocal,
canonical: false,
})
}
roaming, err := r.windowsBase("APPDATA")
if err != nil {
return nil, err
}
user = append(user, layer{
path: r.applyRoot(windowsJoin(roaming.path, r.app.Name)),
source: roaming.source,
priority: PriorityUser,
canonical: true,
})
system, err := r.windowsSystemLayer(r.app.Name)
if err != nil {
return nil, err
}
return composeSearch(user, system, r.app.Scope), nil
}
// dataLayersWindows is shared by every ApplicationKind: canonical
// LOCALAPPDATA\<app>, falling back to PROGRAMDATA\<app> for UserScope.
func (r *Resolver) dataLayersWindows() ([]layer, error) {
if v, ok := r.overrideValue(DataPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
local, err := r.windowsBase("LOCALAPPDATA")
if err != nil {
return nil, err
}
user := []layer{{
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
source: local.source,
priority: PriorityUserLocal,
canonical: true,
}}
system, err := r.windowsSystemLayer(r.app.Name)
if err != nil {
return nil, err
}
return composeSearch(user, system, r.app.Scope), nil
}
func (r *Resolver) executableLayersWindows() ([]layer, error) {
if v, ok := r.overrideValue(BinPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
local, err := r.windowsBase("LOCALAPPDATA")
if err != nil {
return nil, err
}
user := []layer{{
path: r.applyRoot(windowsJoin(local.path, "Yetano", "bin")),
source: local.source,
priority: PriorityUserLocal,
canonical: true,
}}
system, err := r.windowsSystemLayer("Yetano", "bin")
if err != nil {
return nil, err
}
return composeSearch(user, system, r.app.Scope), nil
}
// windowsSystemLayer builds the single %PROGRAMDATA%\<dirParts...> system
// layer shared by every Config/Data/Bin layer builder above.
func (r *Resolver) windowsSystemLayer(dirParts ...string) ([]layer, error) {
programData, err := r.windowsBase("PROGRAMDATA")
if err != nil {
return nil, err
}
return []layer{{
path: r.applyRoot(windowsJoin(append([]string{programData.path}, dirParts...)...)),
source: programData.source,
priority: PrioritySystem,
canonical: r.app.Scope == core.SystemScope,
}}, nil
}
+215
View File
@@ -0,0 +1,215 @@
package paths
import (
"testing"
"yetano.dev/yetano/core"
)
func windowsEnv() map[string]string {
return map[string]string{
"PROGRAMDATA": `C:\ProgramData`,
"APPDATA": `C:\Users\test\AppData\Roaming`,
"LOCALAPPDATA": `C:\Users\test\AppData\Local`,
"USERPROFILE": `C:\Users\test`,
}
}
func TestWindowsCLIDefaults(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()))
checks := []struct {
name string
fn func() (string, error)
want string
}{
{"ConfigDir", r.ConfigDir, `C:\Users\test\AppData\Roaming\yet`},
{"DataDir", r.DataDir, `C:\Users\test\AppData\Local\yet`},
{"StateDir", r.StateDir, `C:\Users\test\AppData\Local\yet\state`},
{"CacheDir", r.CacheDir, `C:\Users\test\AppData\Local\yet\cache`},
{"LogDir", r.LogDir, `C:\Users\test\AppData\Local\yet\log`},
{"RuntimeDir", r.RuntimeDir, `C:\Users\test\AppData\Local\yet\runtime`},
{"BinDir", r.BinDir, `C:\Users\test\AppData\Local\Yetano\bin`},
}
for _, c := range checks {
got, err := c.fn()
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if got != c.want {
t.Errorf("%s = %q, want %q", c.name, got, c.want)
}
if containsForwardSlash(got) {
t.Errorf("%s = %q contains a forward slash, want only backslashes", c.name, got)
}
}
}
func TestWindowsConfigSearchDirsFirstMatchOrder(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()))
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
want := []string{
`C:\Users\test\AppData\Local\yet`,
`C:\Users\test\AppData\Roaming\yet`,
`C:\ProgramData\yet`,
}
if len(dirs) != len(want) {
t.Fatalf("ConfigSearchDirs() = %v, want %v", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("ConfigSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
// The canonical write target (APPDATA) is not the highest-priority
// search entry (LOCALAPPDATA) -- spec section 46.
canonical, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if canonical != want[1] {
t.Errorf("ConfigDir() = %q, want %q (the roaming/APPDATA layer)", canonical, want[1])
}
if dirs[0].Path == canonical {
t.Errorf("highest-priority search entry unexpectedly equals the canonical write target")
}
}
func TestWindowsDataSearchDirs(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()))
dirs, err := r.DataSearchDirs()
if err != nil {
t.Fatalf("DataSearchDirs: %v", err)
}
want := []string{
`C:\Users\test\AppData\Local\yet`,
`C:\ProgramData\yet`,
}
if len(dirs) != len(want) {
t.Fatalf("DataSearchDirs() = %v, want %v", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("DataSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestWindowsSystemScope(t *testing.T) {
app := core.Application{Name: "yasta", Kind: core.Service, Scope: core.SystemScope}
r := mustResolver(t, app, WithPlatform("windows"), WithEnvironment(windowsEnv()))
want := `C:\ProgramData\yasta`
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
if len(dirs) != 1 || dirs[0].Path != want {
t.Errorf("SystemScope ConfigSearchDirs() = %v, want exactly [%s]", dirs, want)
}
bin, err := r.BinDir()
if err != nil {
t.Fatalf("BinDir: %v", err)
}
if wantBin := `C:\ProgramData\Yetano\bin`; bin != wantBin {
t.Errorf("BinDir() = %q, want %q", bin, wantBin)
}
}
func TestWindowsUserScopeMergeOrderMirrorsSearchOrderReversed(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()))
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
for i := 0; i < len(dirs)-1; i++ {
if dirs[i].Priority < dirs[i+1].Priority {
t.Fatalf("ConfigSearchDirs() not in descending priority order: %v", dirs)
}
}
}
func TestWindowsDesktopSimplerLayering(t *testing.T) {
app := core.Application{Name: "yapama", Kind: core.Desktop}
r := mustResolver(t, app, WithPlatform("windows"), WithEnvironment(windowsEnv()))
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
want := []string{
`C:\Users\test\AppData\Roaming\yapama`,
`C:\ProgramData\yapama`,
}
if len(dirs) != len(want) {
t.Fatalf("Desktop ConfigSearchDirs() = %v, want %v (no LOCALAPPDATA override layer)", dirs, want)
}
for i, w := range want {
if dirs[i].Path != w {
t.Errorf("ConfigSearchDirs()[%d].Path = %q, want %q", i, dirs[i].Path, w)
}
}
}
func TestWindowsMissingHomeIsCleanError(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(map[string]string{}))
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
t.Fatalf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
}
}
func TestWindowsAPIOverride(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithConfigDir(`D:\portable\yet-config`))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := `D:\portable\yet-config`; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestWithRootRebasesWindowsPath(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithRoot(`C:\tmp\test-root`))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := `C:\tmp\test-root\Users\test\AppData\Roaming\yet`; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func TestWithRootRebasesWindowsUNCPath(t *testing.T) {
env := windowsEnv()
env["APPDATA"] = `\\server\share\test\AppData\Roaming`
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(env), WithRoot(`C:\tmp\test-root`))
got, err := r.ConfigDir()
if err != nil {
t.Fatalf("ConfigDir: %v", err)
}
if want := `C:\tmp\test-root\test\AppData\Roaming\yet`; got != want {
t.Errorf("ConfigDir() = %q, want %q", got, want)
}
}
func containsForwardSlash(s string) bool {
for _, c := range s {
if c == '/' {
return true
}
}
return false
}