diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..0920b22 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,164 @@ +# Architecture + +This document records the design decisions behind `core/paths` and +`core/config`, and *why*, for anyone extending this library later. See +`README.md` for the user-facing API summary and priority tables. + +## Package split: paths vs. config + +`core/paths` resolves *directories*. It has no notion of a +configuration file, YAML, or file contents. `core/config` resolves +*files* within those directories, and owns everything about search +order, layering/merging, and environment expansion. `config` depends on +`paths` (it needs directories to look in); `paths` never depends on, or +knows about, `config`. This split is a hard rule (see the meta-repo's +`AGENTS.md`), not a style preference: a future caller that only needs +"where does yasta's cache directory live" should never have to pull in +YAML parsing. + +## Application model: Kind and Scope are orthogonal + +`ApplicationKind` (CLI/Desktop/Service) drives platform-*style* defaults +(most visibly on macOS and Windows). `Scope` (User/System) drives +*install-context* defaults (which of "the machine" vs. "this user" a +path belongs to). They are independent axes on purpose: `yasta` is a +`Service` whether it happens to be running as a per-user agent or a +system-wide daemon; conflating "service" with "system-scoped" would +make that impossible to express. Neither axis defaults from the other. + +## Platform strategy: injectable, not build-tag-per-file + +Spec-wise, the natural instinct is `paths_linux.go`, `paths_windows.go`, +etc., each guarded by a `//go:build` tag. This library does *not* do +that for the bulk of the logic, and the reason is spec section 32's own +requirement: "tests must not assume they're running on the OS under +test" -- Windows path logic has to be verifiable on a Linux/macOS CI +runner, and vice versa. A build-tag-gated `paths_windows.go` simply +cannot compile, let alone run, anywhere but Windows. + +Instead: + +- Every platform's logic lives in a plain `.go` file, organized by name + for readability (`unix.go`, `linux.go`, `freebsd.go`, `darwin.go`, + `windows.go`) but selected at *runtime* by `Resolver.platform` + (`runtime.GOOS` by default, overridable via `paths.WithPlatform` for + tests/simulation). +- All environment lookups go through the injectable `Environment` + interface (`paths.WithEnvironment`/`WithEnvironmentProvider`), never + `os.Getenv` directly. +- Windows path construction never uses `path/filepath` (which is + host-native and would silently misbehave when simulating Windows on a + non-Windows host, or vice versa). It uses the address-family-aware + helpers in `join.go` (`unixJoin`/`windowsJoin`/`JoinFamily`/ + `JoinDirFile`) instead, so a computed Windows path is *always* + backslash-joined and a computed Unix path is *always* forward-slash- + joined, regardless of the host running the test. +- The **one** genuine exception is `knownfolders_windows.go`: an + optional, best-effort native lookup via `SHGetKnownFolderPath`, + `//go:build windows`-gated, consulted only as a fallback *below* the + injectable environment variables and only when actually running on + Windows (not merely simulating it). It exists purely as extra fidelity + for edge cases (redirected known folders, a service account without + `APPDATA` set) -- correctness of the deterministic test suite never + depends on it. + +This satisfies spec section 1's "OS-specific implementations... where +it makes sense" (`sofern sinnvoll`) reading: a hand-written syscall +wrapper legitimately needs a build tag; a string-joining decision does +not, and gating it behind one would break the testability requirement +elsewhere in the same spec. + +## Canonical directory vs. search directories + +This is the single most important distinction in the API (see +README.md). It exists because Windows genuinely has three +simultaneously-relevant layers (`%LOCALAPPDATA%`, `%APPDATA%`, +`%PROGRAMDATA%`) with different semantics -- a new config file should be +*written* to the roaming location (so it follows the user), but an +*existing* file should be found even if it's parked in the +machine-local override layer or a system-wide default. Every +`Dir()`/`SearchDirs()` pair in this library follows +that same canonical-vs-search split, even on platforms (Linux) where +they're less obviously necessary, so the API is uniform. + +## Scope gates which layers exist, not just which one is canonical + +`SystemScope` excludes the user tier entirely from every search list +(Config/Data/Executable), rather than merely changing which layer is +canonical. Rationale: a system-scope resolution models an execution +context with no meaningful per-user home directory (a system daemon +account, `SYSTEM` on Windows) -- including `~/.config/` in its +search list would be actively misleading, not just lower priority. +`UserScope` (the default) includes the user tier *and* the system tier +as a lower-priority fallback, which is what makes "a user install +overrides a system install" (spec section 36) fall out of the priority +model for free, rather than needing special-case code. + +## BinDir is shared, not namespaced + +Every other category joins the application name onto a base directory +(`~/.config/`, `%APPDATA%\`, ...). `BinDir` deliberately does +not: `~/.local/bin` and (the spec's own literal example) +`%LOCALAPPDATA%\Yetano\bin` are shared across every Yetano application, +mirroring how a `PATH` entry is inherently a shared, not per-app, +concept. This is `appendsAppName` in `layout.go` -- the one category +where it's `false`. + +## App-specific vs. shared environment tiers: as-is vs. base + +`YET_CONFIG_HOME=/foo` resolves to exactly `/foo` -- not `/foo/yet`. +`YETANO_CONFIG_HOME=/foo` (and `XDG_CONFIG_HOME`, and every platform- +native/default tier) resolves to `/foo/yet`. The reasoning: an +app-specific variable's name *already* names the application, so +appending the name again would be surprising and is not how any +comparable app-specific override convention (elsewhere in the Unix or +Windows world) behaves. A shared variable (Yetano-wide, or XDG, or a +Windows known folder) is inherently a *base* many applications share, +so it needs the per-app name appended to stay collision-free. This +asymmetry is deliberate and tested (`TestAppOverrideWinsOverYetano`). + +## macOS: Config and Data share one directory + +A native macOS app's `~/Library/Application Support/` commonly +holds both preferences-adjacent files and bulk data side by side -- this +library's Desktop strategy keeps `ConfigDir()` and `DataDir()` pointing +at the exact same directory on macOS Desktop, rather than inventing an +artificial `Config`/`Data` subdirectory split that no native macOS app +actually uses. `StateDir()` gets its own `State` subdirectory so it +doesn't collide with either. + +## RuntimeDir: no fabricated fallback + +Spec section 8 explicitly forbids treating `~/.local/run` (or any other +invented path) as an XDG_RUNTIME_DIR equivalent, because a runtime +directory's real semantics (session-scoped, gone after logout, specific +permissions) can't be approximated by just picking a persistent +directory. `RuntimeDir()` on Unix therefore returns +`paths.ErrRuntimeDirUnavailable` rather than a wrong-but-present value +when neither an override nor `XDG_RUNTIME_DIR` is set. Windows and +macOS don't have this ambiguity (there's no "session runtime directory +that may not exist" convention to get wrong there), so `RuntimeDir()` +always succeeds on those platforms. + +## Unix system-scope directories follow each OS's own convention + +Linux SystemScope uses the FHS layout (`/etc`, `/var/lib`, `/var/cache`, +`/run`, `/var/log`). FreeBSD does not reuse it wholesale (spec sections +33/56): it uses `/usr/local/etc` (ports convention) and `/var/db` +(BSD's writable-application-data convention) instead of `/etc` and +`/var/lib`. Any other Unix-family `GOOS` this library doesn't +specifically tune yet falls back to the Linux flavor (`flavor()`'s +`default` case) -- a documented, working default, not a silent wrong +answer, and addable later (a new `.go` flavor table) without +touching any other file (see TODO.md). + +## Explain/doctor never mutates the filesystem + +`Explain()` on both `paths.Resolver` and `config.Resolver` only ever +performs read-only `os.Stat` calls (existence and a best-effort +writability check via the owner-write permission bit -- deliberately +*not* a real access probe, which would require creating and deleting a +test file). This is spec section 47's explicit requirement, and it's +why `Explain` and `Ensure*` are entirely separate code paths: the former +must never accidentally gain a side effect by sharing implementation +with the latter. diff --git a/README.md b/README.md index 17440cb..8628b8c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,237 @@ -# core +# yetano.dev/yetano/core -Shared Go library for Yetano applications: platform-independent path, file, and config resolution (paths/config layering, env expansion, explain/introspection). \ No newline at end of file +Shared Go library for Yetano applications. `core` defines how a Yetano +application behaves with respect to paths, configuration, runtime data, +and platform integration -- not just a grab-bag of utility functions (see +`AGENTS.md` in the meta-repository root, and [ARCHITECTURE.md](ARCHITECTURE.md) +for the full design rationale). + +The first area covered is **platform-independent path, file, and +configuration resolution**: `core/paths` and `core/config`. + +```text +yetano.dev/yetano/core +yetano.dev/yetano/core/paths +yetano.dev/yetano/core/config +``` + +Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions +leak into shared code (see ARCHITECTURE.md's "Platform strategy" section +for how this is achieved without build-tag-per-OS files everywhere). + +## Application model + +```go +app := core.Application{ + Name: "yet", + Kind: core.CLI, // or core.Desktop, core.Service +} +``` + +`Scope` (`core.UserScope`, the default, or `core.SystemScope`) is a +*separate* concept from `Kind`: the same Service application can run at +either scope, resolving different directories for each. + +## core/paths: directories, not files + +```go +resolver, err := paths.For(app) + +configDir, err := resolver.ConfigDir() // preferred write location +searchDirs, err := resolver.ConfigSearchDirs() // every location to search, priority order + +dataDir, err := resolver.DataDir() +stateDir, err := resolver.StateDir() +cacheDir, err := resolver.CacheDir() +runtimeDir, err := resolver.RuntimeDir() // may be ErrRuntimeDirUnavailable, see below +logDir, err := resolver.LogDir() +binDir, err := resolver.BinDir() // shared, not namespaced per app +``` + +Resolving a path **never** creates it. Use `resolver.EnsureConfigDir()` +etc. to create one explicitly. + +### Canonical directory vs. search directories + +Every category has two APIs: `Dir()` (the one preferred +write location) and, for Config/Data/executables, +`SearchDirs()`/`ExecutableSearchDirs()` (every location to +search, highest priority first). These are not always the same +location -- see "Windows" below. + +### Environment variable priority + +Every canonical category is resolved through the same chain, highest +priority first: + +| Priority | Source | Example | +|---|---|---| +| 1 | Explicit API override | `paths.WithConfigDir("/custom")` | +| 2 | App-specific environment | `YET_CONFIG_HOME` | +| 3 | Shared Yetano environment | `YETANO_CONFIG_HOME` | +| 4 | Platform-native mechanism | `XDG_CONFIG_HOME`, a Windows known folder, native macOS paths | +| 5 | Platform default | `~/.config`, `%APPDATA%`, `~/Library/Application Support` | + +Tiers 1-2 (API override, app-specific environment) are used **as-is**: +the value is the final directory, nothing is appended. Tiers 3-4-5 are +treated as a *base* directory that the application name is joined onto +-- except `BinDir`, which is shared across every Yetano application (like +`~/.local/bin`), never namespaced per app, at every tier. + +### Linux/Unix (XDG) + +```text +~/.config/ (XDG_CONFIG_HOME) +~/.local/share/ (XDG_DATA_HOME) +~/.local/state/ (XDG_STATE_HOME) +~/.cache/ (XDG_CACHE_HOME) +$XDG_RUNTIME_DIR/ -- or ErrRuntimeDirUnavailable if unset (see below) +~/.local/state//log +~/.local/bin +``` + +System scope follows the Filesystem Hierarchy Standard: `/etc/`, +`/var/lib/`, `/var/cache/`, `/run/`, `/var/log/`, +`/usr/local/bin`. FreeBSD uses its own ports-flavored equivalents +(`/usr/local/etc`, `/var/db`, ...) instead of blindly reusing Linux's; +any other Unix-family GOOS falls back to the Linux flavor as a +documented, tunable-later default (see TODO.md). + +### macOS: CLI/Service vs. Desktop + +CLI and Service applications use the *same* XDG-flavored layout as +Linux, for consistent cross-platform administration. Only Desktop (a +native GUI app) uses `~/Library/...`: + +```text +~/Library/Application Support/ (Config AND Data -- see ARCHITECTURE.md) +~/Library/Application Support//State +~/Library/Caches/ +~/Library/Logs/ +``` + +### Windows + +Windows is a first-class platform, not XDG-with-backslashes. +`%APPDATA%`, `%LOCALAPPDATA%`, and `%PROGRAMDATA%` have distinct +semantics (roaming user, local-machine user, system-wide) -- see +ARCHITECTURE.md. + +For CLI/Service applications, `ConfigDir()` and `ConfigSearchDirs()` +diverge on purpose: + +```go +resolver.ConfigDir() // %APPDATA%\ (canonical write target) +resolver.ConfigSearchDirs() // %LOCALAPPDATA%\ (highest priority: machine override) + // %APPDATA%\ (canonical, roaming) + // %PROGRAMDATA%\ (lowest priority: system default) +``` + +Desktop applications use the simpler, native two-tier +`%APPDATA%` (canonical) > `%PROGRAMDATA%` (system fallback), without the +machine-local override layer. Data/State/Cache/Log/Runtime live under +`%LOCALAPPDATA%\\...` for every kind. + +### RuntimeDir + +`RuntimeDir()` never fabricates a fallback like `~/.local/run`. On +Unix, without an explicit override and without `XDG_RUNTIME_DIR` set, it +returns `paths.ErrRuntimeDirUnavailable` -- callers decide what to do. +Windows and macOS always resolve a runtime directory (no equivalent +"may legitimately not exist" case there). + +### Explain / doctor + +```go +explanation, err := resolver.Explain() +fmt.Println(explanation) // human-readable report +``` + +Never mutates the filesystem; `Explain` only performs read-only +existence/permission checks. + +### Testing on any host + +Every platform code path is a plain function of an injectable +`Environment` (env vars) and an injectable platform string +(`paths.WithPlatform("windows")`), not `runtime.GOOS`/`os.Getenv` +directly -- see ARCHITECTURE.md's "Platform simulation" section for why, +and the package's own tests for how Windows/macOS/FreeBSD path logic is +verified while running on any host. + +## core/config: finding and layering configuration files + +```go +cfg, err := config.For(app) + +selected, found, err := cfg.Resolve() // highest-priority existing file +all, err := cfg.ResolveAll() // every layer, with metadata + +var target MyConfig +err = cfg.LoadMerged(&target) // lowest-to-highest priority merge, then unmarshal +``` + +### Layer priority + +Search order (`Resolve`/`ResolveAll`) and merge order (`LoadMerged`) are +the *same* hierarchy, walked in opposite directions -- there is only one +priority model to keep in sync, not two independently maintained +orderings. + +| Priority | Layer | Toggle | +|---|---|---| +| Highest | Working directory (`./.yaml`) | `config.WithWorkingDirectory(false)` | +| User | `paths.ConfigDir()`/`ConfigSearchDirs()` for `app` | (always on) | +| System | `paths.ConfigSearchDirs()`'s system-tier entry | `config.WithSystemConfig(false)` | +| Lowest | Shared Yetano config dir (`~/.config/yetano/`, opt-in) | `config.WithYetanoDefaults(true)` | + +On Windows, the "user" tier above expands into the same +LOCALAPPDATA/APPDATA/PROGRAMDATA layering `core/paths` already resolves. + +### Merge semantics + +- **Scalars**: the higher-priority layer's value replaces the lower one. +- **Maps**: merged recursively, key by key. +- **Lists**: replaced wholesale by the higher-priority layer -- never + concatenated element-by-element. +- **Explicit YAML `null`**: removes the key from the merged result (a + layer can write `key: null` to intentionally unset a lower layer's + value). + +### Environment expansion + +String values may reference `${VAR}` or `$VAR` (enabled by default, +`config.WithEnvExpansion(false)` to disable). This is **plain variable +substitution, never a shell**: no `$(...)`, no backticks, no command +execution -- the expander's grammar has no way to represent them. An +unset variable is left literally unexpanded (`${MISSING}` stays in the +result, so a typo is visible); a variable set to `""` expands to an +empty string -- these are deliberately different outcomes. + +### The shared Yetano config vs. an application's own config + +`~/.config/yetano/` (or the platform equivalent) is for +ecosystem-wide, shared settings (`repositories.yaml`, `trust.yaml`, +...) -- it is **not** automatically the same thing as, or automatically +layered into, any one application's own configuration. An application +opts in explicitly with `config.WithYetanoDefaults(true)`. + +## Security + +- Environment expansion is variable substitution only -- never shell + evaluation, command substitution, or execution of any kind. +- Every Windows path is built with `path/filepath`-equivalent, + address-family-aware joining (see `paths.JoinFamily`/`JoinDirFile`), + never naive string concatenation -- UNC paths (`\\server\share\...`) + and drive roots are never corrupted by a portable-root rebase. +- No automatic root/administrator operations: `SystemScope` only changes + *which paths are computed*, never elevates privileges or performs a + privileged action on its own. +- Resolving or explaining paths never mutates the filesystem; creating a + directory always requires an explicit `Ensure*` call. + +## Versioning + +Tagged as plain semver on this repository (`v0.1.0`, ...), per the +meta-repo `AGENTS.md`'s versioning rules: an existing tag is never +force-moved to a different commit. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..86bd83c --- /dev/null +++ b/TODO.md @@ -0,0 +1,90 @@ +# TODO / open architecture questions + +Deliberately not resolved in this V1 (see spec section 63 and AGENTS.md's +"no over-abstraction" rule) -- tracked here rather than solved +speculatively. + +## Migration + +- **Migrate `yet` onto `core/paths`/`core/config`.** `yet`'s + `internal/store.Home()` (`$YETANO_HOME`, defaulting to + `os.UserConfigDir()/yetano`) and `internal/config` (fixed + `/etc/yetano/yetano.yaml` -> `~/.config/yetano/yetano.yaml` -> + `./yetano.yaml` -> `--config` cascade) predate this library and + overlap with what it now provides. Migrating is a deliberately + separate follow-up, not part of this change -- `yet`'s existing + behavior needs to be evaluated field-by-field (e.g. `$YETANO_HOME`'s + default of `os.UserConfigDir()/yetano` is *not* the same location + `core/paths` would resolve for an app named "yetano"/"yet"; that + divergence needs a conscious decision, not a silent behavior change). +- Once `yet` migrates, evaluate `yasta`, `yamocir`, `yaiam`, and + `yalsh`-adjacent projects the same way (per the original task + description) -- each on its own merits, not as a blanket sweep. + +## Platform tuning + +- FreeBSD's flavor (`freebsd.go`) is a best-effort first pass. Other BSD + and Unix-family `GOOS` values (`openbsd`, `netbsd`, `dragonfly`, + `solaris`, `illumos`, ...) currently fall back to the Linux flavor + (`flavor()`'s default case) -- verified to compile and behave + sensibly, not verified against each OS's actual convention. Adding a + dedicated flavor table for one of them is a small, additive change + (a new `.go` file plus one `case` in `flavor()`), never a + redesign. +- macOS Desktop's `RuntimeDir()` (`~/Library/Application + Support//Runtime`) is a placeholder -- macOS has no strong native + convention for a GUI app's ephemeral runtime directory the way + XDG_RUNTIME_DIR does on Linux. Revisit if a real Desktop consumer + needs something more specific (e.g. a `TemporaryItems`-based + location). +- `LogAliasDir()` (spec section 39: `~/.local/log/` as a Unix + convenience symlink target) is resolved but never created -- no + symlink-creation API exists yet. Decide whether this is worth adding + before any consumer actually wants it. + +## Windows + +- **BinDir / installer strategy.** `paths.BinDir()` for Windows + resolves `%LOCALAPPDATA%\Yetano\bin` (user) / + `%PROGRAMDATA%\Yetano\bin` (system) as *locations*, per spec section + 19. Whether/how `yet` actually adds either to `PATH`, and how a + package gets "activated" there (symlink vs. junction vs. copy/shim + launcher, spec section 20) is explicitly out of scope for `core` -- + path resolution and package activation stay separate concerns (spec + section 20's own instruction). +- The native `SHGetKnownFolderPath` fallback in + `knownfolders_windows.go` has only been verified to compile + (`GOOS=windows go build`/`go vet`), never run on an actual Windows + host. It is a secondary fallback below environment variables, so a + latent bug there would only matter in the edge case where + `APPDATA`/`LOCALAPPDATA`/`PROGRAMDATA` are all unset in the process + environment on real Windows. + +## Portability / distribution model + +- `paths.WithRoot`/`YETANO_HOME`-style portable mode: `WithRoot` exists + and is tested, but there is no ecosystem-wide "portable install" + concept wired up yet (spec section 41's "optional later: + `YETANO_HOME` or portable mode"). +- The future `yet` package store model (spec sections 2/37/38: package + store vs. application data vs. config vs. state vs. cache vs. runtime + vs. executables, as distinct concepts) is intentionally not + implemented here -- `core/paths` only provides the primitives (scoped, + prioritized directories) a future store implementation would sit on + top of. +- Plugin/extension search paths: no dedicated category exists yet; + `paths.FindFile` is generic enough that a caller can build one today + (e.g. over `DataSearchDirs()` with a `plugins/` suffix) without + needing a new `PathKind`. +- Atomic package activation, versioning/rollback for that future store: + out of scope, same as above. + +## Central Yetano config + +- `config.WithYetanoDefaults(true)` resolves the shared + `~/.config/yetano/` (or platform equivalent) via a pseudo-`Application + {Name: "yetano", Kind: core.CLI}`. This is deliberately always + CLI-shaped (XDG-flavored everywhere), even for a Desktop or Service + caller, since it's a shared, admin/CLI-facing location -- revisit only + if a real consumer needs the shared config to follow a different + convention on macOS/Windows Desktop apps specifically. diff --git a/app.go b/app.go new file mode 100644 index 0000000..60edb37 --- /dev/null +++ b/app.go @@ -0,0 +1,126 @@ +// Package core defines the shared Application model that the rest of the +// yetano.dev/yetano/core modules (paths, config, and future ones) build on: +// what an application is called, what kind of program it is, and in what +// scope it is installed/running. See paths.For and config.For for how this +// model turns into concrete filesystem locations. +package core + +import ( + "fmt" + "strings" +) + +// ApplicationKind describes what shape a Yetano application takes. It +// controls platform default behavior (most visibly on macOS and Windows, +// see the paths package), never installation privilege -- that is Scope's +// job. +type ApplicationKind int + +const ( + // CLI is a command-line/terminal application. On macOS it prefers the + // same XDG-like layout as Linux, for consistent cross-platform admin. + CLI ApplicationKind = iota + // Desktop is a native GUI application. On macOS and Windows it prefers + // native per-OS directory conventions (Library/Application Support, + // %APPDATA%, ...) over the Unix-y XDG layout. + Desktop + // Service is a long-running background process (daemon/agent). Its + // directory layout follows the same convention as CLI; what makes a + // service a service (install as a launchd/systemd/Windows service + // unit) is outside this library's scope. + Service +) + +// String returns the lowercase name used in Explain output and error +// messages. +func (k ApplicationKind) String() string { + switch k { + case CLI: + return "cli" + case Desktop: + return "desktop" + case Service: + return "service" + default: + return fmt.Sprintf("ApplicationKind(%d)", int(k)) + } +} + +// Scope describes the installation/execution context an Application runs +// in -- independent of ApplicationKind. The same Application (e.g. a +// Service) can run as UserScope or SystemScope; both are legitimate and +// this library resolves different directories for each (see paths). +// +// This is deliberately not "UserService"/"SystemService": Scope applies +// equally to CLI, Desktop, and Service kinds. +type Scope int + +const ( + // UserScope resolves per-user directories (the zero value, and the + // default for "yet install foo"). + UserScope Scope = iota + // SystemScope resolves system-wide directories (e.g. "yet install + // --system foo"), following each platform's system location + // convention (/etc, /var/lib, %PROGRAMDATA%, /Library, ...). + SystemScope +) + +// String returns the lowercase name used in Explain output and error +// messages. +func (s Scope) String() string { + switch s { + case UserScope: + return "user" + case SystemScope: + return "system" + default: + return fmt.Sprintf("Scope(%d)", int(s)) + } +} + +// Application identifies a Yetano application to the paths and config +// resolvers. Name becomes both the directory name under each resolved +// base directory (e.g. ~/.config/) and, unless overridden, the +// basis for the application's environment variable prefix (see +// paths.WithEnvPrefix). +type Application struct { + // Name is the application's short, stable identifier: e.g. "yet", + // "yasta". It must not be empty and must not contain path separators, + // "..", or whitespace -- see Validate. + Name string + + // Kind is the application's shape. The zero value is CLI. + Kind ApplicationKind + + // Scope is the installation/execution context. The zero value is + // UserScope. + Scope Scope +} + +// Validate reports whether a is safe to turn into filesystem paths and +// environment variable names. core intentionally does not keep a fixed +// list of known Yetano application names (see AGENTS.md); any name that +// passes Validate is accepted. +func (a Application) Validate() error { + if a.Name == "" { + return fmt.Errorf("core: application name must not be empty") + } + if strings.ContainsAny(a.Name, "/\\") { + return fmt.Errorf("core: application name %q must not contain path separators", a.Name) + } + if a.Name == "." || a.Name == ".." { + return fmt.Errorf("core: application name %q is not a valid directory name", a.Name) + } + if strings.TrimSpace(a.Name) != a.Name { + return fmt.Errorf("core: application name %q must not have leading/trailing whitespace", a.Name) + } + return nil +} + +// EnvPrefix derives the default application-specific environment variable +// prefix from a.Name: upper-cased, with any '-' replaced by '_' (e.g. +// "yet" -> "YET", "yapl-oci" -> "YAPL_OCI"). paths.WithEnvPrefix overrides +// this; paths.WithoutAppEnv disables it entirely. +func (a Application) EnvPrefix() string { + return strings.ToUpper(strings.ReplaceAll(a.Name, "-", "_")) +} diff --git a/app_test.go b/app_test.go new file mode 100644 index 0000000..4385ff5 --- /dev/null +++ b/app_test.go @@ -0,0 +1,71 @@ +package core + +import "testing" + +func TestApplicationValidate(t *testing.T) { + cases := []struct { + name string + app Application + wantErr bool + }{ + {"valid", Application{Name: "yet"}, false}, + {"valid-with-dash", Application{Name: "yapl-oci"}, false}, + {"empty", Application{Name: ""}, true}, + {"slash", Application{Name: "ye/t"}, true}, + {"backslash", Application{Name: `ye\t`}, true}, + {"dot", Application{Name: "."}, true}, + {"dotdot", Application{Name: ".."}, true}, + {"leading-space", Application{Name: " yet"}, true}, + {"trailing-space", Application{Name: "yet "}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := tc.app.Validate() + if (err != nil) != tc.wantErr { + t.Fatalf("Validate() error = %v, wantErr %v", err, tc.wantErr) + } + }) + } +} + +func TestApplicationEnvPrefix(t *testing.T) { + cases := []struct { + name string + want string + }{ + {"yet", "YET"}, + {"yapl-oci", "YAPL_OCI"}, + {"yasta", "YASTA"}, + } + for _, tc := range cases { + app := Application{Name: tc.name} + if got := app.EnvPrefix(); got != tc.want { + t.Errorf("Application{Name: %q}.EnvPrefix() = %q, want %q", tc.name, got, tc.want) + } + } +} + +func TestApplicationKindString(t *testing.T) { + cases := map[ApplicationKind]string{ + CLI: "cli", + Desktop: "desktop", + Service: "service", + } + for kind, want := range cases { + if got := kind.String(); got != want { + t.Errorf("%v.String() = %q, want %q", int(kind), got, want) + } + } +} + +func TestScopeString(t *testing.T) { + cases := map[Scope]string{ + UserScope: "user", + SystemScope: "system", + } + for scope, want := range cases { + if got := scope.String(); got != want { + t.Errorf("%v.String() = %q, want %q", int(scope), got, want) + } + } +} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..93e86b9 --- /dev/null +++ b/config/config.go @@ -0,0 +1,169 @@ +// Package config resolves, searches, and layers a Yetano application's +// configuration *files* -- built on top of core/paths, which only +// resolves *directories* and knows nothing about file contents (see +// AGENTS.md: "paths must not implicitly parse configuration"). +// +// A Resolver is obtained via For (or New): +// +// app := core.Application{Name: "yet", Kind: core.CLI} +// cfg := config.For(app) +// +// selected, found, err := cfg.Resolve() // highest-priority existing file +// all, err := cfg.ResolveAll() // every layer, with metadata +// +// var target MyConfig +// err = cfg.LoadMerged(&target) // lowest-to-highest priority merge +// +// # Search order and merge order are the same hierarchy +// +// Resolve/ResolveAll walk the priority hierarchy highest-to-lowest +// (first match wins); LoadMerged walks the exact same hierarchy +// lowest-to-highest (each layer overlays the previous one). Both derive +// from one ordered []Layer -- see layers() in layers.go -- so there is +// never a second, independently-maintained ordering to keep in sync. +// +// # Priority hierarchy +// +// Highest to lowest, on Unix: +// +// working directory (./) -- toggle: WithWorkingDirectory +// 's user config dir (paths.ConfigDir/ConfigSearchDirs) +// 's system config dir -- toggle: WithSystemConfig +// the shared Yetano config dir -- toggle: WithYetanoDefaults (opt-in, off by default) +// +// On Windows, the user/system tier expands to the same three-layer +// LOCALAPPDATA > APPDATA > PROGRAMDATA search core/paths already +// resolves (see core/paths's package doc); config only adds the working +// directory layer on top and the Yetano-defaults layer below. +// +// # Environment expansion +// +// A loaded file's string values may reference ${VAR}/$VAR (see +// expand.go); this is plain variable substitution, never a shell -- no +// $(...), no backticks, no command execution of any kind. +package config + +import ( + "yetano.dev/yetano/core" + "yetano.dev/yetano/core/paths" +) + +// Filename derives the default configuration file name for an +// application: ".yaml". +func Filename(app core.Application) string { + return app.Name + ".yaml" +} + +// Resolver resolves, searches, and layers one application's +// configuration files. +type Resolver struct { + app core.Application + paths *paths.Resolver + filename string + workdir bool + workdirPath string + systemConfig bool + yetanoDefaults bool + envExpansion bool + env paths.Environment + pathsOpts []paths.Option +} + +// Option configures a Resolver constructed by New/For. +type Option func(*Resolver) + +// New constructs a Resolver for app. +func New(app core.Application, opts ...Option) (*Resolver, error) { + if err := app.Validate(); err != nil { + return nil, err + } + r := &Resolver{ + app: app, + filename: Filename(app), + workdir: true, + workdirPath: ".", + systemConfig: true, + envExpansion: true, + env: paths.OSEnvironment, + } + for _, opt := range opts { + opt(r) + } + pr, err := paths.New(app, append([]paths.Option{paths.WithEnvironmentProvider(r.env)}, r.pathsOpts...)...) + if err != nil { + return nil, err + } + r.paths = pr + return r, nil +} + +// For is an alias for New, matching the spec's `config.For(app)` spelling. +func For(app core.Application, opts ...Option) (*Resolver, error) { + return New(app, opts...) +} + +// WithFilename overrides the configuration file name (default +// ".yaml"). +func WithFilename(name string) Option { + return func(r *Resolver) { r.filename = name } +} + +// WithWorkingDirectory enables or disables the working-directory layer +// (spec section 23) -- important to disable for services, which have no +// meaningful "current directory" a human invoked them from. +func WithWorkingDirectory(enabled bool) Option { + return func(r *Resolver) { r.workdir = enabled } +} + +// WithWorkdirPath overrides the directory used for the working-directory +// layer (default "."). Mainly useful for deterministic tests. +func WithWorkdirPath(path string) Option { + return func(r *Resolver) { r.workdirPath = path } +} + +// WithSystemConfig enables or disables the system-wide configuration +// layer (/etc/, %PROGRAMDATA%\, ...). Enabled by default. +func WithSystemConfig(enabled bool) Option { + return func(r *Resolver) { r.systemConfig = enabled } +} + +// WithYetanoDefaults enables the shared, ecosystem-wide Yetano +// configuration directory (spec section 4) as the lowest-priority +// fallback layer. Disabled by default: an application must opt in. +func WithYetanoDefaults(enabled bool) Option { + return func(r *Resolver) { r.yetanoDefaults = enabled } +} + +// WithEnvExpansion enables or disables ${VAR}/$VAR expansion of string +// values when loading a file (LoadMerged). Enabled by default. +func WithEnvExpansion(enabled bool) Option { + return func(r *Resolver) { r.envExpansion = enabled } +} + +// WithEnvironment injects a fixed environment variable map, used both +// for ${VAR} expansion and (via WithEnvironmentProvider on the +// underlying paths.Resolver) for locating the configuration directories +// themselves -- so a test can set HOME once and have it apply +// consistently everywhere. +func WithEnvironment(env map[string]string) Option { + return func(r *Resolver) { r.env = paths.MapEnvironment(env) } +} + +// WithEnvironmentProvider injects a custom paths.Environment +// implementation, for the same purposes as WithEnvironment. +func WithEnvironmentProvider(env paths.Environment) Option { + return func(r *Resolver) { r.env = env } +} + +// WithPathsOptions passes additional options through to the underlying +// core/paths.Resolver (e.g. paths.WithPlatform, paths.WithRoot). +func WithPathsOptions(opts ...paths.Option) Option { + return func(r *Resolver) { r.pathsOpts = append(r.pathsOpts, opts...) } +} + +// Application returns the Application this Resolver was built for. +func (r *Resolver) Application() core.Application { return r.app } + +// Filename returns the configuration file name this Resolver searches +// for in every layer. +func (r *Resolver) Filename() string { return r.filename } diff --git a/config/coverage_test.go b/config/coverage_test.go new file mode 100644 index 0000000..1cba0a1 --- /dev/null +++ b/config/coverage_test.go @@ -0,0 +1,82 @@ +package config + +import ( + "path/filepath" + "testing" + + "yetano.dev/yetano/core/paths" +) + +func TestConfigResolverAccessors(t *testing.T) { + r := mustResolver(t, yetApp(), WithFilename("custom.yaml")) + if r.Application().Name != "yet" { + t.Errorf("Application().Name = %q, want yet", r.Application().Name) + } + if r.Filename() != "custom.yaml" { + t.Errorf("Filename() = %q, want custom.yaml", r.Filename()) + } + + r2, err := For(yetApp()) + if err != nil { + t.Fatalf("For: %v", err) + } + if r2.Filename() != "yet.yaml" { + t.Errorf("For(...).Filename() = %q, want yet.yaml", r2.Filename()) + } +} + +func TestWithEnvironmentProviderAndExpansionToggle(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "path: ${HOME}/data\n") + + env := paths.MapEnvironment{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironmentProvider(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkingDirectory(false), + ) + var target struct { + Path string `yaml:"path"` + } + if err := r.LoadMerged(&target); err != nil { + t.Fatalf("LoadMerged: %v", err) + } + if want := "/home/test/data"; target.Path != want { + t.Errorf("Path = %q, want %q", target.Path, want) + } + + r2 := mustResolver(t, yetApp(), + WithEnvironmentProvider(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkingDirectory(false), + WithEnvExpansion(false), + ) + var target2 struct { + Path string `yaml:"path"` + } + if err := r2.LoadMerged(&target2); err != nil { + t.Fatalf("LoadMerged: %v", err) + } + if want := "${HOME}/data"; target2.Path != want { + t.Errorf("Path = %q, want %q (expansion disabled)", target2.Path, want) + } +} + +func TestReadLayerMissingFileIsNotAnError(t *testing.T) { + m, err := readLayer("/does/not/exist/yet.yaml") + if err != nil { + t.Fatalf("readLayer() error = %v, want nil", err) + } + if len(m) != 0 { + t.Errorf("readLayer() = %v, want empty map", m) + } +} + +func TestReadLayerInvalidYAML(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "bad.yaml") + writeFile(t, path, "not: valid: yaml: [") + if _, err := readLayer(path); err == nil { + t.Fatal("readLayer() error = nil, want a parse error") + } +} diff --git a/config/expand.go b/config/expand.go new file mode 100644 index 0000000..8f2d12e --- /dev/null +++ b/config/expand.go @@ -0,0 +1,99 @@ +package config + +import ( + "strings" + + "yetano.dev/yetano/core/paths" +) + +// expandTree walks a value produced by yaml.Unmarshal into interface{} +// (maps, slices, scalars) and expands ${VAR}/$VAR references in every +// string value it finds. Map keys and non-string scalars are left +// untouched (spec section 30: "no expansion of YAML keys", "expansion +// only in string values"). +func expandTree(v any, env paths.Environment) any { + switch t := v.(type) { + case string: + return expandString(t, env) + case map[string]any: + out := make(map[string]any, len(t)) + for k, val := range t { + out[k] = expandTree(val, env) + } + return out + case []any: + out := make([]any, len(t)) + for i, val := range t { + out[i] = expandTree(val, env) + } + return out + default: + return v + } +} + +func isNameStart(c byte) bool { + return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +func isNameChar(c byte) bool { + return isNameStart(c) || (c >= '0' && c <= '9') +} + +// expandString performs plain ${VAR} and $VAR substitution -- never a +// shell: there is no $(...), no backticks, no command execution of any +// kind, because this scanner simply has no grammar for them (spec +// section 30). A variable that is not set in env is left literally +// unexpanded (e.g. "${MISSING}" stays in the result) rather than +// silently becoming an empty string, so a typo is visible in the +// resolved configuration instead of turning into a wrong-but-valid +// path. A variable that *is* set, even to "", expands to its value -- +// this is how "unset" and "set but empty" are told apart (spec section +// 30). +func expandString(s string, env paths.Environment) string { + if !strings.Contains(s, "$") { + return s + } + var b strings.Builder + for i := 0; i < len(s); { + c := s[i] + if c != '$' || i+1 >= len(s) { + b.WriteByte(c) + i++ + continue + } + if s[i+1] == '{' { + end := strings.IndexByte(s[i+2:], '}') + if end < 0 { + b.WriteByte(c) + i++ + continue + } + name := s[i+2 : i+2+end] + if val, ok := env.Lookup(name); ok { + b.WriteString(val) + } else { + b.WriteString(s[i : i+2+end+1]) + } + i += 2 + end + 1 + continue + } + if isNameStart(s[i+1]) { + j := i + 1 + for j < len(s) && isNameChar(s[j]) { + j++ + } + name := s[i+1 : j] + if val, ok := env.Lookup(name); ok { + b.WriteString(val) + } else { + b.WriteString(s[i:j]) + } + i = j + continue + } + b.WriteByte(c) + i++ + } + return b.String() +} diff --git a/config/expand_test.go b/config/expand_test.go new file mode 100644 index 0000000..8001954 --- /dev/null +++ b/config/expand_test.go @@ -0,0 +1,78 @@ +package config + +import ( + "testing" + + "yetano.dev/yetano/core/paths" +) + +func TestExpandStringBraceForm(t *testing.T) { + env := paths.MapEnvironment{"HOME": "/home/test"} + if got, want := expandString("${HOME}/data", env), "/home/test/data"; got != want { + t.Errorf("expandString() = %q, want %q", got, want) + } +} + +func TestExpandStringBareForm(t *testing.T) { + env := paths.MapEnvironment{"HOME": "/home/test"} + if got, want := expandString("$HOME/data", env), "/home/test/data"; got != want { + t.Errorf("expandString() = %q, want %q", got, want) + } +} + +func TestExpandStringUnknownVariableLeftUnexpanded(t *testing.T) { + env := paths.MapEnvironment{"HOME": "/home/test"} + if got, want := expandString("${MISSING}/data", env), "${MISSING}/data"; got != want { + t.Errorf("expandString() = %q, want %q (unset var left literal)", got, want) + } +} + +func TestExpandStringSetButEmptyExpandsToEmpty(t *testing.T) { + env := paths.MapEnvironment{"EMPTY": ""} + if got, want := expandString("[${EMPTY}]", env), "[]"; got != want { + t.Errorf("expandString() = %q, want %q (set-but-empty expands to empty string)", got, want) + } +} + +func TestExpandStringNoCommandSubstitution(t *testing.T) { + env := paths.MapEnvironment{} + input := "$(rm -rf /) `echo hi` plain text" + if got := expandString(input, env); got != input { + t.Errorf("expandString() = %q, want unchanged %q (no shell eval)", got, input) + } +} + +func TestExpandStringWindowsPathValue(t *testing.T) { + env := paths.MapEnvironment{"LOCALAPPDATA": `C:\Users\test\AppData\Local`} + got := expandString(`${LOCALAPPDATA}\yet\objects`, env) + if want := `C:\Users\test\AppData\Local\yet\objects`; got != want { + t.Errorf("expandString() = %q, want %q", got, want) + } +} + +func TestExpandTreeOnlyExpandsStringValues(t *testing.T) { + env := paths.MapEnvironment{"HOME": "/home/test"} + tree := map[string]any{ + "path": "${HOME}/data", + "count": 5, + "list": []any{"${HOME}/a", 1, true}, + "nested": map[string]any{ + "path": "${HOME}/b", + }, + } + got := expandTree(tree, env).(map[string]any) + if got["path"] != "/home/test/data" { + t.Errorf("path = %v, want /home/test/data", got["path"]) + } + if got["count"] != 5 { + t.Errorf("count = %v, want 5 (non-string scalar untouched)", got["count"]) + } + list := got["list"].([]any) + if list[0] != "/home/test/a" || list[1] != 1 || list[2] != true { + t.Errorf("list = %v, want [/home/test/a 1 true]", list) + } + nested := got["nested"].(map[string]any) + if nested["path"] != "/home/test/b" { + t.Errorf("nested.path = %v, want /home/test/b", nested["path"]) + } +} diff --git a/config/explain.go b/config/explain.go new file mode 100644 index 0000000..6ce6e97 --- /dev/null +++ b/config/explain.go @@ -0,0 +1,74 @@ +package config + +import ( + "fmt" + "strings" + + "yetano.dev/yetano/core" + "yetano.dev/yetano/core/paths" +) + +// Explanation is the full, structured report for a doctor-style command +// (spec sections 42/44/45): every configuration layer this Resolver +// considered, plus the paths.Explanation for everything else (Data, +// State, Cache, Runtime, Log, Bin). Building it never mutates the +// filesystem. +type Explanation struct { + Application core.Application + Filename string + Layers []Layer + Selected string // "", if no layer's file exists + Paths paths.Explanation +} + +// Explain resolves every configuration layer and every core/paths +// category and returns a combined, structured report. +func (r *Resolver) Explain() (Explanation, error) { + layers, err := r.layers() + if err != nil { + return Explanation{}, err + } + pathsExplanation, err := r.paths.Explain() + if err != nil { + return Explanation{}, err + } + ex := Explanation{ + Application: r.app, + Filename: r.filename, + Layers: layers, + Paths: pathsExplanation, + } + for _, l := range layers { + if l.Selected { + ex.Selected = l.Path + } + } + return ex, nil +} + +// String renders a human-readable report similar to spec section 44. +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\n", e.Application.Scope) + + b.WriteString("Configuration layers:\n") + for _, l := range e.Layers { + found := "no" + if l.Exists { + found = "yes" + } + fmt.Fprintf(&b, " %s\n priority: %d\n source: %s\n found: %s\n", l.Path, l.Priority, l.Source, found) + } + b.WriteString("\n") + + if e.Selected != "" { + fmt.Fprintf(&b, "Selected:\n %s\n\n", e.Selected) + } else { + b.WriteString("Selected:\n (none found)\n\n") + } + + b.WriteString(e.Paths.String()) + return b.String() +} diff --git a/config/explain_test.go b/config/explain_test.go new file mode 100644 index 0000000..b335205 --- /dev/null +++ b/config/explain_test.go @@ -0,0 +1,39 @@ +package config + +import ( + "path/filepath" + "strings" + "testing" + + "yetano.dev/yetano/core/paths" +) + +func TestConfigExplain(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "port: 8080\n") + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkdirPath(filepath.Join(root, "workdir")), + ) + + ex, err := r.Explain() + if err != nil { + t.Fatalf("Explain: %v", err) + } + if ex.Selected == "" { + t.Fatal("Explain().Selected is empty, want the existing user layer") + } + if want := filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"); ex.Selected != want { + t.Errorf("Explain().Selected = %q, want %q", ex.Selected, want) + } + if len(ex.Paths.Paths) == 0 { + t.Error("Explain().Paths.Paths is empty, want core/paths categories included") + } + + text := ex.String() + if !strings.Contains(text, "Configuration layers:") || !strings.Contains(text, "Selected:") { + t.Errorf("Explain().String() missing expected sections:\n%s", text) + } +} diff --git a/config/layers.go b/config/layers.go new file mode 100644 index 0000000..2e20c65 --- /dev/null +++ b/config/layers.go @@ -0,0 +1,111 @@ +package config + +import ( + "os" + + "yetano.dev/yetano/core" + "yetano.dev/yetano/core/paths" +) + +// Layer is one location in the configuration search/merge hierarchy +// (spec section 48). Search order is descending Priority (first match +// wins); LoadMerged walks the exact same list in reverse (lowest +// priority first, so a higher-priority layer overlays it). +type Layer struct { + Path string + Source paths.Source + Priority int + Exists bool + Selected bool +} + +// PriorityYetanoDefaults is lower than any layer core/paths itself +// resolves (see paths.PrioritySystem), so the shared Yetano config +// directory (spec section 4, opt-in via WithYetanoDefaults) is always +// the last fallback. +const PriorityYetanoDefaults = 0 + +func statExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// layers builds the full, ordered layer list (spec sections 21/22): the +// working directory (if enabled), then core/paths's own ConfigSearchDirs +// for this application (optionally dropping the system-tier layer), then +// -- opt-in only -- the shared Yetano defaults directory. +func (r *Resolver) layers() ([]Layer, error) { + var out []Layer + + if r.workdir { + out = append(out, Layer{ + Path: paths.JoinFamily(r.paths.Platform(), r.workdirPath, r.filename), + Source: paths.WorkingDirectory, + Priority: paths.PriorityWorkingDirectory, + }) + } + + dirs, err := r.paths.ConfigSearchDirs() + if err != nil { + return nil, err + } + for _, d := range dirs { + if !r.systemConfig && d.Priority <= paths.PrioritySystem { + continue + } + out = append(out, Layer{ + Path: paths.JoinDirFile(d.Path, r.filename), + Source: d.Source, + Priority: d.Priority, + }) + } + + if r.yetanoDefaults { + layer, err := r.yetanoDefaultsLayer() + if err != nil { + return nil, err + } + out = append(out, layer) + } + + for i := range out { + out[i].Exists = statExists(out[i].Path) + } + selected := false + for i := range out { + if out[i].Exists && !selected { + out[i].Selected = true + selected = true + } + } + return out, nil +} + +// yetanoDefaultsLayer resolves the ecosystem-wide shared configuration +// directory (spec section 4: "~/.config/yetano/", or the platform +// equivalent) as its own pseudo-Application named "yetano" -- always +// CLI-shaped (XDG-flavored on every OS), since it is a shared, +// admin/CLI-facing location, not tied to any one application's Kind. +func (r *Resolver) yetanoDefaultsLayer() (Layer, error) { + yetanoApp := core.Application{Name: "yetano", Kind: core.CLI, Scope: r.app.Scope} + yp, err := paths.New(yetanoApp, append([]paths.Option{paths.WithEnvironmentProvider(r.env)}, r.pathsOpts...)...) + if err != nil { + return Layer{}, err + } + ex, err := yp.Explain() + if err != nil { + return Layer{}, err + } + var dir string + var source paths.Source + for _, p := range ex.Paths { + if p.Kind == paths.ConfigPath { + dir, source = p.Path, p.Source + } + } + return Layer{ + Path: paths.JoinDirFile(dir, r.filename), + Source: source, + Priority: PriorityYetanoDefaults, + }, nil +} diff --git a/config/merge.go b/config/merge.go new file mode 100644 index 0000000..8015ad3 --- /dev/null +++ b/config/merge.go @@ -0,0 +1,101 @@ +package config + +import ( + "fmt" + "os" + + "gopkg.in/yaml.v3" +) + +// mergeMaps overlays over onto base in place and returns base (spec +// section 28's V1 merge semantics): +// +// - scalars: the higher-priority layer's value replaces the lower one. +// - maps: merged recursively, key by key. +// - lists: replaced wholesale by the higher-priority layer's list -- +// never concatenated element-by-element. +// - explicit YAML null: removes the key from the merged result (a +// layer can use "key: null" to intentionally unset a lower layer's +// value), rather than being stored as a literal nil. +// +// over is expected to be the *higher-priority* layer; base accumulates +// lower-priority layers applied first, per LoadMerged's lowest-to- +// highest iteration order. +func mergeMaps(base, over map[string]any) map[string]any { + if base == nil { + base = map[string]any{} + } + for k, v := range over { + if v == nil { + delete(base, k) + continue + } + if overMap, ok := v.(map[string]any); ok { + if baseMap, ok := base[k].(map[string]any); ok { + base[k] = mergeMaps(baseMap, overMap) + continue + } + } + base[k] = v + } + return base +} + +// readLayer reads and parses path as a YAML mapping, returning an empty +// map (not an error) if the file does not exist -- callers already know +// which layers exist via Layer.Exists; this is a convenience for callers +// that don't check first. +func readLayer(path string) (map[string]any, error) { + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + return map[string]any{}, nil + } + if err != nil { + return nil, fmt.Errorf("config: read %s: %w", path, err) + } + var m map[string]any + if err := yaml.Unmarshal(data, &m); err != nil { + return nil, fmt.Errorf("config: parse %s: %w", path, err) + } + if m == nil { + m = map[string]any{} + } + return m, nil +} + +// LoadMerged loads every existing layer, lowest priority first, merging +// each one on top of the last (spec sections 27/28), optionally +// expanding ${VAR}/$VAR in string values (WithEnvExpansion, default +// on), and unmarshals the merged result into target (a pointer, as for +// yaml.Unmarshal). +func (r *Resolver) LoadMerged(target any) error { + all, err := r.layers() + if err != nil { + return err + } + + merged := map[string]any{} + for i := len(all) - 1; i >= 0; i-- { + l := all[i] + if !l.Exists { + continue + } + m, err := readLayer(l.Path) + if err != nil { + return err + } + if r.envExpansion { + m = expandTree(m, r.env).(map[string]any) + } + merged = mergeMaps(merged, m) + } + + data, err := yaml.Marshal(merged) + if err != nil { + return fmt.Errorf("config: re-marshal merged result: %w", err) + } + if err := yaml.Unmarshal(data, target); err != nil { + return fmt.Errorf("config: unmarshal merged result: %w", err) + } + return nil +} diff --git a/config/merge_test.go b/config/merge_test.go new file mode 100644 index 0000000..cdb4102 --- /dev/null +++ b/config/merge_test.go @@ -0,0 +1,97 @@ +package config + +import ( + "path/filepath" + "testing" + + "yetano.dev/yetano/core/paths" +) + +func TestMergeScalarOverride(t *testing.T) { + base := map[string]any{"port": 8080} + over := map[string]any{"port": 9090} + got := mergeMaps(base, over) + if got["port"] != 9090 { + t.Errorf("port = %v, want 9090", got["port"]) + } +} + +func TestMergeNestedMap(t *testing.T) { + base := map[string]any{ + "http": map[string]any{"host": "0.0.0.0", "port": 8080, "tls": false}, + } + over := map[string]any{ + "http": map[string]any{"port": 9090}, + } + got := mergeMaps(base, over) + httpMap := got["http"].(map[string]any) + if httpMap["host"] != "0.0.0.0" { + t.Errorf("host = %v, want 0.0.0.0 (should survive from base)", httpMap["host"]) + } + if httpMap["port"] != 9090 { + t.Errorf("port = %v, want 9090", httpMap["port"]) + } + if httpMap["tls"] != false { + t.Errorf("tls = %v, want false (should survive from base)", httpMap["tls"]) + } +} + +func TestMergeListReplacesWhollyNoConcatenation(t *testing.T) { + base := map[string]any{"registries": []any{"a", "b"}} + over := map[string]any{"registries": []any{"c"}} + got := mergeMaps(base, over) + list := got["registries"].([]any) + if len(list) != 1 || list[0] != "c" { + t.Errorf("registries = %v, want [c] (full replace, no concatenation)", list) + } +} + +func TestMergeNullRemovesKey(t *testing.T) { + base := map[string]any{"ca_cert": "/etc/ssl/ca.pem", "port": 8080} + over := map[string]any{"ca_cert": nil} + got := mergeMaps(base, over) + if _, exists := got["ca_cert"]; exists { + t.Errorf("ca_cert = %v, want key removed entirely", got["ca_cert"]) + } + if got["port"] != 8080 { + t.Errorf("port = %v, want 8080 (untouched)", got["port"]) + } +} + +func TestLoadMergedEndToEnd(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "http:\n host: 0.0.0.0\n port: 8080\n tls: false\nregistries:\n - a\n - b\n") + writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "http:\n port: 9090\nregistries:\n - c\n") + + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkingDirectory(false), + ) + + type httpConfig struct { + Host string `yaml:"host"` + Port int `yaml:"port"` + TLS bool `yaml:"tls"` + } + var target struct { + HTTP httpConfig `yaml:"http"` + Registries []string `yaml:"registries"` + } + if err := r.LoadMerged(&target); err != nil { + t.Fatalf("LoadMerged: %v", err) + } + if target.HTTP.Host != "0.0.0.0" { + t.Errorf("HTTP.Host = %q, want 0.0.0.0", target.HTTP.Host) + } + if target.HTTP.Port != 9090 { + t.Errorf("HTTP.Port = %d, want 9090", target.HTTP.Port) + } + if target.HTTP.TLS != false { + t.Errorf("HTTP.TLS = %v, want false", target.HTTP.TLS) + } + if len(target.Registries) != 1 || target.Registries[0] != "c" { + t.Errorf("Registries = %v, want [c]", target.Registries) + } +} diff --git a/config/resolve.go b/config/resolve.go new file mode 100644 index 0000000..3e3a475 --- /dev/null +++ b/config/resolve.go @@ -0,0 +1,25 @@ +package config + +// Resolve returns the highest-priority existing configuration file +// (spec section 25). found is false if no layer's file exists -- this is +// not an error; callers decide whether "no configuration file" is fine. +func (r *Resolver) Resolve() (layer Layer, found bool, err error) { + all, err := r.layers() + if err != nil { + return Layer{}, false, err + } + for _, l := range all { + if l.Exists { + return l, true, nil + } + } + return Layer{}, false, nil +} + +// ResolveAll returns every layer in the priority hierarchy, highest +// priority first, whether or not the file exists there (spec section +// 26) -- e.g. for a `doctor`-style report of every location that was +// considered. +func (r *Resolver) ResolveAll() ([]Layer, error) { + return r.layers() +} diff --git a/config/resolve_test.go b/config/resolve_test.go new file mode 100644 index 0000000..aeaa0aa --- /dev/null +++ b/config/resolve_test.go @@ -0,0 +1,193 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "yetano.dev/yetano/core" + "yetano.dev/yetano/core/paths" +) + +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 writeFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestLinuxLayerOrder(t *testing.T) { + root := t.TempDir() + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkdirPath(filepath.Join(root, "workdir")), + ) + + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + want := []string{ + filepath.Join(root, "workdir", "yet.yaml"), + filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), + filepath.Join(root, "etc", "yet", "yet.yaml"), + } + if len(layers) != len(want) { + t.Fatalf("ResolveAll() = %v, want %v", layers, want) + } + for i, w := range want { + if layers[i].Path != w { + t.Errorf("layers[%d].Path = %q, want %q", i, layers[i].Path, w) + } + } +} + +func TestWorkdirDisabled(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "workdir", "yet.yaml"), "ignored: true\n") + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkdirPath(filepath.Join(root, "workdir")), + WithWorkingDirectory(false), + ) + + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + for _, l := range layers { + if l.Source == paths.WorkingDirectory { + t.Fatalf("ResolveAll() included a working-directory layer despite WithWorkingDirectory(false): %v", layers) + } + } +} + +func TestSystemConfigDisabled(t *testing.T) { + root := t.TempDir() + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithSystemConfig(false), + ) + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + for _, l := range layers { + if l.Priority <= paths.PrioritySystem { + t.Errorf("ResolveAll() included a system layer despite WithSystemConfig(false): %v", layers) + } + } +} + +func TestResolveFirstMatch(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "layer: system\n") + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkdirPath(filepath.Join(root, "workdir")), + ) + + layer, found, err := r.Resolve() + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if !found { + t.Fatal("Resolve() found = false, want true") + } + if want := filepath.Join(root, "etc", "yet", "yet.yaml"); layer.Path != want { + t.Errorf("Resolve().Path = %q, want %q", layer.Path, want) + } + + writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "layer: user\n") + layer, found, err = r.Resolve() + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if !found { + t.Fatal("Resolve() found = false, want true") + } + if want := filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"); layer.Path != want { + t.Errorf("Resolve().Path = %q, want %q (user should now win over system)", layer.Path, want) + } +} + +func TestResolveNotFoundIsNotAnError(t *testing.T) { + root := t.TempDir() + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkdirPath(filepath.Join(root, "workdir")), + ) + _, found, err := r.Resolve() + if err != nil { + t.Fatalf("Resolve() error = %v, want nil", err) + } + if found { + t.Fatalf("Resolve() found = true, want false") + } +} + +func TestYetanoDefaultsFallbackLayer(t *testing.T) { + root := t.TempDir() + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithWorkdirPath(filepath.Join(root, "workdir")), + WithYetanoDefaults(true), + ) + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + last := layers[len(layers)-1] + if want := filepath.Join(root, "home", "test", ".config", "yetano", "yet.yaml"); last.Path != want { + t.Errorf("last layer = %q, want %q", last.Path, want) + } + if last.Priority != PriorityYetanoDefaults { + t.Errorf("last layer priority = %d, want %d", last.Priority, PriorityYetanoDefaults) + } +} + +func TestWithFilename(t *testing.T) { + root := t.TempDir() + env := map[string]string{"HOME": "/home/test"} + r := mustResolver(t, yetApp(), + WithEnvironment(env), + WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)), + WithFilename("repositories.yaml"), + WithWorkingDirectory(false), + ) + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + if want := filepath.Join(root, "home", "test", ".config", "yet", "repositories.yaml"); layers[0].Path != want { + t.Errorf("layers[0].Path = %q, want %q", layers[0].Path, want) + } +} diff --git a/config/windows_test.go b/config/windows_test.go new file mode 100644 index 0000000..1ab3c9e --- /dev/null +++ b/config/windows_test.go @@ -0,0 +1,78 @@ +package config + +import ( + "testing" + + "yetano.dev/yetano/core/paths" +) + +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 TestWindowsSearchOrder(t *testing.T) { + r := mustResolver(t, yetApp(), + WithEnvironment(windowsEnv()), + WithPathsOptions(paths.WithPlatform("windows")), + WithWorkdirPath(`C:\work\project`), + ) + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + want := []string{ + `C:\work\project\yet.yaml`, + `C:\Users\test\AppData\Local\yet\yet.yaml`, + `C:\Users\test\AppData\Roaming\yet\yet.yaml`, + `C:\ProgramData\yet\yet.yaml`, + } + if len(layers) != len(want) { + t.Fatalf("ResolveAll() = %v, want %v", layers, want) + } + for i, w := range want { + if layers[i].Path != w { + t.Errorf("layers[%d].Path = %q, want %q", i, layers[i].Path, w) + } + } +} + +func TestWindowsMergeOrderIsSearchOrderReversed(t *testing.T) { + r := mustResolver(t, yetApp(), + WithEnvironment(windowsEnv()), + WithPathsOptions(paths.WithPlatform("windows")), + WithWorkdirPath(`C:\work\project`), + ) + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + for i := 0; i < len(layers)-1; i++ { + if layers[i].Priority < layers[i+1].Priority { + t.Fatalf("ResolveAll() not in descending priority order: %v", layers) + } + } +} + +func TestWindowsPathSeparatorsNeverForwardSlash(t *testing.T) { + r := mustResolver(t, yetApp(), + WithEnvironment(windowsEnv()), + WithPathsOptions(paths.WithPlatform("windows")), + WithWorkdirPath(`C:\work\project`), + ) + layers, err := r.ResolveAll() + if err != nil { + t.Fatalf("ResolveAll: %v", err) + } + for _, l := range layers { + for _, c := range l.Path { + if c == '/' { + t.Errorf("layer path %q contains a forward slash", l.Path) + } + } + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a518208 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module yetano.dev/yetano/core + +go 1.25.0 + +require gopkg.in/yaml.v3 v3.0.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a62c313 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/paths/categories.go b/paths/categories.go new file mode 100644 index 0000000..fc71d6f --- /dev/null +++ b/paths/categories.go @@ -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/ (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() +} diff --git a/paths/coverage_test.go b/paths/coverage_test.go new file mode 100644 index 0000000..a135fbd --- /dev/null +++ b/paths/coverage_test.go @@ -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) + } +} diff --git a/paths/darwin.go b/paths/darwin.go new file mode 100644 index 0000000..ee104ec --- /dev/null +++ b/paths/darwin.go @@ -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 +} diff --git a/paths/darwin_test.go b/paths/darwin_test.go new file mode 100644 index 0000000..fa714ed --- /dev/null +++ b/paths/darwin_test.go @@ -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) + } +} diff --git a/paths/env.go b/paths/env.go new file mode 100644 index 0000000..e1ff2bf --- /dev/null +++ b/paths/env.go @@ -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 +} diff --git a/paths/errors.go b/paths/errors.go new file mode 100644 index 0000000..4e71f38 --- /dev/null +++ b/paths/errors.go @@ -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") diff --git a/paths/explain.go b/paths/explain.go new file mode 100644 index 0000000..ca8da3a --- /dev/null +++ b/paths/explain.go @@ -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() +} diff --git a/paths/explain_test.go b/paths/explain_test.go new file mode 100644 index 0000000..55a253e --- /dev/null +++ b/paths/explain_test.go @@ -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) + } +} diff --git a/paths/freebsd.go b/paths/freebsd.go new file mode 100644 index 0000000..fb1dca1 --- /dev/null +++ b/paths/freebsd.go @@ -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", +} diff --git a/paths/join.go b/paths/join.go new file mode 100644 index 0000000..88caa7b --- /dev/null +++ b/paths/join.go @@ -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) +} diff --git a/paths/join_test.go b/paths/join_test.go new file mode 100644 index 0000000..cbbf121 --- /dev/null +++ b/paths/join_test.go @@ -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) + } +} diff --git a/paths/knownfolders_windows.go b/paths/knownfolders_windows.go new file mode 100644 index 0000000..ce836ef --- /dev/null +++ b/paths/knownfolders_windows.go @@ -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 +} diff --git a/paths/layout.go b/paths/layout.go new file mode 100644 index 0000000..6af35a5 --- /dev/null +++ b/paths/layout.go @@ -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_*/_* 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) +} diff --git a/paths/linux.go b/paths/linux.go new file mode 100644 index 0000000..26164d8 --- /dev/null +++ b/paths/linux.go @@ -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", +} diff --git a/paths/paths.go b/paths/paths.go new file mode 100644 index 0000000..b3eef8b --- /dev/null +++ b/paths/paths.go @@ -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: +// +// - Dir() returns the single, preferred location a new file +// in that category would be written to. +// - 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%\ directory, while +// ConfigSearchDirs() additionally includes %LOCALAPPDATA%\ (a +// machine-specific override layer, checked first) and %PROGRAMDATA%\ +// (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 +} diff --git a/paths/resolver.go b/paths/resolver.go new file mode 100644 index 0000000..4780b6b --- /dev/null +++ b/paths/resolver.go @@ -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 "_CONFIG_HOME", "_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) } diff --git a/paths/search.go b/paths/search.go new file mode 100644 index 0000000..724e147 --- /dev/null +++ b/paths/search.go @@ -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) +} diff --git a/paths/search_test.go b/paths/search_test.go new file mode 100644 index 0000000..89d02f9 --- /dev/null +++ b/paths/search_test.go @@ -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") + } +} diff --git a/paths/unix.go b/paths/unix.go new file mode 100644 index 0000000..00bba8a --- /dev/null +++ b/paths/unix.go @@ -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//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/) -- 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 +} diff --git a/paths/unix_test.go b/paths/unix_test.go new file mode 100644 index 0000000..15583cf --- /dev/null +++ b/paths/unix_test.go @@ -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) + } +} diff --git a/paths/windows.go b/paths/windows.go new file mode 100644 index 0000000..addac5e --- /dev/null +++ b/paths/windows.go @@ -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\, falling back to PROGRAMDATA\ 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%\ 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 +} diff --git a/paths/windows_test.go b/paths/windows_test.go new file mode 100644 index 0000000..d075331 --- /dev/null +++ b/paths/windows_test.go @@ -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 +}