# yetano.dev/yetano/core 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 yetano.dev/yetano/core/manual yetano.dev/yetano/core/completion yetano.dev/yetano/core/doctor yetano.dev/yetano/core/secretref ``` 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. Without a home directory (`HOME`/`USERPROFILE` unset, and no override for the user tier), the search lists simply omit the user tier and still report the system tier -- a system service started without `HOME` keeps finding `/etc/`. The canonical `Dir()` methods still return `paths.ErrNoHomeDirectory` in that case; a write location is never silently swapped for a different tier. ### 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/ $TMPDIR/ (Runtime -- see below) ``` ### 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); macOS Desktop resolves it from `$TMPDIR` (see ARCHITECTURE.md), the same OS-managed ephemeral directory `NSTemporaryDirectory()` returns. ### LogAliasDir `LogAliasDir()` resolves the optional Unix convenience symlink target `~/.local/log/` (spec section 39) without touching the filesystem, same as every other `*Dir()` method. `EnsureLogAlias()` creates the actual `LogDir()` symlink there if nothing exists yet, and is a no-op `EnsureLogDir()` equivalent on Windows/macOS Desktop, where the two already coincide. ### 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 strategy" section for why, and the package's own tests for how Windows/macOS/FreeBSD path logic is verified while running on any host. Combine `WithPlatform` with `WithRoot(t.TempDir())` to also sandbox real filesystem I/O (`Ensure*`, `FindFile`, `Explain`) while simulating a different platform's path *logic* than the host actually running the test. `root` there is always in the real host's native address family (whatever `t.TempDir()` returns), which need not match the simulated platform's family -- `WithRoot` handles that mismatch correctly (see ARCHITECTURE.md's "WithRoot: root's family is the real host's"), so the combination is always safe to use. ## 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)`. ## core/manual: the " manual" command Every Yetano program serves its own documentation (ADR-0012), embedded in the binary. `core/manual` is that command in one shared shape: ```go // at the module root (go:embed can't reach parent directories): //go:embed README.md docs var docsFS embed.FS var Manual = manual.MustFromFS("yasl", docsFS) // in the CLI dispatch: case "manual", "doc": if err := yasl.Manual.Run(args[1:], os.Stdout); err != nil { ... exit non-zero ... } ``` `FromFS` makes `README.md` the topic `readme` and every `docs/**/*.md` a topic (slug = path below `docs/` without `.md`, title = first `#` heading). `Run` serves `manual`, `manual ` and `manual --json [topic]`; the JSON form (`[{slug,title,path}]` / `{slug,title,path, markdown}`) is what yet reads to show an installed program's manual (`yet manual --package`, its TUI and yet-gui). ## core/completion and core/doctor The other two standard commands of every Yetano program (see docs/program-conventions.md in the meta-repository): - `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or PowerShell completion script generated from a static `completion.Tree` of the program's commands. - `doctor.Report` collects the locations the program resolves (`AddPaths(app)` adds the standard `core/paths` ones) and named checks; `Run(args, stdout, stderr)` prints a table or `--json` and returns the exit code (0 all good, 1 a check failed, 2 usage). ## 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. ## core/secretref Resolves secret references in a program's configuration, so a token or password never has to be written into a config file in plain text: | Form | Value from | |---|---| | `secret://` | yaseva (`yaseva [--config ] get `, run as a subprocess) | | `env:` | the process environment | | `file:` | a file (`~` expanded, trailing newline trimmed) | | `base64:` | the value itself, base64 (standard or URL alphabet) -- out of plain sight, not protected | ```go r := secretref.New("") // "yaseva" from PATH token, err := r.ResolveString(ctx, cfg.Token) log.Print(r.Redact(err.Error())) // resolved values become "***" ``` `Validate` accepts only these forms. A program that must keep reading plain values it accepted before checks `IsReference` and treats anything else as a literal. Used by yavebu (its own copy predates this package), yacry and yadenes.