core/configcmd: "<program> config create|validate|upgrade|path" from a Spec (name, application, minimal/full templates, Validate, Schema), taken over from yamase-core/pkg/configcmd and generalized: Filename, Optional (programs that run on defaults) and None (no configuration). core/version: "<program> version [--json]" over the values each program stamps into its internal/version; JSON keys match yasta's existing output (yavebu reads it), VCS fallback for unstamped builds. paths: macOS CLI/Service system-scope RuntimeDir is /var/run/<app> instead of /run/<app>, which macOS does not have. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 KiB
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
.gofile, organized by name for readability (unix.go,linux.go,freebsd.go,darwin.go,windows.go) but selected at runtime byResolver.platform(runtime.GOOSby default, overridable viapaths.WithPlatformfor tests/simulation). - All environment lookups go through the injectable
Environmentinterface (paths.WithEnvironment/WithEnvironmentProvider), neveros.Getenvdirectly. - 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 injoin.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 viaSHGetKnownFolderPath,//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 withoutAPPDATAset) -- 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.
WithRoot: root's family is the real host's, not the simulated one
WithRoot sandboxes real filesystem I/O (for Ensure*, FindFile,
Explain) under a directory while WithPlatform simulates a
different platform's path logic -- e.g. WithPlatform("linux") with
WithRoot(t.TempDir()) on any host, so Linux-shaped path logic can be
exercised with real file I/O on whatever host runs the test. The
resolved path being rebased (p) is always in r.platform's simulated
family, but root itself -- almost always t.TempDir(), or otherwise a
literal, real filesystem location the caller chose -- is always in the
REAL host's native family, which does not have to match r.platform.
applyRoot (via applyRootRebase in join.go) therefore decomposes
p into plain path segments (discarding its own absolute-path root
marker) and re-joins them onto root using root's own family,
inferred from its content the same way JoinDirFile infers a
directory's family -- never from r.platform. This is the only
correct choice: root must end up as a single, valid, real path the
actual host filesystem can use, regardless of which platform's path
shape is being simulated for everything above it.
Two consequences fall out of this and are easy to reintroduce by accident:
- Any code that joins one more suffix onto an already-rooted value
(e.g.
logDirUnixbuilding<StateDir>/log, ordarwinDesktopStateDir/darwinDesktopRuntimeDir's fallback building<AppDir>/State/<AppDir>/Runtime) must useJoinDirFile, not a hardcodedunixJoin/windowsJoin-- the already-rooted value's family now depends onroot's family, not onr.platform. core/config's working-directory layer has the identical concern one level up:r.workdirPathcan be a real filesystem path (e.g. underWithRoot's root) whose family may not matchr.paths.Platform().paths.JoinDirFileFamilyhandles this: it behaves likeJoinDirFilewheneverdircarries its own separator, falling back toJoinFamily's platform-driven choice only whendiris ambiguous (no separator at all, e.g. the default".").
This was a real, previously-invisible bug (mixed-separator and, in one
override case, outright invalid paths) that macOS/Linux test runs could
never surface, because t.TempDir() there happens to already share the
simulated Unix family with whatever was under test. It was only found
by running this package's own test suite on a real Windows host for the
first time (see TODO.md) -- worth remembering next time "verified via
GOOS=windows go build/go vet" is mistaken for "verified on Windows."
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
<Category>Dir()/<Category>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/<app> 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/<app>, %APPDATA%\<app>, ...). 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/<App> 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.
macOS Desktop RuntimeDir: $TMPDIR, not a persistent placeholder
Unlike Unix's XDG_RUNTIME_DIR, macOS has no documented per-app ephemeral
runtime directory convention -- but it does hand every process a real
equivalent: $TMPDIR, the per-user, securely permissioned (0700),
OS-managed directory confstr(_CS_DARWIN_USER_TEMP_DIR) resolves and
NSTemporaryDirectory() returns. darwinDesktopRuntimeDir() prefers it
(joined with the app name) over the previous placeholder,
~/Library/Application Support/<App>/Runtime -- a persistent directory
that misrepresented "ephemeral" -- falling back to that placeholder only
when TMPDIR is absent from the resolved environment (a
simulated/test environment that never set it; a real macOS process
always has it set).
LogAliasDir is resolved separately from being created
LogAliasDir() (the optional ~/.local/log/<app> convenience symlink
target, spec section 39) stays a pure computation like every other
*Dir() method -- resolving it never touches the filesystem. Creating
the actual symlink is EnsureLogAlias()'s job, kept separate and
explicit for the same reason every other Ensure* method is separate
from its *Dir() counterpart (see "No implicit filesystem mutation" in
the package doc comment): a caller that only wants to know the path
(e.g. to show it in doctor/Explain output) should never risk
creating a symlink as a side effect.
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 <os>.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.
Standard commands: one implementation, program-specific data
manual, completion, doctor, configcmd and version implement
the commands every Yetano program offers (docs/program-conventions.md in
the meta-repository). Each takes the program's own part as plain data
(an embedded FS, a command tree, a report, a configcmd.Spec, a
version.Info) and returns an exit code; none depends on cobra or on a
program's flag parser, so a flag-only daemon and a cobra CLI wire them
the same way. They never mutate the filesystem except where the command
exists to do so (config create, config upgrade --write).
configcmd keeps the config schema in the program: core only knows the
YAML tree, the templates and, via reflection on the program's struct,
which keys exist. It started as yamase-core/pkg/configcmd and moved
here unchanged in behavior when the other meta-repos needed it.