Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90132e2d76 | ||
|
|
ca0f06f978 | ||
|
|
58dfe0f5a6 | ||
|
|
43775950a4 | ||
|
|
13c1862c74 | ||
|
|
e757fdd025 | ||
|
|
e8bf23a064 | ||
|
|
72b656262d | ||
|
|
da2ec85381 | ||
|
|
e6b5324ad3 | ||
|
|
689469eb32 |
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
# local claude --resume helper
|
||||||
|
resume.sh
|
||||||
@@ -68,6 +68,52 @@ wrapper legitimately needs a build tag; a string-joining decision does
|
|||||||
not, and gating it behind one would break the testability requirement
|
not, and gating it behind one would break the testability requirement
|
||||||
elsewhere in the same spec.
|
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. `logDirUnix` building `<StateDir>/log`, or
|
||||||
|
`darwinDesktopStateDir`/`darwinDesktopRuntimeDir`'s fallback building
|
||||||
|
`<AppDir>/State`/`<AppDir>/Runtime`) must use `JoinDirFile`, not a
|
||||||
|
hardcoded `unixJoin`/`windowsJoin` -- the already-rooted value's family
|
||||||
|
now depends on `root`'s family, not on `r.platform`.
|
||||||
|
- `core/config`'s working-directory layer has the identical concern one
|
||||||
|
level up: `r.workdirPath` can be a real filesystem path (e.g. under
|
||||||
|
`WithRoot`'s root) whose family may not match `r.paths.Platform()`.
|
||||||
|
`paths.JoinDirFileFamily` handles this: it behaves like `JoinDirFile`
|
||||||
|
whenever `dir` carries its own separator, falling back to
|
||||||
|
`JoinFamily`'s platform-driven choice only when `dir` is 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
|
## Canonical directory vs. search directories
|
||||||
|
|
||||||
This is the single most important distinction in the API (see
|
This is the single most important distinction in the API (see
|
||||||
@@ -140,6 +186,32 @@ macOS don't have this ambiguity (there's no "session runtime directory
|
|||||||
that may not exist" convention to get wrong there), so `RuntimeDir()`
|
that may not exist" convention to get wrong there), so `RuntimeDir()`
|
||||||
always succeeds on those platforms.
|
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
|
## Unix system-scope directories follow each OS's own convention
|
||||||
|
|
||||||
Linux SystemScope uses the FHS layout (`/etc`, `/var/lib`, `/var/cache`,
|
Linux SystemScope uses the FHS layout (`/etc`, `/var/lib`, `/var/cache`,
|
||||||
@@ -162,3 +234,19 @@ test file). This is spec section 47's explicit requirement, and it's
|
|||||||
why `Explain` and `Ensure*` are entirely separate code paths: the former
|
why `Explain` and `Ensure*` are entirely separate code paths: the former
|
||||||
must never accidentally gain a side effect by sharing implementation
|
must never accidentally gain a side effect by sharing implementation
|
||||||
with the latter.
|
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.
|
||||||
@@ -6,13 +6,23 @@ and platform integration -- not just a grab-bag of utility functions (see
|
|||||||
`AGENTS.md` in the meta-repository root, and [ARCHITECTURE.md](ARCHITECTURE.md)
|
`AGENTS.md` in the meta-repository root, and [ARCHITECTURE.md](ARCHITECTURE.md)
|
||||||
for the full design rationale).
|
for the full design rationale).
|
||||||
|
|
||||||
The first area covered is **platform-independent path, file, and
|
It covers **platform-independent path, file, and configuration
|
||||||
configuration resolution**: `core/paths` and `core/config`.
|
resolution** (`core/paths`, `core/config`), the **standard commands**
|
||||||
|
every Yetano program offers (`core/manual`, `core/completion`,
|
||||||
|
`core/doctor`, `core/configcmd`, `core/version`; see
|
||||||
|
docs/program-conventions.md in the meta-repository), and secret
|
||||||
|
references in configuration (`core/secretref`).
|
||||||
|
|
||||||
```text
|
```text
|
||||||
yetano.dev/yetano/core
|
yetano.dev/yetano/core
|
||||||
yetano.dev/yetano/core/paths
|
yetano.dev/yetano/core/paths
|
||||||
yetano.dev/yetano/core/config
|
yetano.dev/yetano/core/config
|
||||||
|
yetano.dev/yetano/core/manual
|
||||||
|
yetano.dev/yetano/core/completion
|
||||||
|
yetano.dev/yetano/core/doctor
|
||||||
|
yetano.dev/yetano/core/configcmd
|
||||||
|
yetano.dev/yetano/core/version
|
||||||
|
yetano.dev/yetano/core/secretref
|
||||||
```
|
```
|
||||||
|
|
||||||
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||||
@@ -59,6 +69,13 @@ write location) and, for Config/Data/executables,
|
|||||||
search, highest priority first). These are not always the same
|
search, highest priority first). These are not always the same
|
||||||
location -- see "Windows" below.
|
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/<app>`. The canonical `<Category>Dir()` methods still
|
||||||
|
return `paths.ErrNoHomeDirectory` in that case; a write location is never
|
||||||
|
silently swapped for a different tier.
|
||||||
|
|
||||||
### Environment variable priority
|
### Environment variable priority
|
||||||
|
|
||||||
Every canonical category is resolved through the same chain, highest
|
Every canonical category is resolved through the same chain, highest
|
||||||
@@ -108,6 +125,7 @@ native GUI app) uses `~/Library/...`:
|
|||||||
~/Library/Application Support/<App>/State
|
~/Library/Application Support/<App>/State
|
||||||
~/Library/Caches/<App>
|
~/Library/Caches/<App>
|
||||||
~/Library/Logs/<App>
|
~/Library/Logs/<App>
|
||||||
|
$TMPDIR/<App> (Runtime -- see below)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Windows
|
### Windows
|
||||||
@@ -138,7 +156,19 @@ machine-local override layer. Data/State/Cache/Log/Runtime live under
|
|||||||
Unix, without an explicit override and without `XDG_RUNTIME_DIR` set, it
|
Unix, without an explicit override and without `XDG_RUNTIME_DIR` set, it
|
||||||
returns `paths.ErrRuntimeDirUnavailable` -- callers decide what to do.
|
returns `paths.ErrRuntimeDirUnavailable` -- callers decide what to do.
|
||||||
Windows and macOS always resolve a runtime directory (no equivalent
|
Windows and macOS always resolve a runtime directory (no equivalent
|
||||||
"may legitimately not exist" case there).
|
"may legitimately not exist" case there; macOS CLI/Service system scope
|
||||||
|
uses `/var/run/<app>`, since macOS has no `/run`); 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/<app>` (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
|
### Explain / doctor
|
||||||
|
|
||||||
@@ -155,10 +185,19 @@ existence/permission checks.
|
|||||||
Every platform code path is a plain function of an injectable
|
Every platform code path is a plain function of an injectable
|
||||||
`Environment` (env vars) and an injectable platform string
|
`Environment` (env vars) and an injectable platform string
|
||||||
(`paths.WithPlatform("windows")`), not `runtime.GOOS`/`os.Getenv`
|
(`paths.WithPlatform("windows")`), not `runtime.GOOS`/`os.Getenv`
|
||||||
directly -- see ARCHITECTURE.md's "Platform simulation" section for why,
|
directly -- see ARCHITECTURE.md's "Platform strategy" section for why,
|
||||||
and the package's own tests for how Windows/macOS/FreeBSD path logic is
|
and the package's own tests for how Windows/macOS/FreeBSD path logic is
|
||||||
verified while running on any host.
|
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
|
## core/config: finding and layering configuration files
|
||||||
|
|
||||||
```go
|
```go
|
||||||
@@ -216,6 +255,82 @@ ecosystem-wide, shared settings (`repositories.yaml`, `trust.yaml`,
|
|||||||
layered into, any one application's own configuration. An application
|
layered into, any one application's own configuration. An application
|
||||||
opts in explicitly with `config.WithYetanoDefaults(true)`.
|
opts in explicitly with `config.WithYetanoDefaults(true)`.
|
||||||
|
|
||||||
|
## core/manual: the "<program> 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 <topic>` 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).
|
||||||
|
|
||||||
|
## core/configcmd: "<program> config"
|
||||||
|
|
||||||
|
`config create [--minimal|--full] [--force] [--output <file>]`,
|
||||||
|
`config validate`, `config upgrade [--write]` and `config path` for
|
||||||
|
every program, from one `configcmd.Spec`: the program's name and
|
||||||
|
`core.Application` (file name and directories), a minimal and a full
|
||||||
|
template, its `Validate(path)` function and, optionally, its config
|
||||||
|
struct as `Schema` (unknown-option detection, operator-named maps in
|
||||||
|
`upgrade`). `Spec.Optional` is for programs that also run without a
|
||||||
|
file, `Spec.None` for programs without configuration (the command then
|
||||||
|
says so). `Spec.Find` is the lookup a program should also use at
|
||||||
|
startup, so `config path` and the program always agree.
|
||||||
|
|
||||||
|
```go
|
||||||
|
spec := configcmd.Spec{
|
||||||
|
Name: "yasl", App: app,
|
||||||
|
Minimal: config.MinimalTemplate, Full: config.FullTemplate,
|
||||||
|
Validate: func(path string) error { _, err := config.Load(path); return err },
|
||||||
|
Schema: config.Config{},
|
||||||
|
}
|
||||||
|
os.Exit(configcmd.Run(spec, configFlag, args, os.Stdout, os.Stderr))
|
||||||
|
```
|
||||||
|
|
||||||
|
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
|
||||||
|
config.Config{})` and expect nothing, so every option stays documented
|
||||||
|
in the full template -- that is what keeps `config upgrade` useful.
|
||||||
|
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
|
||||||
|
report options the program ignores. Taken over from
|
||||||
|
`yamase-core/pkg/configcmd`, which now wraps it.
|
||||||
|
|
||||||
|
## core/version: "<program> version [--json]"
|
||||||
|
|
||||||
|
The values stay in each program's `internal/version` (stamped with
|
||||||
|
`-ldflags -X`); `version.Info{Program, Version, Commit, BuildDate,
|
||||||
|
Contracts}.Run(args, stdout, stderr)` prints them as text or `--json`
|
||||||
|
(`program`, `version`, `commit`, `build_date`, `go`, `platform`,
|
||||||
|
`contracts` for Verse programs). Unstamped builds fall back to the VCS
|
||||||
|
revision Go embeds; a leading "v" is dropped. `Info.Short()` is the
|
||||||
|
one-line form for log lines and web UI footers.
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
- Environment expansion is variable substitution only -- never shell
|
- Environment expansion is variable substitution only -- never shell
|
||||||
@@ -235,3 +350,26 @@ opts in explicitly with `config.WithYetanoDefaults(true)`.
|
|||||||
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
||||||
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
||||||
force-moved to a different commit.
|
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://<name>` | yaseva (`yaseva [--config <file>] get <name>`, run as a subprocess) |
|
||||||
|
| `env:<VARIABLE>` | the process environment |
|
||||||
|
| `file:<path>` | a file (`~` expanded, trailing newline trimmed) |
|
||||||
|
| `base64:<value>` | 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,
|
||||||
|
yacry and yadenes.
|
||||||
@@ -6,41 +6,60 @@ speculatively.
|
|||||||
|
|
||||||
## Migration
|
## Migration
|
||||||
|
|
||||||
- **Migrate `yet` onto `core/paths`/`core/config`.** `yet`'s
|
- [x] **Migrate `yet` onto `core/paths`/`core/config`.** `internal/config`
|
||||||
`internal/store.Home()` (`$YETANO_HOME`, defaulting to
|
already used `core/config`/`core/paths` (shared `Application{Name:
|
||||||
`os.UserConfigDir()/yetano`) and `internal/config` (fixed
|
"yetano"}`). `internal/store`'s own `$YETANO_HOME` (formerly
|
||||||
`/etc/yetano/yetano.yaml` -> `~/.config/yetano/yetano.yaml` ->
|
`os.UserConfigDir()/yetano`, one monolithic root) has now been split
|
||||||
`./yetano.yaml` -> `--config` cascade) predate this library and
|
across three independently overridable `core/paths` categories for
|
||||||
overlap with what it now provides. Migrating is a deliberately
|
`Application{Name: "yet", Kind: core.CLI}`: `store.Home()` (`DataDir`;
|
||||||
separate follow-up, not part of this change -- `yet`'s existing
|
store/packages/profiles/sources/credentials/trust-policy/deployments/
|
||||||
behavior needs to be evaluated field-by-field (e.g. `$YETANO_HOME`'s
|
share-lib-etc), `store.CacheHome()` (`CacheDir`; the blob cache), and
|
||||||
default of `os.UserConfigDir()/yetano` is *not* the same location
|
`store.BinDir()` (`BinDir`; managed command entrypoints, shared across
|
||||||
`core/paths` would resolve for an app named "yetano"/"yet"; that
|
every Yetano application). This is a deliberate default-path and
|
||||||
divergence needs a conscious decision, not a silent behavior change).
|
env-var-shape change (`$YETANO_HOME` no longer exists; see
|
||||||
- Once `yet` migrates, evaluate `yasta`, `yamocir`, `yaiam`, and
|
`YET_DATA_HOME`/`YETANO_DATA_HOME`, `YET_CACHE_HOME`/
|
||||||
`yalsh`-adjacent projects the same way (per the original task
|
`YETANO_CACHE_HOME`, `YET_BIN_HOME`/`YETANO_BIN_HOME` instead) --
|
||||||
description) -- each on its own merits, not as a blanket sweep.
|
existing installations are not migrated (see `yet`'s
|
||||||
|
`docs/install-store-and-profiles.md`).
|
||||||
|
- [x] `yaseva` was built on `core/paths`/`core/config` from the start.
|
||||||
|
- [x] The remaining applications across the `yetano`, `yak`, and
|
||||||
|
`yamase` meta-repos were migrated on 2026-09-22; the record (and the
|
||||||
|
few open follow-ups) is the meta-repo's `TODO-pathchange.md`.
|
||||||
|
|
||||||
|
## Standard commands
|
||||||
|
|
||||||
|
- [x] `manual` (v0.2.0), `completion`, `doctor` (v0.3.0), `secretref`
|
||||||
|
(v0.4.0), `configcmd` and `version` (v0.5.0) -- see
|
||||||
|
docs/program-conventions.md in the meta-repository.
|
||||||
|
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
|
||||||
|
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
||||||
|
- [ ] `core/gui`: the native WebView host from
|
||||||
|
`prototypes/yetano-webview` (yet-gui has a copy in `yet/gui/internal`).
|
||||||
|
|
||||||
## Platform tuning
|
## Platform tuning
|
||||||
|
|
||||||
- FreeBSD's flavor (`freebsd.go`) is a best-effort first pass. Other BSD
|
- [x] macOS Desktop's `RuntimeDir()` now prefers `$TMPDIR` (the
|
||||||
and Unix-family `GOOS` values (`openbsd`, `netbsd`, `dragonfly`,
|
OS-managed, per-user, securely permissioned ephemeral directory every
|
||||||
`solaris`, `illumos`, ...) currently fall back to the Linux flavor
|
macOS process gets -- what `NSTemporaryDirectory()` returns), the real
|
||||||
(`flavor()`'s default case) -- verified to compile and behave
|
native equivalent to XDG_RUNTIME_DIR's role. It falls back to the
|
||||||
sensibly, not verified against each OS's actual convention. Adding a
|
previous `~/Library/Application Support/<App>/Runtime` placeholder only
|
||||||
dedicated flavor table for one of them is a small, additive change
|
when `TMPDIR` is unset in the resolved environment (simulated/test
|
||||||
(a new `<os>.go` file plus one `case` in `flavor()`), never a
|
environments that never set it).
|
||||||
redesign.
|
- [x] `LogAliasDir()` (spec section 39: `~/.local/log/<app>` as a Unix
|
||||||
- macOS Desktop's `RuntimeDir()` (`~/Library/Application
|
convenience symlink target) now has a creation API:
|
||||||
Support/<App>/Runtime`) is a placeholder -- macOS has no strong native
|
`Resolver.EnsureLogAlias()` creates the `LogDir()` symlink if missing,
|
||||||
convention for a GUI app's ephemeral runtime directory the way
|
leaves any pre-existing entry untouched, and is a no-op alias of
|
||||||
XDG_RUNTIME_DIR does on Linux. Revisit if a real Desktop consumer
|
`EnsureLogDir()` on Windows/macOS Desktop (where the two already
|
||||||
needs something more specific (e.g. a `TemporaryItems`-based
|
coincide).
|
||||||
location).
|
- **Low priority, not an MVP blocker:** FreeBSD's flavor (`freebsd.go`)
|
||||||
- `LogAliasDir()` (spec section 39: `~/.local/log/<app>` as a Unix
|
is a best-effort first pass. Other BSD and Unix-family `GOOS` values
|
||||||
convenience symlink target) is resolved but never created -- no
|
(`openbsd`, `netbsd`, `dragonfly`, `solaris`, `illumos`, ...) currently
|
||||||
symlink-creation API exists yet. Decide whether this is worth adding
|
fall back to the Linux flavor (`flavor()`'s default case) -- verified
|
||||||
before any consumer actually wants it.
|
to compile and behave sensibly, not verified against each OS's actual
|
||||||
|
convention. Nobody has asked for one of these yet; adding a dedicated
|
||||||
|
flavor table for one is a small, additive change (a new `<os>.go` file
|
||||||
|
plus one `case` in `flavor()`), never a redesign, and can wait until a
|
||||||
|
real consumer needs it.
|
||||||
|
|
||||||
## Windows
|
## Windows
|
||||||
|
|
||||||
@@ -52,13 +71,71 @@ speculatively.
|
|||||||
launcher, spec section 20) is explicitly out of scope for `core` --
|
launcher, spec section 20) is explicitly out of scope for `core` --
|
||||||
path resolution and package activation stay separate concerns (spec
|
path resolution and package activation stay separate concerns (spec
|
||||||
section 20's own instruction).
|
section 20's own instruction).
|
||||||
- The native `SHGetKnownFolderPath` fallback in
|
- [x] **The native `SHGetKnownFolderPath` fallback has now been run on a
|
||||||
`knownfolders_windows.go` has only been verified to compile
|
real Windows host** (Windows 10, Go 1.25), not just cross-compiled.
|
||||||
(`GOOS=windows go build`/`go vet`), never run on an actual Windows
|
With `APPDATA`/`LOCALAPPDATA`/`PROGRAMDATA` all unset, `ConfigDir()`/
|
||||||
host. It is a secondary fallback below environment variables, so a
|
`DataDir()`/system-scope `ConfigDir()` correctly resolved the real
|
||||||
latent bug there would only matter in the edge case where
|
roaming/local/`ProgramData` known folders via the native API (source
|
||||||
`APPDATA`/`LOCALAPPDATA`/`PROGRAMDATA` are all unset in the process
|
reported as `windows-known-folder`), confirmed via `Explain()` across
|
||||||
environment on real Windows.
|
every category. `go build`/`go test ./...` are clean on real Windows.
|
||||||
|
`go vet ./...` reports exactly one finding there, and it is expected
|
||||||
|
and permanent, not a bug: `knownfolders_windows.go:71` converts a
|
||||||
|
`uintptr` returned via `SHGetKnownFolderPath`'s out-parameter to
|
||||||
|
`unsafe.Pointer` to walk the UTF-16 string it points to -- `go vet`'s
|
||||||
|
`unsafeptr` check can never prove this safe (the pointer is written
|
||||||
|
into memory by the syscall, not derived from a Go pointer in the same
|
||||||
|
expression), for any formulation of this code, without depending on
|
||||||
|
`golang.org/x/sys/windows` (deliberately not done, per this module's
|
||||||
|
minimal-dependency policy -- see the file's own comment). Plain `go
|
||||||
|
vet ./...` on macOS/Linux never sees this file at all (`//go:build
|
||||||
|
windows`); only `GOOS=windows go vet ./...`/vet run on a real Windows
|
||||||
|
host reports it. Verification commands for future reference: `go
|
||||||
|
build ./... && go test ./...` (clean), `go vet ./...` (clean on
|
||||||
|
macOS/Linux; one documented, accepted `unsafeptr` finding on Windows).
|
||||||
|
- [x] **Running on a real Windows host also surfaced and fixed a real,
|
||||||
|
previously-invisible bug**, unrelated to `SHGetKnownFolderPath`: see
|
||||||
|
"WithRoot cross-platform-simulation bug" below.
|
||||||
|
|
||||||
|
## WithRoot cross-platform-simulation bug (found via real-Windows testing)
|
||||||
|
|
||||||
|
`WithRoot` lets tests sandbox real filesystem I/O under a temp directory
|
||||||
|
while `WithPlatform` simulates a *different* platform's path logic (see
|
||||||
|
README's "Testing on any host") -- e.g. `WithPlatform("linux")` with
|
||||||
|
`WithRoot(t.TempDir())` on any host. `root` (typically `t.TempDir()`) is
|
||||||
|
always in the REAL host's native address family, which does not have to
|
||||||
|
match the *simulated* platform's family. `applyRoot` previously assumed
|
||||||
|
they always matched (choosing unix- or windows-style joining purely from
|
||||||
|
`r.platform`), so root's own separators were never normalized: on a real
|
||||||
|
Windows host simulating Linux, `ConfigDir()` etc. produced mixed-
|
||||||
|
separator paths (`C:\...\001/home/test/.config/yet`), and in one case
|
||||||
|
(an override value that itself already embedded `root`) an outright
|
||||||
|
invalid path (a mid-string drive letter). This was invisible on
|
||||||
|
macOS/Linux hosts, where `t.TempDir()` happens to already share the
|
||||||
|
simulated Unix family with whatever was being tested, and was only
|
||||||
|
exposed by actually running this package's own test suite on a real
|
||||||
|
Windows host for the first time (see the `SHGetKnownFolderPath`
|
||||||
|
verification above) -- **this class of bug is exactly why "verified to
|
||||||
|
compile via cross-compilation" is not the same as "verified on the real
|
||||||
|
platform," and is worth remembering before declaring any future
|
||||||
|
Windows/macOS-specific change done from cross-compilation alone.**
|
||||||
|
|
||||||
|
Fixed: `applyRoot` (now `applyRootRebase` in `join.go`) decomposes the
|
||||||
|
resolved path into plain segments and re-joins them onto `root` using
|
||||||
|
root's *own* family, inferred from its content (the same technique
|
||||||
|
`JoinDirFile` already used) -- not `r.platform`'s. Two call sites that
|
||||||
|
joined an already-rooted value with one more suffix (`logDirUnix`,
|
||||||
|
`darwinDesktopStateDir`/`darwinDesktopRuntimeDir`'s fallback) were
|
||||||
|
switched from a hardcoded `unixJoin` to the family-aware `JoinDirFile`
|
||||||
|
for the same reason. `core/config`'s working-directory layer had the
|
||||||
|
identical bug one level up (`JoinFamily` decided family from the
|
||||||
|
simulated platform, not from `r.workdirPath`'s own content when it had
|
||||||
|
one) -- fixed via a new `paths.JoinDirFileFamily`, which behaves like
|
||||||
|
`JoinDirFile` whenever `dir` has a separator of its own, falling back to
|
||||||
|
`JoinFamily`'s platform-driven choice only for an ambiguous bare `dir`
|
||||||
|
like the default `"."`. See `TestApplyRootRebaseMismatchedFamily` and
|
||||||
|
`TestJoinDirFileFamily` for the regression coverage (constructing a
|
||||||
|
mismatched root/platform pair directly, so this no longer depends on
|
||||||
|
which host CI happens to run on).
|
||||||
|
|
||||||
## Portability / distribution model
|
## Portability / distribution model
|
||||||
|
|
||||||
@@ -66,18 +143,15 @@ speculatively.
|
|||||||
and is tested, but there is no ecosystem-wide "portable install"
|
and is tested, but there is no ecosystem-wide "portable install"
|
||||||
concept wired up yet (spec section 41's "optional later:
|
concept wired up yet (spec section 41's "optional later:
|
||||||
`YETANO_HOME` or portable mode").
|
`YETANO_HOME` or portable mode").
|
||||||
- The future `yet` package store model (spec sections 2/37/38: package
|
- The `yet` package store (spec sections 2/37/38) lives in `yet`
|
||||||
store vs. application data vs. config vs. state vs. cache vs. runtime
|
(`internal/store`), built on these primitives; `core/paths` itself
|
||||||
vs. executables, as distinct concepts) is intentionally not
|
stays store-agnostic.
|
||||||
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;
|
- Plugin/extension search paths: no dedicated category exists yet;
|
||||||
`paths.FindFile` is generic enough that a caller can build one today
|
`paths.FindFile` is generic enough that a caller can build one today
|
||||||
(e.g. over `DataSearchDirs()` with a `plugins/` suffix) without
|
(e.g. over `DataSearchDirs()` with a `plugins/` suffix) without
|
||||||
needing a new `PathKind`.
|
needing a new `PathKind`.
|
||||||
- Atomic package activation, versioning/rollback for that future store:
|
- Atomic package activation, versioning/rollback for the store: `yet`'s
|
||||||
out of scope, same as above.
|
business, not core's.
|
||||||
|
|
||||||
## Central Yetano config
|
## Central Yetano config
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Package completion is the shared "<program> completion <shell>" command
|
||||||
|
// of the Yetano program standard (see docs/program-conventions.md in the
|
||||||
|
// yetano meta-repository): it prints a shell completion script for bash,
|
||||||
|
// zsh, fish or PowerShell, generated from a static command tree.
|
||||||
|
//
|
||||||
|
// The scripts are deliberately simple, word-based completion of command
|
||||||
|
// and subcommand names (not flag-aware): they join the words typed so far
|
||||||
|
// into a prefix and look up what may follow it.
|
||||||
|
//
|
||||||
|
// var tree = completion.Tree{
|
||||||
|
// "serve": nil,
|
||||||
|
// "config": completion.Leaf("create", "validate", "path"),
|
||||||
|
// "manual": nil,
|
||||||
|
// "doctor": nil,
|
||||||
|
// "completion": completion.Leaf(completion.Shells...),
|
||||||
|
// "version": nil,
|
||||||
|
// }
|
||||||
|
// case "completion":
|
||||||
|
// err := completion.Run("yasl", tree, args[1:], os.Stdout)
|
||||||
|
package completion
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tree is one level of a program's commands: a name maps to its
|
||||||
|
// subcommands, or to nil for a command without any.
|
||||||
|
type Tree map[string]Tree
|
||||||
|
|
||||||
|
// Leaf is a level of commands that have no subcommands themselves.
|
||||||
|
func Leaf(names ...string) Tree {
|
||||||
|
t := make(Tree, len(names))
|
||||||
|
for _, n := range names {
|
||||||
|
t[n] = nil
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shells are the supported shells, in the order help texts list them.
|
||||||
|
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
||||||
|
|
||||||
|
// ErrUsage is returned by Run for a missing or unknown shell.
|
||||||
|
var ErrUsage = errors.New("usage: completion <bash|zsh|fish|powershell>")
|
||||||
|
|
||||||
|
var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`)
|
||||||
|
|
||||||
|
// entry is a prefix (words typed so far, space-joined) and what may follow.
|
||||||
|
type entry struct {
|
||||||
|
prefix string
|
||||||
|
words []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func flatten(tree Tree) ([]entry, error) {
|
||||||
|
var out []entry
|
||||||
|
var walk func(prefix string, t Tree) error
|
||||||
|
walk = func(prefix string, t Tree) error {
|
||||||
|
names := make([]string, 0, len(t))
|
||||||
|
for n := range t {
|
||||||
|
if !safeWord.MatchString(n) {
|
||||||
|
return fmt.Errorf("completion: command name %q is not a plain word", n)
|
||||||
|
}
|
||||||
|
names = append(names, n)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
out = append(out, entry{prefix, names})
|
||||||
|
for _, n := range names {
|
||||||
|
if sub := t[n]; len(sub) > 0 {
|
||||||
|
p := n
|
||||||
|
if prefix != "" {
|
||||||
|
p = prefix + " " + n
|
||||||
|
}
|
||||||
|
if err := walk(p, sub); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return out, walk("", tree)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Script returns the completion script for shell.
|
||||||
|
func Script(program, shell string, tree Tree) (string, error) {
|
||||||
|
if !safeWord.MatchString(program) {
|
||||||
|
return "", fmt.Errorf("completion: program name %q is not a plain word", program)
|
||||||
|
}
|
||||||
|
entries, err := flatten(tree)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
fn := "_" + strings.NewReplacer("-", "_", ".", "_", ":", "_", "+", "_").Replace(program) + "_complete"
|
||||||
|
var b strings.Builder
|
||||||
|
switch shell {
|
||||||
|
case "bash":
|
||||||
|
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program)
|
||||||
|
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
||||||
|
for _, e := range entries {
|
||||||
|
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
|
||||||
|
case "zsh":
|
||||||
|
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
|
||||||
|
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\"\n local -a completions\n case \"$prefix\" in\n", fn)
|
||||||
|
for _, e := range entries {
|
||||||
|
fmt.Fprintf(&b, " %q) completions=(%s) ;;\n", e.prefix, strings.Join(e.words, " "))
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n")
|
||||||
|
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
|
||||||
|
case "fish":
|
||||||
|
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
|
||||||
|
fmt.Fprintf(&b, "function %s\n set -l tokens (commandline -opc)\n set -l prefix (string join ' ' -- $tokens[2..-1])\n switch \"$prefix\"\n", fn)
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.prefix == "" {
|
||||||
|
b.WriteString(" case ''\n")
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(&b, " case %q\n", e.prefix)
|
||||||
|
}
|
||||||
|
quoted := make([]string, len(e.words))
|
||||||
|
for i, w := range e.words {
|
||||||
|
quoted[i] = fmt.Sprintf("%q", w)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
|
||||||
|
case "powershell":
|
||||||
|
fmt.Fprintf(&b, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", program, program)
|
||||||
|
fmt.Fprintf(&b, "Register-ArgumentCompleter -Native -CommandName '%s', '%s.exe' -ScriptBlock {\n", program, program)
|
||||||
|
b.WriteString(" param($wordToComplete, $commandAst, $cursorPosition)\n")
|
||||||
|
b.WriteString(" $words = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })\n")
|
||||||
|
b.WriteString(" if ($wordToComplete -ne '' -and $words.Count -gt 0) { $words = @($words | Select-Object -First ($words.Count - 1)) }\n")
|
||||||
|
b.WriteString(" $prefix = $words -join ' '\n $candidates = switch ($prefix) {\n")
|
||||||
|
for _, e := range entries {
|
||||||
|
quoted := make([]string, len(e.words))
|
||||||
|
for i, w := range e.words {
|
||||||
|
quoted[i] = "'" + w + "'"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " '%s' { @(%s) }\n", e.prefix, strings.Join(quoted, ", "))
|
||||||
|
}
|
||||||
|
b.WriteString(" default { @() }\n }\n")
|
||||||
|
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
|
||||||
|
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n")
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
|
||||||
|
}
|
||||||
|
return b.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run serves "<program> completion <shell>" -- args are the arguments
|
||||||
|
// after "completion" -- writing the script to w.
|
||||||
|
func Run(program string, tree Tree, args []string, w io.Writer) error {
|
||||||
|
if len(args) != 1 {
|
||||||
|
return ErrUsage
|
||||||
|
}
|
||||||
|
script, err := Script(program, args[0], tree)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = io.WriteString(w, script)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package completion
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var tree = Tree{
|
||||||
|
"serve": nil,
|
||||||
|
"config": Leaf("create", "validate"),
|
||||||
|
"completion": Leaf(Shells...),
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScripts(t *testing.T) {
|
||||||
|
for _, shell := range Shells {
|
||||||
|
s, err := Script("my-tool", shell, tree)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"config", "create", "validate", "powershell"} {
|
||||||
|
if !strings.Contains(s, want) {
|
||||||
|
t.Errorf("%s script lacks %q", shell, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := Script("tool", "tcsh", tree); !errors.Is(err, ErrUsage) {
|
||||||
|
t.Errorf("unknown shell: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := Script("tool", "bash", Tree{"a b": nil}); err == nil {
|
||||||
|
t.Error("a name with a space must be refused")
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
if err := Run("tool", tree, nil, &b); !errors.Is(err, ErrUsage) {
|
||||||
|
t.Errorf("no shell: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBashCompletes runs the generated bash function, when bash is there.
|
||||||
|
func TestBashCompletes(t *testing.T) {
|
||||||
|
if _, err := exec.LookPath("bash"); err != nil {
|
||||||
|
t.Skip("no bash")
|
||||||
|
}
|
||||||
|
s, _ := Script("tool", "bash", tree)
|
||||||
|
out, err := exec.Command("bash", "-c", s+"\nCOMP_WORDS=(tool config v); COMP_CWORD=2; _tool_complete; echo \"${COMPREPLY[@]}\"").CombinedOutput()
|
||||||
|
if err != nil || strings.TrimSpace(string(out)) != "validate" {
|
||||||
|
t.Fatalf("bash completion: %v %q", err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,6 +67,7 @@ type Resolver struct {
|
|||||||
envExpansion bool
|
envExpansion bool
|
||||||
env paths.Environment
|
env paths.Environment
|
||||||
pathsOpts []paths.Option
|
pathsOpts []paths.Option
|
||||||
|
explicitPath string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Option configures a Resolver constructed by New/For.
|
// Option configures a Resolver constructed by New/For.
|
||||||
@@ -161,6 +162,17 @@ func WithPathsOptions(opts ...paths.Option) Option {
|
|||||||
return func(r *Resolver) { r.pathsOpts = append(r.pathsOpts, opts...) }
|
return func(r *Resolver) { r.pathsOpts = append(r.pathsOpts, opts...) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithExplicitPath adds path as the highest-priority layer -- above the
|
||||||
|
// working directory -- for a CLI's own explicit "--config <path>"-style
|
||||||
|
// flag. Unlike every other (optional) layer, an explicit path that does
|
||||||
|
// not exist is an error from Resolve/ResolveAll/LoadMerged/Explain,
|
||||||
|
// rather than being silently skipped: a typo'd --config flag should
|
||||||
|
// fail loudly, not fall through to a different layer. Passing "" (the
|
||||||
|
// default) disables this layer entirely.
|
||||||
|
func WithExplicitPath(path string) Option {
|
||||||
|
return func(r *Resolver) { r.explicitPath = path }
|
||||||
|
}
|
||||||
|
|
||||||
// Application returns the Application this Resolver was built for.
|
// Application returns the Application this Resolver was built for.
|
||||||
func (r *Resolver) Application() core.Application { return r.app }
|
func (r *Resolver) Application() core.Application { return r.app }
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWithExplicitPathWinsOverEverything(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "layer: system\n")
|
||||||
|
writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "layer: user\n")
|
||||||
|
explicit := filepath.Join(root, "explicit.yaml")
|
||||||
|
writeFile(t, explicit, "layer: explicit\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")),
|
||||||
|
WithExplicitPath(explicit),
|
||||||
|
)
|
||||||
|
|
||||||
|
layer, found, err := r.Resolve()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Resolve: %v", err)
|
||||||
|
}
|
||||||
|
if !found || layer.Path != explicit {
|
||||||
|
t.Fatalf("Resolve() = %+v, found=%v, want the explicit path to win", layer, found)
|
||||||
|
}
|
||||||
|
if layer.Priority != PriorityExplicit {
|
||||||
|
t.Errorf("layer.Priority = %d, want %d", layer.Priority, PriorityExplicit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithExplicitPathMissingIsAnError(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)),
|
||||||
|
WithExplicitPath(filepath.Join(root, "does-not-exist.yaml")),
|
||||||
|
)
|
||||||
|
if _, _, err := r.Resolve(); err == nil {
|
||||||
|
t.Fatal("Resolve() error = nil, want an error for a missing explicit path")
|
||||||
|
}
|
||||||
|
if _, err := r.ResolveAll(); err == nil {
|
||||||
|
t.Fatal("ResolveAll() error = nil, want an error for a missing explicit path")
|
||||||
|
}
|
||||||
|
var target struct{}
|
||||||
|
if err := r.LoadMerged(&target); err == nil {
|
||||||
|
t.Fatal("LoadMerged() error = nil, want an error for a missing explicit path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithExplicitPathEmptyDisablesLayer(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")),
|
||||||
|
WithExplicitPath(""),
|
||||||
|
)
|
||||||
|
layers, err := r.ResolveAll()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ResolveAll: %v", err)
|
||||||
|
}
|
||||||
|
for _, l := range layers {
|
||||||
|
if l.Priority == PriorityExplicit {
|
||||||
|
t.Fatalf("ResolveAll() included an explicit layer despite WithExplicitPath(\"\"): %v", layers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
-5
@@ -1,6 +1,7 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"yetano.dev/yetano/core"
|
"yetano.dev/yetano/core"
|
||||||
@@ -25,21 +26,44 @@ type Layer struct {
|
|||||||
// the last fallback.
|
// the last fallback.
|
||||||
const PriorityYetanoDefaults = 0
|
const PriorityYetanoDefaults = 0
|
||||||
|
|
||||||
|
// PriorityExplicit is higher than every other layer (including the
|
||||||
|
// working directory), for WithExplicitPath's "--config <path>" use
|
||||||
|
// case: an explicit override always wins, no exceptions.
|
||||||
|
const PriorityExplicit = 1000
|
||||||
|
|
||||||
func statExists(path string) bool {
|
func statExists(path string) bool {
|
||||||
_, err := os.Stat(path)
|
_, err := os.Stat(path)
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// layers builds the full, ordered layer list (spec sections 21/22): the
|
// layers builds the full, ordered layer list (spec sections 21/22): an
|
||||||
// working directory (if enabled), then core/paths's own ConfigSearchDirs
|
// explicit override path (if set; see WithExplicitPath), then the
|
||||||
// for this application (optionally dropping the system-tier layer), then
|
// working directory (if enabled), then core/paths's own
|
||||||
// -- opt-in only -- the shared Yetano defaults directory.
|
// 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) {
|
func (r *Resolver) layers() ([]Layer, error) {
|
||||||
var out []Layer
|
var out []Layer
|
||||||
|
|
||||||
|
if r.explicitPath != "" {
|
||||||
|
if !statExists(r.explicitPath) {
|
||||||
|
return nil, fmt.Errorf("config: explicit path %s does not exist", r.explicitPath)
|
||||||
|
}
|
||||||
|
out = append(out, Layer{
|
||||||
|
Path: r.explicitPath,
|
||||||
|
Source: paths.APIOverride,
|
||||||
|
Priority: PriorityExplicit,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
if r.workdir {
|
if r.workdir {
|
||||||
out = append(out, Layer{
|
out = append(out, Layer{
|
||||||
Path: paths.JoinFamily(r.paths.Platform(), r.workdirPath, r.filename),
|
// JoinDirFileFamily (not JoinFamily): r.workdirPath may be a
|
||||||
|
// real filesystem path from a caller/test (e.g. under
|
||||||
|
// WithRoot's root), whose own family can differ from
|
||||||
|
// r.paths.Platform()'s simulated one -- see core/paths'
|
||||||
|
// applyRootRebase for why that combination is legitimate.
|
||||||
|
Path: paths.JoinDirFileFamily(r.paths.Platform(), r.workdirPath, r.filename),
|
||||||
Source: paths.WorkingDirectory,
|
Source: paths.WorkingDirectory,
|
||||||
Priority: paths.PriorityWorkingDirectory,
|
Priority: paths.PriorityWorkingDirectory,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A process without HOME (e.g. a system service) still finds its
|
||||||
|
// working-directory and system config; only the user tier is skipped.
|
||||||
|
func TestResolveWithoutHome(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
workdir := filepath.Join(root, "work")
|
||||||
|
newResolver := func() *Resolver {
|
||||||
|
return mustResolver(t, yetApp(),
|
||||||
|
WithEnvironment(map[string]string{}),
|
||||||
|
WithWorkdirPath(workdir),
|
||||||
|
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, found, err := newResolver().Resolve(); err != nil || found {
|
||||||
|
t.Fatalf("Resolve() on empty tree = found=%v err=%v, want found=false err=nil", found, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
system := filepath.Join(root, "etc", "yet", "yet.yaml")
|
||||||
|
writeFile(t, system, "system: true\n")
|
||||||
|
layer, found, err := newResolver().Resolve()
|
||||||
|
if err != nil || !found {
|
||||||
|
t.Fatalf("Resolve() = found=%v err=%v, want the system file", found, err)
|
||||||
|
}
|
||||||
|
if layer.Path != system {
|
||||||
|
t.Errorf("Resolve() path = %q, want %q", layer.Path, system)
|
||||||
|
}
|
||||||
|
|
||||||
|
cwd := filepath.Join(workdir, "yet.yaml")
|
||||||
|
writeFile(t, cwd, "cwd: true\n")
|
||||||
|
layer, found, err = newResolver().Resolve()
|
||||||
|
if err != nil || !found || layer.Path != cwd {
|
||||||
|
t.Fatalf("Resolve() = %q found=%v err=%v, want %q", layer.Path, found, err, cwd)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,466 @@
|
|||||||
|
// Package configcmd is the shared "<program> config" command of the
|
||||||
|
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
|
||||||
|
// the yetano meta-repository):
|
||||||
|
//
|
||||||
|
// <program> config create [--minimal|--full] [--force] [--output <file>]
|
||||||
|
// <program> config validate
|
||||||
|
// <program> config upgrade [--write]
|
||||||
|
// <program> config path
|
||||||
|
//
|
||||||
|
// The command behaves the same in every program; what differs is only
|
||||||
|
// the program's own part, passed in as a Spec: its name and
|
||||||
|
// core.Application (which determine the file name and the directories
|
||||||
|
// searched), its two templates (a minimal one that is just enough to be
|
||||||
|
// valid, and a full one documenting every option), and the function
|
||||||
|
// that loads and validates a file. The schema itself stays in each
|
||||||
|
// program's own config package.
|
||||||
|
//
|
||||||
|
// var configSpec = configcmd.Spec{
|
||||||
|
// Name: "yasl", App: app,
|
||||||
|
// Minimal: config.MinimalTemplate, Full: config.FullTemplate,
|
||||||
|
// Validate: func(path string) error { _, err := config.Load(path); return err },
|
||||||
|
// Schema: config.Config{},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// case "config":
|
||||||
|
// os.Exit(configcmd.Run(configSpec, configFlag, args[1:], os.Stdout, os.Stderr))
|
||||||
|
//
|
||||||
|
// A program's tests call UndocumentedKeys with its full template so a
|
||||||
|
// new option cannot be added without documenting it -- that is what
|
||||||
|
// keeps "config upgrade" useful. create/upgrade/unknown-key detection
|
||||||
|
// work on YAML files.
|
||||||
|
//
|
||||||
|
// Exit codes: 0 success, 1 the command ran and found a problem (invalid
|
||||||
|
// configuration, no file found, refusing to overwrite), 2 usage error.
|
||||||
|
//
|
||||||
|
// The package does not depend on cobra: a cobra program wires Run into
|
||||||
|
// a command with flag parsing disabled, taking --config out of the
|
||||||
|
// arguments itself, the same way it wires core/doctor.
|
||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
coreconfig "yetano.dev/yetano/core/config"
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes, matching core/doctor's.
|
||||||
|
const (
|
||||||
|
ExitOK = 0
|
||||||
|
ExitProblem = 1
|
||||||
|
ExitUsage = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNotFound is returned (wrapped, with the list of searched
|
||||||
|
// locations) by Find when no explicit path was given and no location
|
||||||
|
// has the file.
|
||||||
|
var ErrNotFound = errors.New("no configuration file found")
|
||||||
|
|
||||||
|
// Spec is one program's part of the config command.
|
||||||
|
type Spec struct {
|
||||||
|
// Name is the program's own name, used in messages ("yasl",
|
||||||
|
// "yamase-smtpd").
|
||||||
|
Name string
|
||||||
|
|
||||||
|
// App determines the directories searched (core/config). Programs
|
||||||
|
// of one family may share an App and differ only in Filename.
|
||||||
|
App core.Application
|
||||||
|
|
||||||
|
// Filename is the file searched for in every location; default
|
||||||
|
// "<Name>.yaml".
|
||||||
|
Filename string
|
||||||
|
|
||||||
|
// Optional says the program also runs without a configuration file
|
||||||
|
// (on built-in defaults): "validate" and "upgrade" then report that
|
||||||
|
// no file exists instead of failing.
|
||||||
|
Optional bool
|
||||||
|
|
||||||
|
// None says the program has no configuration at all; every
|
||||||
|
// subcommand says so (the standard still requires the command).
|
||||||
|
None bool
|
||||||
|
|
||||||
|
// Minimal is the template "config create" writes by default: just
|
||||||
|
// enough to be valid, with placeholder values an operator adjusts.
|
||||||
|
Minimal string
|
||||||
|
|
||||||
|
// Full is the template "config create --full" writes, documenting
|
||||||
|
// every option. "config upgrade" offers the options of Full a file
|
||||||
|
// does not mention yet, so every key the program reads should be in
|
||||||
|
// it (see UndocumentedKeys).
|
||||||
|
Full string
|
||||||
|
|
||||||
|
// Validate loads and validates the configuration the same way the
|
||||||
|
// program does at startup, including files it names (TLS key pairs,
|
||||||
|
// ...). path is the file Find selected; "" for an Optional program
|
||||||
|
// without a file (validate the built-in defaults). A program that
|
||||||
|
// merges several layers may ignore path and load its own way.
|
||||||
|
Validate func(path string) error
|
||||||
|
|
||||||
|
// Schema is the program's configuration struct (e.g. config.Config{}).
|
||||||
|
// It enables unknown-option detection in "validate" and tells
|
||||||
|
// "upgrade" which mappings hold operator-named entries rather than
|
||||||
|
// options (see Missing). Optional.
|
||||||
|
Schema any
|
||||||
|
|
||||||
|
// Options are passed through to core/config; tests use them to
|
||||||
|
// inject a platform, environment, root and working directory.
|
||||||
|
Options []coreconfig.Option
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) filename() string {
|
||||||
|
if s.Filename != "" {
|
||||||
|
return s.Filename
|
||||||
|
}
|
||||||
|
return s.Name + ".yaml"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run serves "<program> config <args...>" and returns the exit code.
|
||||||
|
// explicit is the program's --config value ("" if not given).
|
||||||
|
func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
if len(args) == 0 {
|
||||||
|
usage(s, stderr)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
sub, rest := args[0], args[1:]
|
||||||
|
switch sub {
|
||||||
|
case "create", "validate", "upgrade", "path":
|
||||||
|
if s.None {
|
||||||
|
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch sub {
|
||||||
|
case "create":
|
||||||
|
return s.create(explicit, rest, stdout, stderr)
|
||||||
|
case "validate":
|
||||||
|
return s.validate(explicit, rest, stdout, stderr)
|
||||||
|
case "upgrade":
|
||||||
|
return s.upgrade(explicit, rest, stdout, stderr)
|
||||||
|
case "path":
|
||||||
|
return s.path(explicit, rest, stdout, stderr)
|
||||||
|
case "help", "-h", "-help", "--help":
|
||||||
|
usage(s, stdout)
|
||||||
|
return ExitOK
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "%s config: unknown subcommand %q\n", s.Name, sub)
|
||||||
|
usage(s, stderr)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subcommands are the config subcommands, for a program's completion
|
||||||
|
// tree and help text.
|
||||||
|
var Subcommands = []string{"create", "validate", "upgrade", "path"}
|
||||||
|
|
||||||
|
func usage(s Spec, w io.Writer) {
|
||||||
|
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
||||||
|
|
||||||
|
create [--minimal|--full] [--force] [--output <file>]
|
||||||
|
write a commented starter configuration (minimal by default)
|
||||||
|
validate check the configuration file the program would use
|
||||||
|
upgrade [--write]
|
||||||
|
show the options of "create --full" the file does not mention
|
||||||
|
yet, as commented blocks; --write adds them to the file
|
||||||
|
path list the locations searched for %[2]s, highest priority first
|
||||||
|
`, s.Name, s.filename())
|
||||||
|
}
|
||||||
|
|
||||||
|
// newFlagSet returns a flag set for one subcommand whose usage errors go
|
||||||
|
// to stderr.
|
||||||
|
func (s Spec) newFlagSet(sub string, stderr io.Writer) *flag.FlagSet {
|
||||||
|
fs := flag.NewFlagSet(s.Name+" config "+sub, flag.ContinueOnError)
|
||||||
|
fs.SetOutput(stderr)
|
||||||
|
return fs
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse parses args into fs and maps the outcome to an exit code: -1 to
|
||||||
|
// go on, ExitOK for --help, ExitUsage for anything else that is wrong,
|
||||||
|
// including positional arguments (no subcommand takes any).
|
||||||
|
func parse(fs *flag.FlagSet, args []string) int {
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
|
if errors.Is(err, flag.ErrHelp) {
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
fmt.Fprintf(fs.Output(), "%s: unexpected argument %q\n", fs.Name(), fs.Arg(0))
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Layers returns every location searched, highest priority first, the
|
||||||
|
// one in use marked Selected. explicit is the --config value.
|
||||||
|
func (s Spec) Layers(explicit string) ([]coreconfig.Layer, error) {
|
||||||
|
opts := append([]coreconfig.Option{
|
||||||
|
coreconfig.WithExplicitPath(explicit),
|
||||||
|
coreconfig.WithFilename(s.filename()),
|
||||||
|
coreconfig.WithEnvExpansion(false),
|
||||||
|
}, s.Options...)
|
||||||
|
r, err := coreconfig.New(s.App, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("config: %w", err)
|
||||||
|
}
|
||||||
|
return r.ResolveAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find returns the configuration file the program uses: the explicit
|
||||||
|
// --config path (which must exist), else the highest-priority existing
|
||||||
|
// file. Without one it returns an error wrapping ErrNotFound that lists
|
||||||
|
// the locations searched -- a program that needs a file can print it
|
||||||
|
// as is. Programs use it at startup so "config path" and the program
|
||||||
|
// always agree.
|
||||||
|
func (s Spec) Find(explicit string) (coreconfig.Layer, error) {
|
||||||
|
layers, err := s.Layers(explicit)
|
||||||
|
if err != nil {
|
||||||
|
return coreconfig.Layer{}, err
|
||||||
|
}
|
||||||
|
for _, l := range layers {
|
||||||
|
if l.Selected {
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
searched := make([]string, len(layers))
|
||||||
|
for i, l := range layers {
|
||||||
|
searched[i] = " " + l.Path
|
||||||
|
}
|
||||||
|
return coreconfig.Layer{}, fmt.Errorf("%w for %s: pass --config <file>, or create one (\"%s config create\" writes a starter file) of (highest priority first):\n%s",
|
||||||
|
ErrNotFound, s.Name, s.Name, strings.Join(searched, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// find returns the configuration file the program would use. ok is
|
||||||
|
// false after a failure was reported on stderr; path is "" (and ok
|
||||||
|
// true) for an Optional program without a file.
|
||||||
|
func (s Spec) find(explicit, sub string, stderr io.Writer) (path string, ok bool) {
|
||||||
|
file, err := s.Find(explicit)
|
||||||
|
if err != nil {
|
||||||
|
if s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stderr, "%s config %s: %v\n", s.Name, sub, err)
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return file.Path, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) validate(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
if code := parse(s.newFlagSet("validate", stderr), args); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
path, ok := s.find(explicit, "validate", stderr)
|
||||||
|
if !ok {
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
if path == "" {
|
||||||
|
if s.Validate != nil {
|
||||||
|
if err := s.Validate(""); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s: no configuration file, and the built-in defaults are invalid: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults (\"%s config path\" lists the locations)\n", s.Name, s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
code := ExitOK
|
||||||
|
// Unknown keys first: a typo there is often why a value is "wrong".
|
||||||
|
// The program ignores them (it starts and warns), validate fails.
|
||||||
|
if s.Schema != nil {
|
||||||
|
unknown, err := UnknownKeysFile(path, s.Schema)
|
||||||
|
if err == nil && len(unknown) > 0 {
|
||||||
|
for _, k := range unknown {
|
||||||
|
fmt.Fprintf(stderr, "%s: %s: unknown option %s -- ignored, the default applies (a typo? see \"%s config create --full\")\n", s.Name, path, k, s.Name)
|
||||||
|
}
|
||||||
|
code = ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.Validate != nil {
|
||||||
|
if err := s.Validate(path); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s: configuration %s is invalid: %v\n", s.Name, path, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code != ExitOK {
|
||||||
|
fmt.Fprintf(stderr, "%s: configuration %s is otherwise valid, but has unknown options\n", s.Name, path)
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "configuration %s is valid\n", path)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
fs := s.newFlagSet("create", stderr)
|
||||||
|
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
|
||||||
|
full := fs.Bool("full", false, "write the fully commented reference configuration")
|
||||||
|
force := fs.Bool("force", false, "overwrite the file if it already exists")
|
||||||
|
output := fs.String("output", "", "file to write (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
|
||||||
|
if code := parse(fs, args); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
if *minimal && *full {
|
||||||
|
fmt.Fprintf(stderr, "%s config create: --minimal and --full are mutually exclusive\n", s.Name)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
content, kind := s.Minimal, "minimal"
|
||||||
|
if *full || content == "" {
|
||||||
|
content, kind = s.Full, "full"
|
||||||
|
}
|
||||||
|
|
||||||
|
path := *output
|
||||||
|
if path == "" {
|
||||||
|
var err error
|
||||||
|
if path, err = s.defaultCreatePath(explicit); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(path); err == nil {
|
||||||
|
if !*force {
|
||||||
|
fmt.Fprintf(stderr, "%s config create: %s already exists -- use --force to overwrite it, --output to write somewhere else, or \"%s config upgrade\" to add new options to it\n", s.Name, path, s.Name)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
// 0640: a configuration may name credentials files and should not
|
||||||
|
// be world-readable by default.
|
||||||
|
if err := os.WriteFile(path, []byte(content), 0o640); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s: wrote %s configuration -- review it, then run \"%s config validate\"\n", path, kind, s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultCreatePath is the explicit --config path, else the file the
|
||||||
|
// program would currently use, else the program's file in the user
|
||||||
|
// config directory -- the system one when running as root, since a
|
||||||
|
// daemon started by root does not look in root's home first by intent.
|
||||||
|
func (s Spec) defaultCreatePath(explicit string) (string, error) {
|
||||||
|
if explicit != "" {
|
||||||
|
return explicit, nil
|
||||||
|
}
|
||||||
|
layers, err := s.Layers("")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var user, system string
|
||||||
|
for _, l := range layers {
|
||||||
|
if l.Selected {
|
||||||
|
return l.Path, nil
|
||||||
|
}
|
||||||
|
switch l.Source {
|
||||||
|
case paths.WorkingDirectory, paths.APIOverride:
|
||||||
|
case paths.SystemDirectory:
|
||||||
|
system = l.Path
|
||||||
|
default:
|
||||||
|
if user == "" {
|
||||||
|
user = l.Path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (os.Geteuid() == 0 || user == "") && system != "" {
|
||||||
|
return system, nil
|
||||||
|
}
|
||||||
|
if user == "" {
|
||||||
|
return "", errors.New("no configuration directory known; pass --output <file>")
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) upgrade(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
fs := s.newFlagSet("upgrade", stderr)
|
||||||
|
write := fs.Bool("write", false, "add the missing options to the file (default: only show them)")
|
||||||
|
if code := parse(fs, args); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
path, ok := s.find(explicit, "upgrade", stderr)
|
||||||
|
if !ok {
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
if path == "" {
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- nothing to upgrade (\"%s config create\" writes one)\n", s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config upgrade: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
adds, err := Missing(raw, []byte(s.Full), s.Schema)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config upgrade: %s: %v\n", s.Name, path, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
if len(adds) == 0 {
|
||||||
|
fmt.Fprintf(stdout, "%s: already mentions every option this %s version knows about\n", path, s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
keys := make([]string, len(adds))
|
||||||
|
for i, a := range adds {
|
||||||
|
keys[i] = a.Key
|
||||||
|
}
|
||||||
|
if !*write {
|
||||||
|
fmt.Fprintf(stdout, "%s does not mention %d option(s): %s\n", path, len(adds), strings.Join(keys, ", "))
|
||||||
|
fmt.Fprintln(stdout, "These commented blocks would be added (nothing changes until the \"#\" is removed):")
|
||||||
|
for _, a := range adds {
|
||||||
|
where := "at the end of the file"
|
||||||
|
if a.AfterLine > 0 {
|
||||||
|
where = fmt.Sprintf("after line %d", a.AfterLine)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "\n# --- %s, %s:\n%s", a.Key, where, a.Text)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, "\nRun again with --write to apply.")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, Apply(raw, adds), 0o640); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config upgrade: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s: added %d commented option(s): %s\n", path, len(adds), strings.Join(keys, ", "))
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) path(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
if code := parse(s.newFlagSet("path", stderr), args); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
layers, err := s.Layers(explicit)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config path: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, l := range layers {
|
||||||
|
mark, state := " ", "missing"
|
||||||
|
switch {
|
||||||
|
case l.Selected:
|
||||||
|
mark, state, found = "*", "used", true
|
||||||
|
case l.Exists:
|
||||||
|
state = "exists, shadowed"
|
||||||
|
}
|
||||||
|
src := l.Source.String()
|
||||||
|
if l.Source == paths.APIOverride {
|
||||||
|
src = "--config"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s %s (%s, %s)\n", mark, l.Path, src, state)
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- \"%s config create\" writes one\n", s.Name)
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
@@ -0,0 +1,429 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
coreconfig "yetano.dev/yetano/core/config"
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
const fullTemplate = `# yamase-test full configuration.
|
||||||
|
|
||||||
|
# Minimum log level: debug, info, warn, error.
|
||||||
|
log-level: info
|
||||||
|
|
||||||
|
listen:
|
||||||
|
- address: "0.0.0.0:25"
|
||||||
|
tls: false
|
||||||
|
|
||||||
|
limits:
|
||||||
|
# Largest message accepted, in bytes.
|
||||||
|
max-message-size-bytes: 52428800
|
||||||
|
# Not yet enforced.
|
||||||
|
connection-rate-per-source: 20
|
||||||
|
|
||||||
|
storage:
|
||||||
|
queue:
|
||||||
|
# Only "filesystem" is implemented.
|
||||||
|
driver: filesystem
|
||||||
|
root: /var/lib/yamase/queue
|
||||||
|
|
||||||
|
tls:
|
||||||
|
cert-file: /etc/yamase/tls/test.crt
|
||||||
|
key-file: /etc/yamase/tls/test.key
|
||||||
|
`
|
||||||
|
|
||||||
|
const minimalTemplate = `listen:
|
||||||
|
- address: "0.0.0.0:25"
|
||||||
|
storage:
|
||||||
|
queue:
|
||||||
|
driver: filesystem
|
||||||
|
root: /var/lib/yamase/queue
|
||||||
|
`
|
||||||
|
|
||||||
|
type schema struct {
|
||||||
|
LogLevel string `yaml:"log-level"`
|
||||||
|
Listen []struct {
|
||||||
|
Address string `yaml:"address"`
|
||||||
|
TLS string `yaml:"tls"`
|
||||||
|
} `yaml:"listen"`
|
||||||
|
Limits struct {
|
||||||
|
MaxMessageSizeBytes int64 `yaml:"max-message-size-bytes"`
|
||||||
|
ConnectionRate int `yaml:"connection-rate-per-source"`
|
||||||
|
} `yaml:"limits"`
|
||||||
|
Storage struct {
|
||||||
|
Queue struct {
|
||||||
|
Driver string `yaml:"driver"`
|
||||||
|
Root string `yaml:"root"`
|
||||||
|
} `yaml:"queue"`
|
||||||
|
} `yaml:"storage"`
|
||||||
|
TLS *struct {
|
||||||
|
CertFile string `yaml:"cert-file"`
|
||||||
|
KeyFile string `yaml:"key-file"`
|
||||||
|
} `yaml:"tls"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func validate(path string) error {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var s schema
|
||||||
|
if err := yaml.Unmarshal(data, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(s.Listen) == 0 {
|
||||||
|
return errors.New("listen: at least one listener is required")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// testSpec returns a Spec for a simulated Linux host rooted at root,
|
||||||
|
// with the working directory at root/work.
|
||||||
|
func testSpec(root string) Spec {
|
||||||
|
return Spec{
|
||||||
|
Name: "yamase-test",
|
||||||
|
App: core.Application{Name: "yamase", Kind: core.Service},
|
||||||
|
Minimal: minimalTemplate,
|
||||||
|
Full: fullTemplate,
|
||||||
|
Validate: validate,
|
||||||
|
Schema: schema{},
|
||||||
|
Options: []coreconfig.Option{
|
||||||
|
coreconfig.WithEnvironment(map[string]string{"HOME": "/home/test"}),
|
||||||
|
coreconfig.WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
|
||||||
|
coreconfig.WithWorkdirPath(filepath.Join(root, "work")),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(t *testing.T, s Spec, explicit string, args ...string) (int, string, string) {
|
||||||
|
t.Helper()
|
||||||
|
var out, errOut bytes.Buffer
|
||||||
|
code := Run(s, explicit, args, &out, &errOut)
|
||||||
|
return code, out.String(), errOut.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
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 TestUsage(t *testing.T) {
|
||||||
|
s := testSpec(t.TempDir())
|
||||||
|
if code, _, _ := run(t, s, ""); code != ExitUsage {
|
||||||
|
t.Errorf("no subcommand: exit %d, want %d", code, ExitUsage)
|
||||||
|
}
|
||||||
|
if code, _, _ := run(t, s, "", "frobnicate"); code != ExitUsage {
|
||||||
|
t.Errorf("unknown subcommand: exit %d, want %d", code, ExitUsage)
|
||||||
|
}
|
||||||
|
if code, _, _ := run(t, s, "", "validate", "extra"); code != ExitUsage {
|
||||||
|
t.Errorf("positional argument: exit %d, want %d", code, ExitUsage)
|
||||||
|
}
|
||||||
|
if code, _, _ := run(t, s, "", "create", "--minimal", "--full"); code != ExitUsage {
|
||||||
|
t.Errorf("--minimal --full: exit %d, want %d", code, ExitUsage)
|
||||||
|
}
|
||||||
|
if code, out, _ := run(t, s, "", "help"); code != ExitOK || !strings.Contains(out, "upgrade") {
|
||||||
|
t.Errorf("help: exit %d, output %q", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateDefaultsToUserConfigDir(t *testing.T) {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("as root, create defaults to the system config dir")
|
||||||
|
}
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
code, _, errOut := run(t, s, "", "create")
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("create: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
want := filepath.Join(root, "home", "test", ".config", "yamase", "yamase-test.yaml")
|
||||||
|
got, err := os.ReadFile(want)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create did not write %s: %v", want, err)
|
||||||
|
}
|
||||||
|
if string(got) != minimalTemplate {
|
||||||
|
t.Errorf("create wrote %q, want the minimal template", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The file now exists: a second create refuses, --force overwrites.
|
||||||
|
if code, _, _ := run(t, s, "", "create", "--full"); code != ExitProblem {
|
||||||
|
t.Errorf("create over an existing file: exit %d, want %d", code, ExitProblem)
|
||||||
|
}
|
||||||
|
if code, _, errOut := run(t, s, "", "create", "--full", "--force"); code != ExitOK {
|
||||||
|
t.Fatalf("create --force: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
if got, _ := os.ReadFile(want); string(got) != fullTemplate {
|
||||||
|
t.Errorf("create --full --force did not write the full template")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateExplicitAndOutput(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
explicit := filepath.Join(root, "x", "explicit.yaml")
|
||||||
|
if code, _, errOut := run(t, s, explicit, "create"); code != ExitOK {
|
||||||
|
t.Fatalf("create --config: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(explicit); err != nil {
|
||||||
|
t.Errorf("create --config did not write %s: %v", explicit, err)
|
||||||
|
}
|
||||||
|
output := filepath.Join(root, "out.yaml")
|
||||||
|
if code, _, errOut := run(t, s, explicit, "create", "--output", output, "--full"); code != ExitOK {
|
||||||
|
t.Fatalf("create --output: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
if got, _ := os.ReadFile(output); string(got) != fullTemplate {
|
||||||
|
t.Errorf("create --output --full did not write the full template to --output")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidate(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "no configuration file found") {
|
||||||
|
t.Errorf("validate without a file: exit %d, stderr %q", code, errOut)
|
||||||
|
}
|
||||||
|
file := filepath.Join(root, "work", "yamase-test.yaml")
|
||||||
|
writeFile(t, file, "log-level: info\n")
|
||||||
|
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "listen") {
|
||||||
|
t.Errorf("validate invalid file: exit %d, stderr %q", code, errOut)
|
||||||
|
}
|
||||||
|
writeFile(t, file, minimalTemplate)
|
||||||
|
if code, out, errOut := run(t, s, "", "validate"); code != ExitOK || !strings.Contains(out, file) {
|
||||||
|
t.Errorf("validate valid file: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
// An unknown option fails validate, with its path and line, though
|
||||||
|
// the program itself would start (it ignores the key).
|
||||||
|
writeFile(t, file, minimalTemplate+"log-levle: debug\n")
|
||||||
|
if code, out, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "unknown option log-levle (line") || strings.Contains(out, "is valid") {
|
||||||
|
t.Errorf("validate with an unknown option: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPathNeverCreates(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
code, out, _ := run(t, s, "", "path")
|
||||||
|
if code != ExitOK || !strings.Contains(out, "no configuration file found") {
|
||||||
|
t.Errorf("path: exit %d, output %q", code, out)
|
||||||
|
}
|
||||||
|
for _, f := range []string{"work/yamase-test.yaml", "etc/yamase/yamase-test.yaml"} {
|
||||||
|
if !strings.Contains(out, filepath.Join(root, f)) {
|
||||||
|
t.Errorf("path output does not list %s:\n%s", f, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries, _ := os.ReadDir(root)
|
||||||
|
if len(entries) != 0 {
|
||||||
|
t.Errorf("path created %d entries under the root", len(entries))
|
||||||
|
}
|
||||||
|
|
||||||
|
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate)
|
||||||
|
if _, out, _ := run(t, s, "", "path"); !strings.Contains(out, "* "+filepath.Join(root, "etc", "yamase", "yamase-test.yaml")) {
|
||||||
|
t.Errorf("path does not mark the used file:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpgradePreviewWriteIdempotent(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
file := filepath.Join(root, "work", "yamase-test.yaml")
|
||||||
|
original := minimalTemplate + "limits:\n max-message-size-bytes: 1000\n"
|
||||||
|
writeFile(t, file, original)
|
||||||
|
|
||||||
|
code, out, errOut := run(t, s, "", "upgrade")
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("upgrade: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
for _, k := range []string{"log-level", "limits.connection-rate-per-source", "tls"} {
|
||||||
|
if !strings.Contains(out, k) {
|
||||||
|
t.Errorf("upgrade preview does not mention %s:\n%s", k, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, k := range []string{"storage.queue", "listen[]", "limits.max-message-size-bytes"} {
|
||||||
|
if strings.Contains(out, "# --- "+k) {
|
||||||
|
t.Errorf("upgrade preview offers %s, which the file already has:\n%s", k, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, _ := os.ReadFile(file); string(got) != original {
|
||||||
|
t.Fatal("upgrade without --write changed the file")
|
||||||
|
}
|
||||||
|
|
||||||
|
if code, _, errOut := run(t, s, "", "upgrade", "--write"); code != ExitOK {
|
||||||
|
t.Fatalf("upgrade --write: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
upgraded, _ := os.ReadFile(file)
|
||||||
|
|
||||||
|
// The result still loads, with the same effective values: the
|
||||||
|
// additions are comments only.
|
||||||
|
var before, after schema
|
||||||
|
if err := yaml.Unmarshal([]byte(original), &before); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := yaml.Unmarshal(upgraded, &after); err != nil {
|
||||||
|
t.Fatalf("upgraded file does not parse: %v\n%s", err, upgraded)
|
||||||
|
}
|
||||||
|
if !equalYAML(t, before, after) {
|
||||||
|
t.Errorf("upgrade changed the effective configuration:\n%s", upgraded)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(upgraded), " # Not yet enforced.\n # connection-rate-per-source: 20\n") {
|
||||||
|
t.Errorf("connection-rate-per-source not added into limits: with its comment:\n%s", upgraded)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Running again finds nothing and changes nothing.
|
||||||
|
code, out, _ = run(t, s, "", "upgrade", "--write")
|
||||||
|
if code != ExitOK || !strings.Contains(out, "already mentions every option") {
|
||||||
|
t.Errorf("second upgrade: exit %d, output %q", code, out)
|
||||||
|
}
|
||||||
|
if again, _ := os.ReadFile(file); !bytes.Equal(again, upgraded) {
|
||||||
|
t.Errorf("second upgrade changed the file:\n%s", again)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func equalYAML(t *testing.T, a, b any) bool {
|
||||||
|
t.Helper()
|
||||||
|
ya, _ := yaml.Marshal(a)
|
||||||
|
yb, _ := yaml.Marshal(b)
|
||||||
|
return bytes.Equal(ya, yb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingRespectsCommentsAndNonMappings(t *testing.T) {
|
||||||
|
file := `listen:
|
||||||
|
- address: ":25"
|
||||||
|
# log-level: debug
|
||||||
|
tls:
|
||||||
|
storage:
|
||||||
|
queue: {driver: filesystem}
|
||||||
|
limits:
|
||||||
|
max-message-size-bytes: 1
|
||||||
|
# connection-rate-per-source: 5
|
||||||
|
`
|
||||||
|
adds, err := Missing([]byte(file), []byte(fullTemplate), schema{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(adds) != 0 {
|
||||||
|
t.Errorf("Missing() = %+v, want nothing (commented, empty and flow values count as present)", adds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingEmptyFile(t *testing.T) {
|
||||||
|
adds, err := Missing([]byte("# nothing yet\n"), []byte(fullTemplate), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(adds) != 5 {
|
||||||
|
t.Errorf("Missing() on an empty file = %d additions, want every top-level option (5)", len(adds))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingRejectsNonMapping(t *testing.T) {
|
||||||
|
if _, err := Missing([]byte("- a\n- b\n"), []byte(fullTemplate), nil); err == nil {
|
||||||
|
t.Error("Missing() on a top-level list succeeded, want an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUndocumentedKeys(t *testing.T) {
|
||||||
|
got, err := UndocumentedKeys(fullTemplate, schema{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(got) != 0 {
|
||||||
|
t.Errorf("UndocumentedKeys(full) = %v, want none", got)
|
||||||
|
}
|
||||||
|
got, _ = UndocumentedKeys(minimalTemplate, schema{})
|
||||||
|
want := "log-level listen[].tls limits tls"
|
||||||
|
if strings.Join(got, " ") != want {
|
||||||
|
t.Errorf("UndocumentedKeys(minimal) = %v, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingDoesNotOfferEntriesOfOperatorNamedMaps(t *testing.T) {
|
||||||
|
type backend struct {
|
||||||
|
Driver string `yaml:"driver"`
|
||||||
|
Root string `yaml:"root"`
|
||||||
|
}
|
||||||
|
type ctl struct {
|
||||||
|
Backends map[string]backend `yaml:"backends"`
|
||||||
|
}
|
||||||
|
tmpl := "backends:\n inbound:\n driver: filesystem\n root: /q\n"
|
||||||
|
file := "backends:\n queue:\n driver: filesystem\n root: /x\n"
|
||||||
|
adds, err := Missing([]byte(file), []byte(tmpl), ctl{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(adds) != 0 {
|
||||||
|
t.Errorf("Missing() with schema = %+v, want nothing (backends names are operator data)", adds)
|
||||||
|
}
|
||||||
|
// Without the schema the template's example entry is offered.
|
||||||
|
if adds, _ := Missing([]byte(file), []byte(tmpl), nil); len(adds) != 1 || adds[0].Key != "backends.inbound" {
|
||||||
|
t.Errorf("Missing() without schema = %+v, want backends.inbound", adds)
|
||||||
|
}
|
||||||
|
// A file without the map at all is offered the whole block.
|
||||||
|
if adds, _ := Missing([]byte("{}\n"), []byte(tmpl), ctl{}); len(adds) != 1 || adds[0].Key != "backends" {
|
||||||
|
t.Errorf("Missing() on a file without backends = %+v, want backends", adds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOptionalWithoutFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
s.Optional = true
|
||||||
|
s.Validate = func(path string) error {
|
||||||
|
if path != "" {
|
||||||
|
t.Errorf("Validate got %q, want the defaults (\"\")", path)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
code, out, errOut := run(t, s, "", "validate")
|
||||||
|
if code != ExitOK || !strings.Contains(out, "built-in defaults") {
|
||||||
|
t.Fatalf("validate: code %d, out %q, err %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
code, out, _ = run(t, s, "", "upgrade")
|
||||||
|
if code != ExitOK || !strings.Contains(out, "nothing to upgrade") {
|
||||||
|
t.Fatalf("upgrade: code %d, out %q", code, out)
|
||||||
|
}
|
||||||
|
// An explicit --config that does not exist is still an error.
|
||||||
|
if code, _, _ = run(t, s, filepath.Join(root, "nope.yaml"), "validate"); code != ExitProblem {
|
||||||
|
t.Fatalf("validate --config missing: code %d, want %d", code, ExitProblem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNone(t *testing.T) {
|
||||||
|
s := Spec{Name: "yatool", None: true}
|
||||||
|
for _, sub := range Subcommands {
|
||||||
|
code, out, _ := run(t, s, "", sub)
|
||||||
|
if code != ExitOK || out != "yatool has no configuration file\n" {
|
||||||
|
t.Errorf("%s: code %d, out %q", sub, code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code, _, _ := run(t, s, "", "bogus"); code != ExitUsage {
|
||||||
|
t.Errorf("bogus: code %d, want %d", code, ExitUsage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilenameAndFind(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
s.Filename = "custom.yml"
|
||||||
|
if _, err := s.Find(""); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatalf("Find without file: %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(root, "work", "custom.yml"), minimalTemplate)
|
||||||
|
l, err := s.Find("")
|
||||||
|
if err != nil || filepath.Base(l.Path) != "custom.yml" {
|
||||||
|
t.Fatalf("Find: %v, %v", l.Path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UnknownKey is a key of a configuration file that no option of the
|
||||||
|
// program has: a typo, an option of another program, or one a newer
|
||||||
|
// version dropped. The program ignores it, so it silently gets the
|
||||||
|
// default instead of what the operator meant.
|
||||||
|
type UnknownKey struct {
|
||||||
|
// Key is the dotted path ("pre-accept-checks.requre-known-domain");
|
||||||
|
// entries of a list are "listen[1].tls".
|
||||||
|
Key string
|
||||||
|
Line int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k UnknownKey) String() string { return fmt.Sprintf("%s (line %d)", k.Key, k.Line) }
|
||||||
|
|
||||||
|
// UnknownKeys lists the keys of raw that schema (the program's
|
||||||
|
// configuration struct, e.g. config.Config{}) has no field for, by its
|
||||||
|
// yaml tags. It descends into struct-typed mappings, lists of structs
|
||||||
|
// and maps of structs (a map of named backends: the names are the
|
||||||
|
// operator's, their contents are options). A type with its own
|
||||||
|
// UnmarshalYAML is taken as a whole: it decides itself what it accepts.
|
||||||
|
func UnknownKeys(raw []byte, schema any) ([]UnknownKey, error) {
|
||||||
|
var doc yaml.Node
|
||||||
|
if err := yaml.Unmarshal(raw, &doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing: %w", err)
|
||||||
|
}
|
||||||
|
root := docMapping(&doc)
|
||||||
|
if root == nil || schema == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var out []UnknownKey
|
||||||
|
walkUnknown(nil, reflect.TypeOf(schema), root, &out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnknownKeysFile is UnknownKeys for the file at path.
|
||||||
|
func UnknownKeysFile(path string, schema any) ([]UnknownKey, error) {
|
||||||
|
raw, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return UnknownKeys(raw, schema)
|
||||||
|
}
|
||||||
|
|
||||||
|
var unmarshalerType = reflect.TypeOf((*yaml.Unmarshaler)(nil)).Elem()
|
||||||
|
|
||||||
|
// opaque reports whether t decodes itself (or is no struct/map/list),
|
||||||
|
// so its contents are not checked key by key.
|
||||||
|
func opaque(t reflect.Type) bool {
|
||||||
|
if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch t.Kind() {
|
||||||
|
case reflect.Struct, reflect.Map, reflect.Slice, reflect.Array:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func walkUnknown(path []string, t reflect.Type, n *yaml.Node, out *[]UnknownKey) {
|
||||||
|
t = deref(t)
|
||||||
|
if opaque(t) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case n.Kind == yaml.MappingNode && t.Kind() == reflect.Struct:
|
||||||
|
for i := 0; i+1 < len(n.Content); i += 2 {
|
||||||
|
k, v := n.Content[i], n.Content[i+1]
|
||||||
|
sub := append(append([]string(nil), path...), k.Value)
|
||||||
|
ft, ok := fieldType(t, k.Value)
|
||||||
|
if !ok {
|
||||||
|
*out = append(*out, UnknownKey{Key: strings.Join(sub, "."), Line: k.Line})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
walkUnknown(sub, ft, v, out)
|
||||||
|
}
|
||||||
|
case n.Kind == yaml.MappingNode && t.Kind() == reflect.Map:
|
||||||
|
for i := 0; i+1 < len(n.Content); i += 2 {
|
||||||
|
k, v := n.Content[i], n.Content[i+1]
|
||||||
|
walkUnknown(append(append([]string(nil), path...), k.Value), t.Elem(), v, out)
|
||||||
|
}
|
||||||
|
case n.Kind == yaml.SequenceNode && (t.Kind() == reflect.Slice || t.Kind() == reflect.Array):
|
||||||
|
for i, item := range n.Content {
|
||||||
|
sub := append([]string(nil), path...)
|
||||||
|
if len(sub) > 0 {
|
||||||
|
sub[len(sub)-1] = fmt.Sprintf("%s[%d]", sub[len(sub)-1], i)
|
||||||
|
}
|
||||||
|
walkUnknown(sub, t.Elem(), item, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WarnUnknown logs every unknown option of the configuration file at
|
||||||
|
// path. A program calls it after loading its configuration: it keeps
|
||||||
|
// running with the defaults for those keys (a typo must not take a
|
||||||
|
// server down), but the operator sees why a setting has no effect.
|
||||||
|
func WarnUnknown(log *slog.Logger, path string, schema any) {
|
||||||
|
unknown, err := UnknownKeysFile(path, schema)
|
||||||
|
if err != nil {
|
||||||
|
return // Load already reported a file it cannot parse
|
||||||
|
}
|
||||||
|
for _, k := range unknown {
|
||||||
|
log.Warn("configuration: unknown option, ignored (the default applies)", "option", k.Key, "line", k.Line, "path", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnknownCheck is doctor's check of the file at path: ok without
|
||||||
|
// unknown options, else a note listing them.
|
||||||
|
func UnknownCheck(path string, schema any) (ok bool, note string) {
|
||||||
|
unknown, err := UnknownKeysFile(path, schema)
|
||||||
|
if err != nil {
|
||||||
|
return false, err.Error()
|
||||||
|
}
|
||||||
|
if len(unknown) == 0 {
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
|
parts := make([]string, len(unknown))
|
||||||
|
for i, k := range unknown {
|
||||||
|
parts[i] = k.String()
|
||||||
|
}
|
||||||
|
return false, "ignored, the defaults apply: " + strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type testInner struct {
|
||||||
|
Driver string `yaml:"driver"`
|
||||||
|
Root string `yaml:"root"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type testThrottle struct {
|
||||||
|
Enabled bool `yaml:"enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type testThrottleSection struct {
|
||||||
|
Config testThrottle `yaml:",inline"`
|
||||||
|
Storage testInner `yaml:"storage"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type testListener struct {
|
||||||
|
Address string `yaml:"address"`
|
||||||
|
TLS string `yaml:"tls"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type selfDecoding struct{ v map[string]string }
|
||||||
|
|
||||||
|
func (s *selfDecoding) UnmarshalYAML(n *yaml.Node) error { return n.Decode(&s.v) }
|
||||||
|
|
||||||
|
type testConfig struct {
|
||||||
|
LogLevel string `yaml:"log-level"`
|
||||||
|
Listen []testListener `yaml:"listen"`
|
||||||
|
Storage struct {
|
||||||
|
Mail *testInner `yaml:"mailstore"`
|
||||||
|
} `yaml:"storage"`
|
||||||
|
Backends map[string]testInner `yaml:"backends"`
|
||||||
|
Throttle testThrottleSection `yaml:"throttle"`
|
||||||
|
Timeout time.Duration `yaml:"timeout"`
|
||||||
|
Custom selfDecoding `yaml:"custom"`
|
||||||
|
Ignored string `yaml:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnknownKeys(t *testing.T) {
|
||||||
|
raw := []byte(`log-level: info
|
||||||
|
log-levle: debug
|
||||||
|
listen:
|
||||||
|
- address: ":25"
|
||||||
|
tsl: auto
|
||||||
|
storage:
|
||||||
|
mailstore:
|
||||||
|
driver: filesystem
|
||||||
|
rot: /x
|
||||||
|
backends:
|
||||||
|
inbound: {driver: filesystem, root: /q, extra: 1}
|
||||||
|
throttle:
|
||||||
|
enabled: true
|
||||||
|
storage: {driver: filesystem, root: /t}
|
||||||
|
enabeld: false
|
||||||
|
timeout: 5s
|
||||||
|
custom: {anything: goes}
|
||||||
|
Ignored: x
|
||||||
|
`)
|
||||||
|
got, err := UnknownKeys(raw, testConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []UnknownKey{
|
||||||
|
{"log-levle", 2},
|
||||||
|
{"listen[0].tsl", 5},
|
||||||
|
{"storage.mailstore.rot", 9},
|
||||||
|
{"backends.inbound.extra", 11},
|
||||||
|
{"throttle.enabeld", 15},
|
||||||
|
{"Ignored", 18},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("UnknownKeys =\n%v\nwant\n%v", got, want)
|
||||||
|
}
|
||||||
|
if got, _ := UnknownKeys([]byte("log-level: info\n"), testConfig{}); len(got) != 0 {
|
||||||
|
t.Fatalf("a clean file has unknown keys: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarnUnknownAndCheck(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "c.yaml")
|
||||||
|
if err := os.WriteFile(path, []byte("log-level: info\nlog-levle: debug\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
WarnUnknown(slog.New(slog.NewTextHandler(&buf, nil)), path, testConfig{})
|
||||||
|
if !strings.Contains(buf.String(), "level=WARN") || !strings.Contains(buf.String(), "option=log-levle") || !strings.Contains(buf.String(), "line=2") {
|
||||||
|
t.Errorf("warning = %q", buf.String())
|
||||||
|
}
|
||||||
|
if ok, note := UnknownCheck(path, testConfig{}); ok || !strings.Contains(note, "log-levle (line 2)") {
|
||||||
|
t.Errorf("check = %v %q", ok, note)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte("log-level: info\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok, note := UnknownCheck(path, testConfig{}); !ok || note != "" {
|
||||||
|
t.Errorf("clean file: %v %q", ok, note)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Addition is one option a configuration file does not mention yet,
|
||||||
|
// rendered from the full template as a commented YAML block.
|
||||||
|
type Addition struct {
|
||||||
|
// Key is the option's dotted path, e.g. "limits.connection-rate-per-source".
|
||||||
|
Key string
|
||||||
|
// Text is the commented block, indented for where it goes, ending
|
||||||
|
// in a newline.
|
||||||
|
Text string
|
||||||
|
// AfterLine is the 1-based line of the file the block goes after;
|
||||||
|
// 0 means the end of the file (a top-level option).
|
||||||
|
AfterLine int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing compares a configuration file with the full template and
|
||||||
|
// returns, in template order, every option the template documents that
|
||||||
|
// the file neither sets nor mentions as a "# key:" comment -- the same
|
||||||
|
// shape the blocks themselves are added in, so running it again on the
|
||||||
|
// upgraded file finds nothing.
|
||||||
|
//
|
||||||
|
// The comparison descends into mappings the file and the template both
|
||||||
|
// have; a list (listeners, blocklists, ...) is the operator's data and
|
||||||
|
// is never descended into, and neither is an option the file sets to a
|
||||||
|
// non-mapping value (e.g. "tls:" left empty on purpose).
|
||||||
|
//
|
||||||
|
// schema is the program's configuration struct (e.g. config.Config{}).
|
||||||
|
// With it, a mapping whose Go type is a map (keys the operator names,
|
||||||
|
// like a map of named backends) is operator data too: only its presence
|
||||||
|
// counts, the template's example entries are never offered inside it.
|
||||||
|
// nil compares by the template alone.
|
||||||
|
func Missing(raw, full []byte, schema any) ([]Addition, error) {
|
||||||
|
var file, tmpl yaml.Node
|
||||||
|
if err := yaml.Unmarshal(raw, &file); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing: %w", err)
|
||||||
|
}
|
||||||
|
if err := yaml.Unmarshal(full, &tmpl); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing the full template: %w", err)
|
||||||
|
}
|
||||||
|
troot := docMapping(&tmpl)
|
||||||
|
if troot == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
lines := strings.Split(string(raw), "\n")
|
||||||
|
froot := docMapping(&file)
|
||||||
|
if froot == nil {
|
||||||
|
if len(file.Content) > 0 {
|
||||||
|
return nil, fmt.Errorf("top level is not a mapping")
|
||||||
|
}
|
||||||
|
// empty (or comments only): every top-level option is missing
|
||||||
|
froot = &yaml.Node{Kind: yaml.MappingNode}
|
||||||
|
}
|
||||||
|
var t reflect.Type
|
||||||
|
if schema != nil {
|
||||||
|
t = reflect.TypeOf(schema)
|
||||||
|
}
|
||||||
|
return compare(nil, t, froot, troot, 0, 1, len(lines), 0, lines), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func docMapping(doc *yaml.Node) *yaml.Node {
|
||||||
|
if doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return doc.Content[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// compare collects the template keys missing in fmap. t is the Go type
|
||||||
|
// of the mapping (nil: unknown, compare by the template alone), from..to
|
||||||
|
// (1-based) are the file lines fmap spans, childIndent the column its
|
||||||
|
// keys start at, and afterLine where a missing key's block goes (0: end
|
||||||
|
// of file).
|
||||||
|
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
||||||
|
var out []Addition
|
||||||
|
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
||||||
|
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
||||||
|
sub := append(append([]string(nil), path...), tkey.Value)
|
||||||
|
var ft reflect.Type
|
||||||
|
if t != nil {
|
||||||
|
var ok bool
|
||||||
|
if ft, ok = fieldType(t, tkey.Value); !ok {
|
||||||
|
continue // not an option of this program
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fkey, fval := lookup(fmap, tkey.Value)
|
||||||
|
if fval != nil {
|
||||||
|
if fval.Kind == yaml.MappingNode && tval.Kind == yaml.MappingNode && fval.Style&yaml.FlowStyle == 0 &&
|
||||||
|
(ft == nil || deref(ft).Kind() == reflect.Struct) {
|
||||||
|
indent := childIndent + 2
|
||||||
|
if len(fval.Content) > 0 {
|
||||||
|
indent = fval.Content[0].Column - 1
|
||||||
|
}
|
||||||
|
end := blockEnd(lines, lastLine(fval), indent)
|
||||||
|
out = append(out, compare(sub, ft, fval, tval, indent, fkey.Line, end, end, lines)...)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if mentioned(lines, from, to, childIndent, tkey.Value) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, Addition{
|
||||||
|
Key: strings.Join(sub, "."),
|
||||||
|
Text: render(tkey, tval, childIndent),
|
||||||
|
AfterLine: afterLine,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookup(m *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
|
||||||
|
for i := 0; i+1 < len(m.Content); i += 2 {
|
||||||
|
if m.Content[i].Value == key {
|
||||||
|
return m.Content[i], m.Content[i+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// lastLine is the last file line a node's value occupies.
|
||||||
|
func lastLine(n *yaml.Node) int {
|
||||||
|
last := n.Line
|
||||||
|
if n.Kind == yaml.ScalarNode && n.Style&(yaml.LiteralStyle|yaml.FoldedStyle) != 0 {
|
||||||
|
last += strings.Count(strings.TrimRight(n.Value, "\n"), "\n") + 1
|
||||||
|
}
|
||||||
|
for _, c := range n.Content {
|
||||||
|
last = max(last, lastLine(c))
|
||||||
|
}
|
||||||
|
return last
|
||||||
|
}
|
||||||
|
|
||||||
|
func indentOf(l string) int { return len(l) - len(strings.TrimLeft(l, " ")) }
|
||||||
|
|
||||||
|
// blockEnd extends a block's last line over the comment lines right
|
||||||
|
// after it that are indented as its children -- blocks an earlier
|
||||||
|
// upgrade added there still belong to it.
|
||||||
|
func blockEnd(lines []string, last, minIndent int) int {
|
||||||
|
for last < len(lines) {
|
||||||
|
l := lines[last] // the line after "last" (1-based)
|
||||||
|
if !strings.HasPrefix(strings.TrimSpace(l), "#") || indentOf(l) < minIndent {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
last++
|
||||||
|
}
|
||||||
|
return last
|
||||||
|
}
|
||||||
|
|
||||||
|
// mentioned reports whether lines from..to (1-based) set key or carry it
|
||||||
|
// as a "# key:" comment at the given indent. Only "#" followed by at
|
||||||
|
// most one space counts, so the deeper lines of a commented block
|
||||||
|
// ("# driver: ...") are not taken for a sibling option.
|
||||||
|
func mentioned(lines []string, from, to, indent int, key string) bool {
|
||||||
|
re := regexp.MustCompile(`^#\s?` + regexp.QuoteMeta(key) + `:`)
|
||||||
|
for i := max(from, 1) - 1; i < to && i < len(lines); i++ {
|
||||||
|
if indentOf(lines[i]) == indent && re.MatchString(lines[i][indent:]) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// render returns one template option as a commented block at indent:
|
||||||
|
// the template's comment lines stay as they are, every YAML line gets
|
||||||
|
// "# " in front, so adding it changes nothing until the operator
|
||||||
|
// removes the "#".
|
||||||
|
func render(key, val *yaml.Node, indent int) string {
|
||||||
|
k := *key
|
||||||
|
k.FootComment = ""
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := yaml.NewEncoder(&buf)
|
||||||
|
enc.SetIndent(2)
|
||||||
|
_ = enc.Encode(&yaml.Node{Kind: yaml.MappingNode, Content: []*yaml.Node{&k, val}})
|
||||||
|
_ = enc.Close()
|
||||||
|
|
||||||
|
pad := strings.Repeat(" ", indent)
|
||||||
|
var b strings.Builder
|
||||||
|
for _, l := range strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") {
|
||||||
|
switch {
|
||||||
|
case strings.TrimSpace(l) == "":
|
||||||
|
case strings.HasPrefix(l, "#"):
|
||||||
|
b.WriteString(pad + l + "\n")
|
||||||
|
default:
|
||||||
|
b.WriteString(pad + "# " + l + "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply inserts the additions Missing returned into raw: nested ones
|
||||||
|
// after their line (bottom-up, so earlier line numbers stay valid),
|
||||||
|
// top-level ones at the end of the file.
|
||||||
|
func Apply(raw []byte, adds []Addition) []byte {
|
||||||
|
lines := strings.Split(string(raw), "\n")
|
||||||
|
byLine := map[int]string{}
|
||||||
|
var at []int
|
||||||
|
var tail strings.Builder
|
||||||
|
for _, a := range adds {
|
||||||
|
if a.AfterLine == 0 {
|
||||||
|
tail.WriteString("\n" + a.Text)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := byLine[a.AfterLine]; !ok {
|
||||||
|
at = append(at, a.AfterLine)
|
||||||
|
}
|
||||||
|
byLine[a.AfterLine] += a.Text
|
||||||
|
}
|
||||||
|
sort.Sort(sort.Reverse(sort.IntSlice(at)))
|
||||||
|
for _, n := range at {
|
||||||
|
n = min(n, len(lines))
|
||||||
|
ins := strings.Split(strings.TrimRight(byLine[n], "\n"), "\n")
|
||||||
|
lines = append(lines[:n], append(ins, lines[n:]...)...)
|
||||||
|
}
|
||||||
|
out := strings.Join(lines, "\n")
|
||||||
|
if tail.Len() > 0 {
|
||||||
|
out = strings.TrimRight(out, "\n") + "\n" + tail.String()
|
||||||
|
}
|
||||||
|
return []byte(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
||||||
|
// value, e.g. config.Config{}) that the template does not contain --
|
||||||
|
// neither as a key nor, for a list of structs, in the list's first
|
||||||
|
// item. A program's tests call it with its full template so that a new
|
||||||
|
// option cannot be added without documenting it, which is what keeps
|
||||||
|
// "config upgrade" useful.
|
||||||
|
func UndocumentedKeys(template string, schema any) ([]string, error) {
|
||||||
|
var doc yaml.Node
|
||||||
|
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing the template: %w", err)
|
||||||
|
}
|
||||||
|
root := docMapping(&doc)
|
||||||
|
if root == nil {
|
||||||
|
return nil, fmt.Errorf("template top level is not a mapping")
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
walkSchema(reflect.TypeOf(schema), root, nil, &out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
||||||
|
t = deref(t)
|
||||||
|
if t.Kind() != reflect.Struct {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i := range t.NumField() {
|
||||||
|
f := t.Field(i)
|
||||||
|
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||||
|
if name == "-" || !f.IsExported() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// An inline (embedded) struct's fields are keys of this mapping.
|
||||||
|
if f.Anonymous && strings.Contains(","+opts+",", ",inline,") {
|
||||||
|
walkSchema(f.Type, m, path, out)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
name = strings.ToLower(f.Name)
|
||||||
|
}
|
||||||
|
sub := append(append([]string(nil), path...), name)
|
||||||
|
_, val := lookup(m, name)
|
||||||
|
if val == nil {
|
||||||
|
*out = append(*out, strings.Join(sub, "."))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ft := deref(f.Type)
|
||||||
|
switch {
|
||||||
|
case ft.Kind() == reflect.Struct && val.Kind == yaml.MappingNode:
|
||||||
|
walkSchema(ft, val, sub, out)
|
||||||
|
case ft.Kind() == reflect.Slice && deref(ft.Elem()).Kind() == reflect.Struct &&
|
||||||
|
val.Kind == yaml.SequenceNode && len(val.Content) > 0 && val.Content[0].Kind == yaml.MappingNode:
|
||||||
|
walkSchema(ft.Elem(), val.Content[0], append(sub[:len(sub)-1:len(sub)-1], name+"[]"), out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fieldType returns the type of the field of struct t (or a pointer to
|
||||||
|
// one) whose YAML name is key.
|
||||||
|
func fieldType(t reflect.Type, key string) (reflect.Type, bool) {
|
||||||
|
t = deref(t)
|
||||||
|
if t.Kind() != reflect.Struct {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
for i := range t.NumField() {
|
||||||
|
f := t.Field(i)
|
||||||
|
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||||
|
if strings.Contains(","+opts+",", ",inline,") {
|
||||||
|
// An inline struct's keys are its parent's (named or
|
||||||
|
// embedded); an inline map takes every other key.
|
||||||
|
if deref(f.Type).Kind() == reflect.Map {
|
||||||
|
return deref(f.Type).Elem(), true
|
||||||
|
}
|
||||||
|
if ft, ok := fieldType(f.Type, key); ok {
|
||||||
|
return ft, true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
name = strings.ToLower(f.Name)
|
||||||
|
}
|
||||||
|
if name == key && name != "-" && f.IsExported() {
|
||||||
|
return f.Type, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func deref(t reflect.Type) reflect.Type {
|
||||||
|
for t.Kind() == reflect.Pointer {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// Package doctor is the shared "<program> doctor [--json]" command of the
|
||||||
|
// Yetano program standard (see docs/program-conventions.md in the yetano
|
||||||
|
// meta-repository): one report shape -- the locations the program
|
||||||
|
// resolves, and named checks -- printed as a table or as JSON, with one
|
||||||
|
// exit-code rule.
|
||||||
|
//
|
||||||
|
// r := doctor.Report{Program: "yasl"}
|
||||||
|
// r.AddPaths(app) // core/paths locations
|
||||||
|
// r.Check("config file valid", err == nil, note) // program-specific
|
||||||
|
// os.Exit(r.Run(args, os.Stdout, os.Stderr))
|
||||||
|
//
|
||||||
|
// A doctor only observes: it never creates a directory or file (a
|
||||||
|
// writability check may create and remove a probe file in a directory
|
||||||
|
// that already exists, and must say so in its note).
|
||||||
|
package doctor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Path is one location the program resolves. Exists is only observed.
|
||||||
|
type Path struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path,omitempty"`
|
||||||
|
Target string `json:"target,omitempty"` // symlink-resolved Path, when it differs
|
||||||
|
Exists bool `json:"exists"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check is one named check.
|
||||||
|
type Check struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Note string `json:"note,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report is "<program> doctor --json"'s output.
|
||||||
|
type Report struct {
|
||||||
|
Program string `json:"program,omitempty"`
|
||||||
|
Scope string `json:"scope,omitempty"` // "user" or "system"
|
||||||
|
Paths []Path `json:"paths"`
|
||||||
|
Checks []Check `json:"checks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exit codes of Run.
|
||||||
|
const (
|
||||||
|
ExitOK = 0 // every check passed
|
||||||
|
ExitProblems = 1 // at least one check failed
|
||||||
|
ExitUsage = 2 // bad arguments
|
||||||
|
)
|
||||||
|
|
||||||
|
// AddPath records a location, observing whether it exists.
|
||||||
|
func (r *Report) AddPath(name, path string, err error) {
|
||||||
|
p := Path{Name: name, Path: path}
|
||||||
|
if err != nil {
|
||||||
|
p.Error = err.Error()
|
||||||
|
} else if path != "" {
|
||||||
|
if _, statErr := os.Stat(path); statErr == nil {
|
||||||
|
p.Exists = true
|
||||||
|
}
|
||||||
|
if target, lerr := filepath.EvalSymlinks(path); lerr == nil && target != path {
|
||||||
|
p.Target = target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.Paths = append(r.Paths, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddPaths records the standard core/paths locations of app (config, data,
|
||||||
|
// state, cache, log; runtime only where the platform has one) and sets
|
||||||
|
// Scope.
|
||||||
|
func (r *Report) AddPaths(app core.Application) {
|
||||||
|
r.Scope = "user"
|
||||||
|
if app.Scope == core.SystemScope {
|
||||||
|
r.Scope = "system"
|
||||||
|
}
|
||||||
|
res, err := paths.For(app)
|
||||||
|
if err != nil {
|
||||||
|
r.AddPath("paths", "", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range []struct {
|
||||||
|
name string
|
||||||
|
fn func() (string, error)
|
||||||
|
}{
|
||||||
|
{"config dir", res.ConfigDir},
|
||||||
|
{"data dir", res.DataDir},
|
||||||
|
{"state dir", res.StateDir},
|
||||||
|
{"cache dir", res.CacheDir},
|
||||||
|
{"log dir", res.LogDir},
|
||||||
|
} {
|
||||||
|
p, err := c.fn()
|
||||||
|
r.AddPath(c.name, p, err)
|
||||||
|
}
|
||||||
|
if p, err := res.RuntimeDir(); err == nil && p != "" {
|
||||||
|
r.AddPath("runtime dir", p, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check records a named check.
|
||||||
|
func (r *Report) Check(name string, ok bool, note string) {
|
||||||
|
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Problems counts failed checks.
|
||||||
|
func (r Report) Problems() int {
|
||||||
|
n := 0
|
||||||
|
for _, c := range r.Checks {
|
||||||
|
if !c.OK {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write prints the report: JSON, or a paths table and a checks table.
|
||||||
|
func (r Report) Write(w io.Writer, asJSON bool) error {
|
||||||
|
if asJSON {
|
||||||
|
if r.Paths == nil {
|
||||||
|
r.Paths = []Path{}
|
||||||
|
}
|
||||||
|
if r.Checks == nil {
|
||||||
|
r.Checks = []Check{}
|
||||||
|
}
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(r)
|
||||||
|
}
|
||||||
|
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
|
||||||
|
if len(r.Paths) > 0 {
|
||||||
|
fmt.Fprintf(tw, "PATH\tLOCATION\tEXISTS\n")
|
||||||
|
for _, p := range r.Paths {
|
||||||
|
loc := p.Path
|
||||||
|
if p.Error != "" {
|
||||||
|
loc = "error: " + p.Error
|
||||||
|
} else if p.Target != "" {
|
||||||
|
loc += " -> " + p.Target
|
||||||
|
}
|
||||||
|
fmt.Fprintf(tw, "%s\t%s\t%s\n", p.Name, loc, yesNo(p.Exists))
|
||||||
|
}
|
||||||
|
fmt.Fprintln(tw)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n")
|
||||||
|
for _, c := range r.Checks {
|
||||||
|
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note)
|
||||||
|
}
|
||||||
|
return tw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
func yesNo(b bool) string {
|
||||||
|
if b {
|
||||||
|
return "yes"
|
||||||
|
}
|
||||||
|
return "no"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run serves "<program> doctor [--json]" -- args are the arguments after
|
||||||
|
// "doctor" -- and returns the exit code: ExitOK, ExitProblems (also
|
||||||
|
// reported on stderr), or ExitUsage.
|
||||||
|
func (r Report) Run(args []string, stdout, stderr io.Writer) int {
|
||||||
|
asJSON := false
|
||||||
|
for _, a := range args {
|
||||||
|
switch a {
|
||||||
|
case "--json", "-json":
|
||||||
|
asJSON = true
|
||||||
|
case "-h", "--help", "-help":
|
||||||
|
fmt.Fprintf(stdout, "usage: %s doctor [--json]\n", nameOr(r.Program))
|
||||||
|
return ExitOK
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "usage: %s doctor [--json] (unknown argument %q)\n", nameOr(r.Program), a)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := r.Write(stdout, asJSON); err != nil {
|
||||||
|
fmt.Fprintln(stderr, err)
|
||||||
|
return ExitProblems
|
||||||
|
}
|
||||||
|
if n := r.Problems(); n > 0 {
|
||||||
|
fmt.Fprintf(stderr, "%s doctor: %d problem(s) found\n", nameOr(r.Program), n)
|
||||||
|
return ExitProblems
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func nameOr(s string) string {
|
||||||
|
if strings.TrimSpace(s) == "" {
|
||||||
|
return "program"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package doctor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRun(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
r := Report{Program: "tool"}
|
||||||
|
r.AddPath("data dir", dir, nil)
|
||||||
|
r.AddPath("missing", filepath.Join(dir, "nope"), nil)
|
||||||
|
r.AddPath("broken", "", errors.New("no home"))
|
||||||
|
r.Check("config valid", true, "")
|
||||||
|
|
||||||
|
var out, errOut strings.Builder
|
||||||
|
if code := r.Run([]string{"--json"}, &out, &errOut); code != ExitOK {
|
||||||
|
t.Fatalf("exit %d: %s", code, errOut.String())
|
||||||
|
}
|
||||||
|
var got Report
|
||||||
|
if err := json.Unmarshal([]byte(out.String()), &got); err != nil || len(got.Paths) != 3 || !got.Paths[0].Exists || got.Paths[1].Exists || got.Paths[2].Error != "no home" {
|
||||||
|
t.Fatalf("json: %v %+v", err, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Check("listener port free", false, "port 514 in use")
|
||||||
|
out.Reset()
|
||||||
|
if code := r.Run(nil, &out, &errOut); code != ExitProblems || !strings.Contains(out.String(), "port 514 in use") || !strings.Contains(errOut.String(), "1 problem") {
|
||||||
|
t.Fatalf("problems: %d %q %q", code, out.String(), errOut.String())
|
||||||
|
}
|
||||||
|
if code := r.Run([]string{"--bogus"}, &out, &errOut); code != ExitUsage {
|
||||||
|
t.Fatalf("usage: %d", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddPaths(t *testing.T) {
|
||||||
|
var r Report
|
||||||
|
r.AddPaths(core.Application{Name: "doctor-test", Kind: core.CLI})
|
||||||
|
if r.Scope != "user" || len(r.Paths) < 5 || r.Paths[0].Name != "config dir" {
|
||||||
|
t.Fatalf("paths: %+v", r)
|
||||||
|
}
|
||||||
|
for _, p := range r.Paths {
|
||||||
|
if p.Error == "" && p.Path == "" {
|
||||||
|
t.Errorf("%s: no path", p.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
// Package manual gives a Yetano program its embedded, self-served manual:
|
||||||
|
// the "<program> manual" command of ADR-0012, in one shared shape.
|
||||||
|
//
|
||||||
|
// A program embeds its documentation -- usually README.md and docs/*.md,
|
||||||
|
// with a //go:embed in a Go file at the module root, since go:embed cannot
|
||||||
|
// reach parent directories -- and hands it to FromFS; Run then serves
|
||||||
|
//
|
||||||
|
// <program> manual topic list
|
||||||
|
// <program> manual <topic> one topic's Markdown
|
||||||
|
// <program> manual --json [{"slug", "title", "path"}, ...]
|
||||||
|
// <program> manual --json <topic> {"slug", "title", "path", "markdown"}
|
||||||
|
//
|
||||||
|
// The --json form is what yet reads to show an installed program's manual
|
||||||
|
// in "yet manual --package", its TUI and yet-gui (yet's own "yet manual
|
||||||
|
// --json" uses the same shape). path is the page's source path in the
|
||||||
|
// repository, so relative links between pages resolve against it.
|
||||||
|
package manual
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Topic is one manual page.
|
||||||
|
type Topic struct {
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manual is a program's embedded manual.
|
||||||
|
type Manual struct {
|
||||||
|
// Name is the program name, used in the plain-text listing.
|
||||||
|
Name string
|
||||||
|
FS fs.FS
|
||||||
|
Topics []Topic
|
||||||
|
}
|
||||||
|
|
||||||
|
var heading = regexp.MustCompile(`(?m)^#\s+(.+?)\s*#*\s*$`)
|
||||||
|
|
||||||
|
// FromFS builds a Manual from fsys: README.md first (slug "readme"), then
|
||||||
|
// every *.md under docs/ (recursively, by path; slug: the path below docs/
|
||||||
|
// without ".md", e.g. "configuration" or "adr/0001-x"). A page's title is
|
||||||
|
// its first "# " heading, else its slug. Other files are ignored.
|
||||||
|
func FromFS(name string, fsys fs.FS) (Manual, error) {
|
||||||
|
m := Manual{Name: name, FS: fsys}
|
||||||
|
if data, err := fs.ReadFile(fsys, "README.md"); err == nil {
|
||||||
|
m.Topics = append(m.Topics, Topic{Slug: "readme", Title: titleOf(data, "Overview"), Path: "README.md"})
|
||||||
|
}
|
||||||
|
var docs []Topic
|
||||||
|
err := fs.WalkDir(fsys, "docs", func(p string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, fs.ErrNotExist) && p == "docs" {
|
||||||
|
return fs.SkipDir
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.IsDir() || !strings.EqualFold(path.Ext(p), ".md") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
data, err := fs.ReadFile(fsys, p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
slug := strings.TrimSuffix(strings.TrimPrefix(p, "docs/"), path.Ext(p))
|
||||||
|
docs = append(docs, Topic{Slug: slug, Title: titleOf(data, slug), Path: p})
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Manual{}, err
|
||||||
|
}
|
||||||
|
sort.Slice(docs, func(i, j int) bool { return docs[i].Path < docs[j].Path })
|
||||||
|
m.Topics = append(m.Topics, docs...)
|
||||||
|
if len(m.Topics) == 0 {
|
||||||
|
return Manual{}, errors.New("manual: no README.md and no docs/*.md in the embedded files")
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustFromFS is FromFS for a package-level variable; it panics on error
|
||||||
|
// (a missing embed is a build mistake).
|
||||||
|
func MustFromFS(name string, fsys fs.FS) Manual {
|
||||||
|
m, err := FromFS(name, fsys)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
func titleOf(data []byte, fallback string) string {
|
||||||
|
if m := heading.FindSubmatch(data); m != nil {
|
||||||
|
return string(m[1])
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the topic with slug.
|
||||||
|
func (m Manual) Lookup(slug string) (Topic, bool) {
|
||||||
|
for _, t := range m.Topics {
|
||||||
|
if t.Slug == slug {
|
||||||
|
return t, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Topic{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Markdown returns a topic's source.
|
||||||
|
func (m Manual) Markdown(t Topic) (string, error) {
|
||||||
|
data, err := fs.ReadFile(m.FS, t.Path)
|
||||||
|
return string(data), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrUsage is returned by Run for bad arguments; the caller should print
|
||||||
|
// it and exit with its usage exit code.
|
||||||
|
var ErrUsage = errors.New("usage: manual [--json] [topic]")
|
||||||
|
|
||||||
|
// Run serves "<program> manual [--json] [topic]" -- args are the
|
||||||
|
// arguments after "manual" -- writing to w. An unknown topic is an error
|
||||||
|
// (the caller exits non-zero).
|
||||||
|
func (m Manual) Run(args []string, w io.Writer) error {
|
||||||
|
asJSON := false
|
||||||
|
var rest []string
|
||||||
|
for _, a := range args {
|
||||||
|
switch a {
|
||||||
|
case "--json", "-json":
|
||||||
|
asJSON = true
|
||||||
|
case "-h", "--help", "-help":
|
||||||
|
fmt.Fprintf(w, "usage: %s manual [--json] [topic]\n", m.Name)
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(a, "-") {
|
||||||
|
return fmt.Errorf("%w (unknown flag %q)", ErrUsage, a)
|
||||||
|
}
|
||||||
|
rest = append(rest, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(rest) > 1 {
|
||||||
|
return ErrUsage
|
||||||
|
}
|
||||||
|
if len(rest) == 0 {
|
||||||
|
if asJSON {
|
||||||
|
return writeJSON(w, m.Topics)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "%s manual topics:\n", m.Name)
|
||||||
|
for _, t := range m.Topics {
|
||||||
|
fmt.Fprintf(w, " %-28s %s\n", t.Slug, t.Title)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "\nrun \"%s manual <topic>\" to read one\n", m.Name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
t, ok := m.Lookup(rest[0])
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("unknown manual topic %q (run \"%s manual\" for the list)", rest[0], m.Name)
|
||||||
|
}
|
||||||
|
md, err := m.Markdown(t)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if asJSON {
|
||||||
|
return writeJSON(w, struct {
|
||||||
|
Topic
|
||||||
|
Markdown string `json:"markdown"`
|
||||||
|
}{t, md})
|
||||||
|
}
|
||||||
|
_, err = io.WriteString(w, md)
|
||||||
|
if err == nil && !strings.HasSuffix(md, "\n") {
|
||||||
|
_, err = io.WriteString(w, "\n")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w io.Writer, v any) error {
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(v)
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package manual
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testFS() fstest.MapFS {
|
||||||
|
return fstest.MapFS{
|
||||||
|
"README.md": {Data: []byte("# Tool\n\nIntro.\n")},
|
||||||
|
"docs/configuration.md": {Data: []byte("# Configuration\n\nKeys.")},
|
||||||
|
"docs/adr/0001-decision.md": {Data: []byte("no heading here")},
|
||||||
|
"docs/image.png": {Data: []byte("x")},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFromFSAndJSON(t *testing.T) {
|
||||||
|
m, err := FromFS("tool", testFS())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []Topic{
|
||||||
|
{Slug: "readme", Title: "Tool", Path: "README.md"},
|
||||||
|
{Slug: "adr/0001-decision", Title: "adr/0001-decision", Path: "docs/adr/0001-decision.md"},
|
||||||
|
{Slug: "configuration", Title: "Configuration", Path: "docs/configuration.md"},
|
||||||
|
}
|
||||||
|
if len(m.Topics) != len(want) {
|
||||||
|
t.Fatalf("topics = %+v", m.Topics)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if m.Topics[i] != want[i] {
|
||||||
|
t.Errorf("topic %d = %+v, want %+v", i, m.Topics[i], want[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
if err := m.Run([]string{"--json"}, &b); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var list []Topic
|
||||||
|
if err := json.Unmarshal([]byte(b.String()), &list); err != nil || len(list) != 3 {
|
||||||
|
t.Fatalf("list json: %v %s", err, b.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
b.Reset()
|
||||||
|
if err := m.Run([]string{"--json", "configuration"}, &b); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var page struct {
|
||||||
|
Topic
|
||||||
|
Markdown string `json:"markdown"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(b.String()), &page); err != nil || page.Markdown != "# Configuration\n\nKeys." || page.Path != "docs/configuration.md" {
|
||||||
|
t.Fatalf("page json: %v %+v", err, page)
|
||||||
|
}
|
||||||
|
|
||||||
|
b.Reset()
|
||||||
|
if err := m.Run([]string{"readme"}, &b); err != nil || b.String() != "# Tool\n\nIntro.\n" {
|
||||||
|
t.Fatalf("plain page: %v %q", err, b.String())
|
||||||
|
}
|
||||||
|
b.Reset()
|
||||||
|
if err := m.Run(nil, &b); err != nil || !strings.Contains(b.String(), "configuration") {
|
||||||
|
t.Fatalf("plain list: %v %q", err, b.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunErrors(t *testing.T) {
|
||||||
|
m := MustFromFS("tool", testFS())
|
||||||
|
var b strings.Builder
|
||||||
|
if err := m.Run([]string{"nope"}, &b); err == nil {
|
||||||
|
t.Error("unknown topic should fail")
|
||||||
|
}
|
||||||
|
if err := m.Run([]string{"--bogus"}, &b); !errors.Is(err, ErrUsage) {
|
||||||
|
t.Errorf("unknown flag: %v", err)
|
||||||
|
}
|
||||||
|
if err := m.Run([]string{"a", "b"}, &b); !errors.Is(err, ErrUsage) {
|
||||||
|
t.Errorf("two topics: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := FromFS("empty", fstestEmpty()); err == nil {
|
||||||
|
t.Error("an empty manual should be an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func fstestEmpty() fstest.MapFS { return fstest.MapFS{"x.txt": {Data: []byte("x")}} }
|
||||||
+4
-4
@@ -136,10 +136,10 @@ func (r *Resolver) logDirValue() (value, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// LogAliasDir returns the optional Unix convenience location
|
// LogAliasDir returns the optional Unix convenience location
|
||||||
// ~/.local/log/<app> (spec section 39). It is never created
|
// ~/.local/log/<app> (spec section 39). Resolving it never creates
|
||||||
// automatically; nothing else in this package treats it as canonical.
|
// anything -- use EnsureLogAlias for that; nothing else in this package
|
||||||
// On Windows and macOS Desktop it is the same as LogDir (there is no
|
// treats it as canonical. On Windows and macOS Desktop it is the same as
|
||||||
// separate alias convention there).
|
// LogDir (there is no separate alias convention there).
|
||||||
func (r *Resolver) LogAliasDir() (string, error) {
|
func (r *Resolver) LogAliasDir() (string, error) {
|
||||||
if r.isWindows() || r.isDarwinDesktop() {
|
if r.isWindows() || r.isDarwinDesktop() {
|
||||||
return r.LogDir()
|
return r.LogDir()
|
||||||
|
|||||||
+100
-1
@@ -103,11 +103,110 @@ func TestLogAliasDirWindowsFallsBackToLogDir(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEnsureLogAliasCreatesSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
env := map[string]string{"HOME": "/home/test"}
|
||||||
|
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
|
||||||
|
|
||||||
|
alias, err := r.EnsureLogAlias()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EnsureLogAlias: %v", err)
|
||||||
|
}
|
||||||
|
wantAlias, err := r.LogAliasDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LogAliasDir: %v", err)
|
||||||
|
}
|
||||||
|
if alias != wantAlias {
|
||||||
|
t.Errorf("EnsureLogAlias() = %q, want %q", alias, wantAlias)
|
||||||
|
}
|
||||||
|
info, err := os.Lstat(alias)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Lstat(%q): %v", alias, err)
|
||||||
|
}
|
||||||
|
if info.Mode()&os.ModeSymlink == 0 {
|
||||||
|
t.Fatalf("%q was not created as a symlink", alias)
|
||||||
|
}
|
||||||
|
target, err := os.Readlink(alias)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Readlink(%q): %v", alias, err)
|
||||||
|
}
|
||||||
|
logDir, err := r.LogDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LogDir: %v", err)
|
||||||
|
}
|
||||||
|
if target != logDir {
|
||||||
|
t.Errorf("symlink target = %q, want %q", target, logDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotent: a second call must not fail or touch the existing link.
|
||||||
|
if _, err := r.EnsureLogAlias(); err != nil {
|
||||||
|
t.Fatalf("EnsureLogAlias (second call): %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureLogAliasLeavesExistingEntryAlone(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
env := map[string]string{"HOME": "/home/test"}
|
||||||
|
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
|
||||||
|
|
||||||
|
alias, err := r.LogAliasDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LogAliasDir: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(alias, 0o700); err != nil {
|
||||||
|
t.Fatalf("MkdirAll(%q): %v", alias, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := r.EnsureLogAlias()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EnsureLogAlias: %v", err)
|
||||||
|
}
|
||||||
|
if got != alias {
|
||||||
|
t.Errorf("EnsureLogAlias() = %q, want %q", got, alias)
|
||||||
|
}
|
||||||
|
info, err := os.Lstat(alias)
|
||||||
|
if err != nil || !info.IsDir() {
|
||||||
|
t.Errorf("pre-existing directory at %q was replaced (err=%v)", alias, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureLogAliasWindowsEqualsLogDir(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithRoot(root))
|
||||||
|
|
||||||
|
alias, err := r.EnsureLogAlias()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EnsureLogAlias: %v", err)
|
||||||
|
}
|
||||||
|
logDir, err := r.LogDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LogDir: %v", err)
|
||||||
|
}
|
||||||
|
if alias != logDir {
|
||||||
|
t.Errorf("EnsureLogAlias() = %q, want %q (LogDir)", alias, logDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDarwinDesktopRuntimeDirPrefersTMPDIR(t *testing.T) {
|
||||||
|
env := map[string]string{"HOME": "/Users/test", "TMPDIR": "/var/folders/zz/T/"}
|
||||||
|
app := core.Application{Name: "yapama", Kind: core.Desktop}
|
||||||
|
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(env))
|
||||||
|
|
||||||
|
if got, err := r.RuntimeDir(); err != nil || got != "/var/folders/zz/T/yapama" {
|
||||||
|
t.Errorf("RuntimeDir() = (%q, %v), want /var/folders/zz/T/yapama", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestEnsureAllCategories(t *testing.T) {
|
func TestEnsureAllCategories(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
env := map[string]string{"HOME": "/home/test"}
|
env := map[string]string{"HOME": "/home/test"}
|
||||||
|
// WithRuntimeDir takes a bare path in the simulated platform's
|
||||||
|
// family (here Linux/Unix); applyRoot nests it under root exactly
|
||||||
|
// once -- pre-pending root here too would double-root it (and, on a
|
||||||
|
// real Windows host where root is itself Windows-native, produce an
|
||||||
|
// invalid mid-path drive letter).
|
||||||
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root),
|
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root),
|
||||||
WithRuntimeDir(root+"/runtime-override"))
|
WithRuntimeDir("/runtime-override"))
|
||||||
|
|
||||||
ensures := []func() (string, error){
|
ensures := []func() (string, error){
|
||||||
r.EnsureConfigDir, r.EnsureDataDir, r.EnsureStateDir,
|
r.EnsureConfigDir, r.EnsureDataDir, r.EnsureStateDir,
|
||||||
|
|||||||
+33
-4
@@ -13,6 +13,15 @@ import "yetano.dev/yetano/core"
|
|||||||
// preferences-adjacent files and its bulk data side by side); State gets
|
// preferences-adjacent files and its bulk data side by side); State gets
|
||||||
// its own subdirectory so it doesn't collide with either.
|
// its own subdirectory so it doesn't collide with either.
|
||||||
|
|
||||||
|
// darwinFlavor is the Linux layout CLI and Service applications use on
|
||||||
|
// macOS, except the system runtime base: macOS has no /run, its
|
||||||
|
// equivalent is /var/run.
|
||||||
|
var darwinFlavor = func() unixFlavor {
|
||||||
|
f := linuxFlavor
|
||||||
|
f.systemRuntimeBase = "/var/run"
|
||||||
|
return f
|
||||||
|
}()
|
||||||
|
|
||||||
func darwinAppSupportBase(scope core.Scope, home string) string {
|
func darwinAppSupportBase(scope core.Scope, home string) string {
|
||||||
if scope == core.SystemScope {
|
if scope == core.SystemScope {
|
||||||
return "/Library/Application Support"
|
return "/Library/Application Support"
|
||||||
@@ -80,7 +89,11 @@ func (r *Resolver) darwinDesktopStateDir() (value, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return value{}, err
|
return value{}, err
|
||||||
}
|
}
|
||||||
return value{path: unixJoin(app.path, "State"), source: app.source}, nil
|
// app.path already applied the root (see applyRootRebase), which can
|
||||||
|
// be a different address family than this simulated platform -- use
|
||||||
|
// JoinDirFile, not unixJoin, so the "State" suffix lands in whichever
|
||||||
|
// family app.path actually ended up in.
|
||||||
|
return value{path: JoinDirFile(app.path, "State"), source: app.source}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Resolver) darwinDesktopCacheDir() (value, error) {
|
func (r *Resolver) darwinDesktopCacheDir() (value, error) {
|
||||||
@@ -113,15 +126,28 @@ func (r *Resolver) darwinDesktopLogDir() (value, error) {
|
|||||||
return value{path: r.applyRoot(unixJoin(darwinLogsBase(r.app.Scope, home), r.app.Name)), source: source}, nil
|
return value{path: r.applyRoot(unixJoin(darwinLogsBase(r.app.Scope, home), r.app.Name)), source: source}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// darwinDesktopRuntimeDir prefers $TMPDIR -- the per-user, securely
|
||||||
|
// permissioned, OS-managed ephemeral directory macOS itself hands every
|
||||||
|
// process (confstr(_CS_DARWIN_USER_TEMP_DIR), what NSTemporaryDirectory()
|
||||||
|
// returns), the closest real native equivalent to XDG_RUNTIME_DIR's
|
||||||
|
// role. It falls back to the previous Application Support-based location
|
||||||
|
// only when TMPDIR is unset in the resolved environment (e.g. a
|
||||||
|
// simulated/test environment that never set it) -- see AGENTS.md TODO
|
||||||
|
// history: this was a placeholder before TMPDIR was wired in here.
|
||||||
func (r *Resolver) darwinDesktopRuntimeDir() (value, error) {
|
func (r *Resolver) darwinDesktopRuntimeDir() (value, error) {
|
||||||
if v, ok := r.overrideValue(RuntimePath); ok {
|
if v, ok := r.overrideValue(RuntimePath); ok {
|
||||||
return value{path: r.applyRoot(v.path), source: v.source}, nil
|
return value{path: r.applyRoot(v.path), source: v.source}, nil
|
||||||
}
|
}
|
||||||
|
if tmpdir, ok := lookup(r.env, "TMPDIR"); ok {
|
||||||
|
return value{path: r.applyRoot(unixJoin(tmpdir, r.app.Name)), source: MacOSNative}, nil
|
||||||
|
}
|
||||||
app, err := r.darwinDesktopAppDir()
|
app, err := r.darwinDesktopAppDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return value{}, err
|
return value{}, err
|
||||||
}
|
}
|
||||||
return value{path: unixJoin(app.path, "Runtime"), source: app.source}, nil
|
// See darwinDesktopStateDir: app.path is already rooted and may be in
|
||||||
|
// either address family, so JoinDirFile picks the right one.
|
||||||
|
return value{path: JoinDirFile(app.path, "Runtime"), source: app.source}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// darwinDesktopBinDir has no native GUI-app convention; it reuses the
|
// darwinDesktopBinDir has no native GUI-app convention; it reuses the
|
||||||
@@ -143,16 +169,19 @@ func (r *Resolver) darwinDesktopLayers(kind PathKind, base func(core.Scope, stri
|
|||||||
if v, ok := r.overrideValue(kind); ok {
|
if v, ok := r.overrideValue(kind); ok {
|
||||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||||
}
|
}
|
||||||
|
var user []layer
|
||||||
home, err := r.homeDir()
|
home, err := r.homeDir()
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
user := []layer{{
|
if err == nil {
|
||||||
|
user = []layer{{
|
||||||
path: r.applyRoot(unixJoin(base(core.UserScope, home), r.app.Name)),
|
path: r.applyRoot(unixJoin(base(core.UserScope, home), r.app.Name)),
|
||||||
source: MacOSNative,
|
source: MacOSNative,
|
||||||
priority: PriorityUser,
|
priority: PriorityUser,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
}}
|
}}
|
||||||
|
}
|
||||||
system := []layer{{
|
system := []layer{{
|
||||||
path: r.applyRoot(unixJoin(base(core.SystemScope, ""), r.app.Name)),
|
path: r.applyRoot(unixJoin(base(core.SystemScope, ""), r.app.Name)),
|
||||||
source: SystemDirectory,
|
source: SystemDirectory,
|
||||||
|
|||||||
@@ -93,3 +93,19 @@ func TestDarwinServiceUsesXDGLikeLayout(t *testing.T) {
|
|||||||
t.Errorf("ConfigDir() = %q, want %q (macOS Service should match Linux layout)", got, want)
|
t.Errorf("ConfigDir() = %q, want %q (macOS Service should match Linux layout)", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDarwinServiceSystemRuntimeDirIsVarRun(t *testing.T) {
|
||||||
|
app := core.Application{Name: "yasta", Kind: core.Service, Scope: core.SystemScope}
|
||||||
|
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(map[string]string{}))
|
||||||
|
got, err := r.RuntimeDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("RuntimeDir: %v", err)
|
||||||
|
}
|
||||||
|
if want := "/var/run/yasta"; got != want {
|
||||||
|
t.Errorf("RuntimeDir() = %q, want %q (macOS has no /run)", got, want)
|
||||||
|
}
|
||||||
|
lin := mustResolver(t, app, WithPlatform("linux"), WithEnvironment(map[string]string{}))
|
||||||
|
if got, _ := lin.RuntimeDir(); got != "/run/yasta" {
|
||||||
|
t.Errorf("linux RuntimeDir() = %q, want /run/yasta", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+81
-14
@@ -76,6 +76,22 @@ func JoinFamily(platform string, elems ...string) string {
|
|||||||
return unixJoin(elems...)
|
return unixJoin(elems...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// JoinDirFileFamily joins dir and name like JoinDirFile (inferring the
|
||||||
|
// family from dir's own content when it contains a separator of either
|
||||||
|
// kind), falling back to platform's family (as JoinFamily does) only
|
||||||
|
// when dir is ambiguous -- has no separator of its own to infer from,
|
||||||
|
// such as a bare "." (core/config's default working-directory layer
|
||||||
|
// before WithWorkdirPath overrides it). Prefer this over JoinFamily
|
||||||
|
// whenever dir might come from a real filesystem path (e.g. WithRoot's
|
||||||
|
// root, or a caller-supplied override) rather than always being a
|
||||||
|
// hardcoded literal in platform's own family.
|
||||||
|
func JoinDirFileFamily(platform, dir, name string) string {
|
||||||
|
if !strings.ContainsRune(dir, '/') && !strings.ContainsRune(dir, '\\') {
|
||||||
|
return JoinFamily(platform, dir, name)
|
||||||
|
}
|
||||||
|
return JoinDirFile(dir, name)
|
||||||
|
}
|
||||||
|
|
||||||
// JoinDirFile joins a directory (as produced by ConfigSearchDirs/
|
// JoinDirFile joins a directory (as produced by ConfigSearchDirs/
|
||||||
// DataSearchDirs/ExecutableSearchDirs, in either address family) with a
|
// DataSearchDirs/ExecutableSearchDirs, in either address family) with a
|
||||||
// plain file name, picking the join style from the directory's own
|
// plain file name, picking the join style from the directory's own
|
||||||
@@ -113,24 +129,75 @@ func splitWindowsRoot(p string) (root, rest string, ok bool) {
|
|||||||
return "", "", false
|
return "", "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
// applyRootUnix rebases an absolute unix-family path under root, when
|
// isWindowsPath reports whether p looks like a Windows-family path
|
||||||
// root is set. An empty root leaves p untouched.
|
// (backslash-separated, no forward slash) -- the same content-based
|
||||||
func applyRootUnix(root, p string) string {
|
// heuristic JoinDirFile uses, applied here to root rather than to a
|
||||||
if root == "" {
|
// resolved category directory.
|
||||||
return p
|
func isWindowsPath(p string) bool {
|
||||||
}
|
return strings.ContainsRune(p, '\\') && !strings.ContainsRune(p, '/')
|
||||||
return unixJoin(root, strings.TrimPrefix(p, "/"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// applyRootWindows rebases an absolute windows-family path under root,
|
// pathSegments splits an absolute path p (in the given family) into its
|
||||||
// when root is set. An empty root leaves p untouched.
|
// plain path components, discarding p's own absolute-path root marker
|
||||||
func applyRootWindows(root, p string) string {
|
// (a leading "/" for Unix; a drive letter or UNC share for Windows).
|
||||||
|
func pathSegments(p string, windowsFamily bool) []string {
|
||||||
|
if windowsFamily {
|
||||||
|
rest := p
|
||||||
|
if _, r, ok := splitWindowsRoot(p); ok {
|
||||||
|
rest = r
|
||||||
|
}
|
||||||
|
return splitNonEmpty(rest, '\\')
|
||||||
|
}
|
||||||
|
return splitNonEmpty(strings.TrimPrefix(p, "/"), '/')
|
||||||
|
}
|
||||||
|
|
||||||
|
// dirName returns p's parent directory, picking "/"- or "\"-based
|
||||||
|
// splitting from p's own content (the same heuristic JoinDirFile uses)
|
||||||
|
// rather than the host OS's path/filepath conventions -- a resolved
|
||||||
|
// path's family depends on WithRoot's root, not on the host this code
|
||||||
|
// happens to run on (see applyRootRebase), so path/filepath (or the
|
||||||
|
// stdlib "path" package) would silently pick the wrong separator, or
|
||||||
|
// none at all, whenever the two differ.
|
||||||
|
func dirName(p string) string {
|
||||||
|
sep := byte('/')
|
||||||
|
if isWindowsPath(p) {
|
||||||
|
sep = '\\'
|
||||||
|
}
|
||||||
|
if i := strings.LastIndexByte(p, sep); i >= 0 {
|
||||||
|
return p[:i]
|
||||||
|
}
|
||||||
|
return "."
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitNonEmpty(s string, sep byte) []string {
|
||||||
|
var out []string
|
||||||
|
for part := range strings.SplitSeq(s, string(sep)) {
|
||||||
|
if part != "" {
|
||||||
|
out = append(out, part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyRootRebase rebases p -- an absolute path in the family denoted by
|
||||||
|
// pIsWindows (r.platform's *simulated* family) -- under root, when root
|
||||||
|
// is set. root is always in the REAL host's native family (e.g.
|
||||||
|
// t.TempDir()'s result, or a literal caller-chosen path), which need not
|
||||||
|
// match pIsWindows: WithRoot exists precisely to sandbox real filesystem
|
||||||
|
// I/O while a *different* platform's path logic is being simulated (see
|
||||||
|
// README's "Testing on any host"). p is decomposed into plain segments
|
||||||
|
// and re-joined onto root using root's own family -- inferred from its
|
||||||
|
// content via isWindowsPath, not from pIsWindows -- so the result is a
|
||||||
|
// single, valid, host-usable path regardless of which platform is being
|
||||||
|
// simulated. An empty root leaves p untouched.
|
||||||
|
func applyRootRebase(root, p string, pIsWindows bool) string {
|
||||||
if root == "" {
|
if root == "" {
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
_, rest, ok := splitWindowsRoot(p)
|
segments := pathSegments(p, pIsWindows)
|
||||||
if !ok {
|
elems := append([]string{root}, segments...)
|
||||||
return windowsJoin(root, p)
|
if isWindowsPath(root) {
|
||||||
|
return windowsJoin(elems...)
|
||||||
}
|
}
|
||||||
return windowsJoin(root, rest)
|
return unixJoin(elems...)
|
||||||
}
|
}
|
||||||
+53
-12
@@ -58,24 +58,46 @@ func TestSplitWindowsRoot(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyRootUnix(t *testing.T) {
|
func TestApplyRootRebaseUnix(t *testing.T) {
|
||||||
if got, want := applyRootUnix("", "/etc/yet"), "/etc/yet"; got != want {
|
if got, want := applyRootRebase("", "/etc/yet", false), "/etc/yet"; got != want {
|
||||||
t.Errorf("applyRootUnix(\"\", ...) = %q, want %q", got, want)
|
t.Errorf("applyRootRebase(\"\", ...) = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
if got, want := applyRootUnix("/tmp/root", "/etc/yet"), "/tmp/root/etc/yet"; got != want {
|
if got, want := applyRootRebase("/tmp/root", "/etc/yet", false), "/tmp/root/etc/yet"; got != want {
|
||||||
t.Errorf("applyRootUnix = %q, want %q", got, want)
|
t.Errorf("applyRootRebase = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyRootWindows(t *testing.T) {
|
func TestApplyRootRebaseWindows(t *testing.T) {
|
||||||
if got, want := applyRootWindows("", `C:\ProgramData\yet`), `C:\ProgramData\yet`; got != want {
|
if got, want := applyRootRebase("", `C:\ProgramData\yet`, true), `C:\ProgramData\yet`; got != want {
|
||||||
t.Errorf("applyRootWindows(\"\", ...) = %q, want %q", got, want)
|
t.Errorf("applyRootRebase(\"\", ...) = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
if got, want := applyRootWindows(`C:\sandbox`, `C:\ProgramData\yet`), `C:\sandbox\ProgramData\yet`; got != want {
|
if got, want := applyRootRebase(`C:\sandbox`, `C:\ProgramData\yet`, true), `C:\sandbox\ProgramData\yet`; got != want {
|
||||||
t.Errorf("applyRootWindows = %q, want %q", got, want)
|
t.Errorf("applyRootRebase = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
if got, want := applyRootWindows(`C:\sandbox`, `\\server\share\yet`), `C:\sandbox\yet`; got != want {
|
if got, want := applyRootRebase(`C:\sandbox`, `\\server\share\yet`, true), `C:\sandbox\yet`; got != want {
|
||||||
t.Errorf("applyRootWindows(UNC) = %q, want %q", got, want)
|
t.Errorf("applyRootRebase(UNC) = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyRootRebaseMismatchedFamily covers the scenario that motivated
|
||||||
|
// applyRootRebase's design: root in the REAL host's native family (e.g.
|
||||||
|
// t.TempDir()'s result on a real Windows host) combined with p in a
|
||||||
|
// *different*, simulated platform's family (see README's "Testing on
|
||||||
|
// any host"). Before this was fixed, mismatched families produced a
|
||||||
|
// mixed-separator (Unix root, Windows-native root) or doubly-drive-
|
||||||
|
// lettered (Windows root, Unix p incorrectly windows-joined) result.
|
||||||
|
func TestApplyRootRebaseMismatchedFamily(t *testing.T) {
|
||||||
|
// Windows-native root (as a real t.TempDir() would return), Unix p
|
||||||
|
// (a Linux-simulated resolver's unrooted result).
|
||||||
|
if got, want := applyRootRebase(`C:\Users\test\AppData\Local\Temp\001`, "/home/test/.config/yet", false),
|
||||||
|
`C:\Users\test\AppData\Local\Temp\001\home\test\.config\yet`; got != want {
|
||||||
|
t.Errorf("applyRootRebase(windows root, unix p) = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
// Unix-native root, Windows p (a Windows-simulated resolver's
|
||||||
|
// unrooted result) -- the mirror image, for symmetry.
|
||||||
|
if got, want := applyRootRebase("/tmp/sandbox", `C:\Users\test\AppData\Roaming\yet`, true),
|
||||||
|
"/tmp/sandbox/Users/test/AppData/Roaming/yet"; got != want {
|
||||||
|
t.Errorf("applyRootRebase(unix root, windows p) = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,3 +109,22 @@ func TestJoinDirFile(t *testing.T) {
|
|||||||
t.Errorf("JoinDirFile(windows) = %q, want %q", got, want)
|
t.Errorf("JoinDirFile(windows) = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestJoinDirFileFamily(t *testing.T) {
|
||||||
|
// dir carries its own family: content wins regardless of platform.
|
||||||
|
if got, want := JoinDirFileFamily("windows", "/etc/yet", "yet.yaml"), "/etc/yet/yet.yaml"; got != want {
|
||||||
|
t.Errorf("JoinDirFileFamily(unix dir, windows platform) = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := JoinDirFileFamily("linux", `C:\Users\test\workdir`, "yet.yaml"),
|
||||||
|
`C:\Users\test\workdir\yet.yaml`; got != want {
|
||||||
|
t.Errorf("JoinDirFileFamily(windows dir, linux platform) = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
// dir is ambiguous (no separator of its own, e.g. the default "."):
|
||||||
|
// platform decides, same as JoinFamily.
|
||||||
|
if got, want := JoinDirFileFamily("windows", ".", "yet.yaml"), `.\yet.yaml`; got != want {
|
||||||
|
t.Errorf("JoinDirFileFamily(ambiguous, windows) = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := JoinDirFileFamily("linux", ".", "yet.yaml"), "./yet.yaml"; got != want {
|
||||||
|
t.Errorf("JoinDirFileFamily(ambiguous, linux) = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-7
@@ -1,6 +1,10 @@
|
|||||||
package paths
|
package paths
|
||||||
|
|
||||||
import "yetano.dev/yetano/core"
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
)
|
||||||
|
|
||||||
// layer is one directory in a search/priority hierarchy (see
|
// layer is one directory in a search/priority hierarchy (see
|
||||||
// AGENTS.md-style docs in paths.go: "canonical path vs. search paths").
|
// AGENTS.md-style docs in paths.go: "canonical path vs. search paths").
|
||||||
@@ -40,6 +44,22 @@ func composeSearch(user, system []layer, scope core.Scope) []layer {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// skipMissingHome filters a user-tier lookup error for the search-dir
|
||||||
|
// builders (Config/Data/Executable): a missing home directory only means
|
||||||
|
// there is no user tier to search -- the working-directory and system
|
||||||
|
// tiers are still meaningful (e.g. a system service started without
|
||||||
|
// HOME whose config lives in /etc/<app>), so ErrNoHomeDirectory is
|
||||||
|
// dropped here and the caller simply omits its user layer(s). Any other
|
||||||
|
// error is returned unchanged. The canonical <Category>Dir() methods are
|
||||||
|
// unaffected and still report ErrNoHomeDirectory: a write location is
|
||||||
|
// never silently swapped for a different tier.
|
||||||
|
func skipMissingHome(err error) error {
|
||||||
|
if errors.Is(err, ErrNoHomeDirectory) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// envSuffix maps each category to the "_HOME" suffix used to build its
|
// envSuffix maps each category to the "_HOME" suffix used to build its
|
||||||
// YETANO_*/<PREFIX>_* environment variable names (e.g. ConfigPath ->
|
// YETANO_*/<PREFIX>_* environment variable names (e.g. ConfigPath ->
|
||||||
// "YETANO_CONFIG_HOME" / "YET_CONFIG_HOME").
|
// "YETANO_CONFIG_HOME" / "YET_CONFIG_HOME").
|
||||||
@@ -104,11 +124,10 @@ func (r *Resolver) join(elems ...string) string {
|
|||||||
func (r *Resolver) isWindows() bool { return r.platform == "windows" }
|
func (r *Resolver) isWindows() bool { return r.platform == "windows" }
|
||||||
func (r *Resolver) isDarwin() bool { return r.platform == "darwin" }
|
func (r *Resolver) isDarwin() bool { return r.platform == "darwin" }
|
||||||
|
|
||||||
// applyRoot rebases an absolute path under the portable root (WithRoot),
|
// applyRoot rebases an absolute path (in r.platform's simulated address
|
||||||
// if one is set, using the same address family as r.platform.
|
// family) under the portable root (WithRoot), if one is set -- see
|
||||||
|
// applyRootRebase for why root's own family, not r.platform's, decides
|
||||||
|
// the result's family.
|
||||||
func (r *Resolver) applyRoot(p string) string {
|
func (r *Resolver) applyRoot(p string) string {
|
||||||
if r.isWindows() {
|
return applyRootRebase(r.root, p, r.isWindows())
|
||||||
return applyRootWindows(r.root, p)
|
|
||||||
}
|
|
||||||
return applyRootUnix(r.root, p)
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package paths
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Without a home directory, the search-dir builders drop only the user
|
||||||
|
// tier; the system tier stays searchable, while the canonical *Dir()
|
||||||
|
// methods keep reporting ErrNoHomeDirectory.
|
||||||
|
func TestSearchDirsWithoutHome(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
platform string
|
||||||
|
app core.Application
|
||||||
|
search func(*Resolver) ([]SearchResult, error)
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"linux config", "linux", yetApp(), (*Resolver).ConfigSearchDirs, []string{"/etc/yet"}},
|
||||||
|
{"freebsd config", "freebsd", yetApp(), (*Resolver).ConfigSearchDirs, []string{"/usr/local/etc/yet"}},
|
||||||
|
{"linux data", "linux", yetApp(), (*Resolver).DataSearchDirs, []string{"/usr/local/share/yet", "/usr/share/yet"}},
|
||||||
|
{"linux bin", "linux", yetApp(), (*Resolver).ExecutableSearchDirs, []string{"/usr/local/bin"}},
|
||||||
|
{"darwin desktop config", "darwin", core.Application{Name: "Yet", Kind: core.Desktop}, (*Resolver).ConfigSearchDirs, []string{"/Library/Application Support/Yet"}},
|
||||||
|
{"windows config", "windows", yetApp(), (*Resolver).ConfigSearchDirs, []string{`C:\ProgramData\yet`}},
|
||||||
|
{"windows data", "windows", yetApp(), (*Resolver).DataSearchDirs, []string{`C:\ProgramData\yet`}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
r := mustResolver(t, tc.app, WithPlatform(tc.platform), WithEnvironment(map[string]string{}))
|
||||||
|
dirs, err := tc.search(r)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("search dirs: %v", err)
|
||||||
|
}
|
||||||
|
var got []string
|
||||||
|
for _, d := range dirs {
|
||||||
|
got = append(got, d.Path)
|
||||||
|
}
|
||||||
|
if len(got) != len(tc.want) {
|
||||||
|
t.Fatalf("search dirs = %v, want %v", got, tc.want)
|
||||||
|
}
|
||||||
|
for i := range got {
|
||||||
|
if got[i] != tc.want[i] {
|
||||||
|
t.Fatalf("search dirs = %v, want %v", got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
|
||||||
|
t.Errorf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A partially available Windows user tier (APPDATA set, LOCALAPPDATA and
|
||||||
|
// USERPROFILE unset) keeps the layers it can resolve.
|
||||||
|
func TestWindowsConfigSearchPartialUserTier(t *testing.T) {
|
||||||
|
r := mustResolver(t, yetApp(), WithPlatform("windows"),
|
||||||
|
WithEnvironment(map[string]string{"APPDATA": `C:\Users\t\AppData\Roaming`}))
|
||||||
|
dirs, err := r.ConfigSearchDirs()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ConfigSearchDirs: %v", err)
|
||||||
|
}
|
||||||
|
want := []string{`C:\Users\t\AppData\Roaming\yet`, `C:\ProgramData\yet`}
|
||||||
|
if len(dirs) != len(want) {
|
||||||
|
t.Fatalf("ConfigSearchDirs = %v, want %v", dirs, want)
|
||||||
|
}
|
||||||
|
for i, d := range dirs {
|
||||||
|
if d.Path != want[i] {
|
||||||
|
t.Fatalf("ConfigSearchDirs[%d] = %q, want %q", i, d.Path, want[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -190,3 +190,39 @@ func (r *Resolver) EnsureBinDir() (string, error) {
|
|||||||
}
|
}
|
||||||
return ensure(dir, 0o755)
|
return ensure(dir, 0o755)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EnsureLogAlias creates the optional Unix convenience symlink
|
||||||
|
// LogAliasDir() -> LogDir() (spec section 39), first ensuring LogDir()
|
||||||
|
// itself exists, and returns LogAliasDir()'s path. On Windows and macOS
|
||||||
|
// Desktop, LogAliasDir() already equals LogDir() (there is nothing to
|
||||||
|
// alias), so this is equivalent to EnsureLogDir() there.
|
||||||
|
//
|
||||||
|
// A pre-existing entry at LogAliasDir() -- file, directory, or another
|
||||||
|
// symlink -- is left untouched and reported as success: this method only
|
||||||
|
// ever creates a genuinely missing alias, never overwrites one (spec
|
||||||
|
// section 47's "no implicit destructive mutation").
|
||||||
|
func (r *Resolver) EnsureLogAlias() (string, error) {
|
||||||
|
logDir, err := r.EnsureLogDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
alias, err := r.LogAliasDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if alias == logDir {
|
||||||
|
return logDir, nil
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(alias); err == nil {
|
||||||
|
return alias, nil
|
||||||
|
} else if !os.IsNotExist(err) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dirName(alias), 0o700); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.Symlink(logDir, alias); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return alias, nil
|
||||||
|
}
|
||||||
+27
-12
@@ -23,13 +23,16 @@ type unixFlavor struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// flavor selects the unixFlavor for r.platform. darwin (in CLI/Service
|
// flavor selects the unixFlavor for r.platform. darwin (in CLI/Service
|
||||||
// kind) and any GOOS not otherwise recognized fall back to the Linux
|
// kind) uses the Linux flavor with macOS's runtime base; any GOOS not
|
||||||
// flavor as a documented, sane default -- see AGENTS.md TODO for tuning
|
// otherwise recognized falls back to the Linux flavor as a documented,
|
||||||
// individual BSDs later without a redesign.
|
// sane default -- see AGENTS.md TODO for tuning individual BSDs later
|
||||||
|
// without a redesign.
|
||||||
func (r *Resolver) flavor() unixFlavor {
|
func (r *Resolver) flavor() unixFlavor {
|
||||||
switch r.platform {
|
switch r.platform {
|
||||||
case "freebsd":
|
case "freebsd":
|
||||||
return freebsdFlavor
|
return freebsdFlavor
|
||||||
|
case "darwin":
|
||||||
|
return darwinFlavor
|
||||||
default:
|
default:
|
||||||
return linuxFlavor
|
return linuxFlavor
|
||||||
}
|
}
|
||||||
@@ -146,9 +149,12 @@ func (r *Resolver) logDirUnix() (value, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return value{}, err
|
return value{}, err
|
||||||
}
|
}
|
||||||
// stateDirUnix already applied the root; join the "log" suffix onto
|
// stateDirUnix already applied the root, so joining the "log" suffix
|
||||||
// the already-rooted path so it isn't rebased twice.
|
// must use JoinDirFile (not unixJoin) rather than rebasing again:
|
||||||
return value{path: unixJoin(state.path, "log"), source: state.source}, nil
|
// WithRoot's root can be in a different address family than this
|
||||||
|
// simulated platform (see applyRootRebase), so the already-rooted
|
||||||
|
// state.path may itself be Windows-separated even here.
|
||||||
|
return value{path: JoinDirFile(state.path, "log"), source: state.source}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// logAliasDirUnix is the optional convenience location spec section 39
|
// logAliasDirUnix is the optional convenience location spec section 39
|
||||||
@@ -183,16 +189,19 @@ func (r *Resolver) configLayersUnix() ([]layer, error) {
|
|||||||
if v, ok := r.overrideValue(ConfigPath); ok {
|
if v, ok := r.overrideValue(ConfigPath); ok {
|
||||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||||
}
|
}
|
||||||
|
var user []layer
|
||||||
userVal, err := r.xdgBase("XDG_CONFIG_HOME", ".config")
|
userVal, err := r.xdgBase("XDG_CONFIG_HOME", ".config")
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
user := []layer{{
|
if err == nil {
|
||||||
|
user = []layer{{
|
||||||
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
|
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
|
||||||
source: userVal.source,
|
source: userVal.source,
|
||||||
priority: PriorityUser,
|
priority: PriorityUser,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
}}
|
}}
|
||||||
|
}
|
||||||
system := make([]layer, len(r.flavor().systemConfigDirs))
|
system := make([]layer, len(r.flavor().systemConfigDirs))
|
||||||
for i, dir := range r.flavor().systemConfigDirs {
|
for i, dir := range r.flavor().systemConfigDirs {
|
||||||
system[i] = layer{
|
system[i] = layer{
|
||||||
@@ -209,16 +218,19 @@ func (r *Resolver) dataLayersUnix() ([]layer, error) {
|
|||||||
if v, ok := r.overrideValue(DataPath); ok {
|
if v, ok := r.overrideValue(DataPath); ok {
|
||||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||||
}
|
}
|
||||||
|
var user []layer
|
||||||
userVal, err := r.xdgBase("XDG_DATA_HOME", ".local", "share")
|
userVal, err := r.xdgBase("XDG_DATA_HOME", ".local", "share")
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
user := []layer{{
|
if err == nil {
|
||||||
|
user = []layer{{
|
||||||
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
|
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
|
||||||
source: userVal.source,
|
source: userVal.source,
|
||||||
priority: PriorityUser,
|
priority: PriorityUser,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
}}
|
}}
|
||||||
|
}
|
||||||
dirs, source := r.xdgDataDirs()
|
dirs, source := r.xdgDataDirs()
|
||||||
system := make([]layer, len(dirs))
|
system := make([]layer, len(dirs))
|
||||||
for i, dir := range dirs {
|
for i, dir := range dirs {
|
||||||
@@ -236,16 +248,19 @@ func (r *Resolver) executableLayersUnix() ([]layer, error) {
|
|||||||
if v, ok := r.overrideValue(BinPath); ok {
|
if v, ok := r.overrideValue(BinPath); ok {
|
||||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||||
}
|
}
|
||||||
|
var user []layer
|
||||||
home, err := r.homeDir()
|
home, err := r.homeDir()
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
user := []layer{{
|
if err == nil {
|
||||||
|
user = []layer{{
|
||||||
path: r.applyRoot(unixJoin(home, ".local", "bin")),
|
path: r.applyRoot(unixJoin(home, ".local", "bin")),
|
||||||
source: PlatformDefault,
|
source: PlatformDefault,
|
||||||
priority: PriorityUser,
|
priority: PriorityUser,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
}}
|
}}
|
||||||
|
}
|
||||||
system := []layer{{
|
system := []layer{{
|
||||||
path: r.applyRoot(r.flavor().systemBinDir),
|
path: r.applyRoot(r.flavor().systemBinDir),
|
||||||
source: SystemDirectory,
|
source: SystemDirectory,
|
||||||
|
|||||||
+16
-6
@@ -128,9 +128,10 @@ func (r *Resolver) configLayersWindows() ([]layer, error) {
|
|||||||
var user []layer
|
var user []layer
|
||||||
if r.app.Kind != core.Desktop {
|
if r.app.Kind != core.Desktop {
|
||||||
local, err := r.windowsBase("LOCALAPPDATA")
|
local, err := r.windowsBase("LOCALAPPDATA")
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err == nil {
|
||||||
user = append(user, layer{
|
user = append(user, layer{
|
||||||
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
|
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
|
||||||
source: local.source,
|
source: local.source,
|
||||||
@@ -138,16 +139,19 @@ func (r *Resolver) configLayersWindows() ([]layer, error) {
|
|||||||
canonical: false,
|
canonical: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
}
|
||||||
roaming, err := r.windowsBase("APPDATA")
|
roaming, err := r.windowsBase("APPDATA")
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err == nil {
|
||||||
user = append(user, layer{
|
user = append(user, layer{
|
||||||
path: r.applyRoot(windowsJoin(roaming.path, r.app.Name)),
|
path: r.applyRoot(windowsJoin(roaming.path, r.app.Name)),
|
||||||
source: roaming.source,
|
source: roaming.source,
|
||||||
priority: PriorityUser,
|
priority: PriorityUser,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
})
|
})
|
||||||
|
}
|
||||||
system, err := r.windowsSystemLayer(r.app.Name)
|
system, err := r.windowsSystemLayer(r.app.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -161,16 +165,19 @@ func (r *Resolver) dataLayersWindows() ([]layer, error) {
|
|||||||
if v, ok := r.overrideValue(DataPath); ok {
|
if v, ok := r.overrideValue(DataPath); ok {
|
||||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||||
}
|
}
|
||||||
|
var user []layer
|
||||||
local, err := r.windowsBase("LOCALAPPDATA")
|
local, err := r.windowsBase("LOCALAPPDATA")
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
user := []layer{{
|
if err == nil {
|
||||||
|
user = []layer{{
|
||||||
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
|
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
|
||||||
source: local.source,
|
source: local.source,
|
||||||
priority: PriorityUserLocal,
|
priority: PriorityUserLocal,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
}}
|
}}
|
||||||
|
}
|
||||||
system, err := r.windowsSystemLayer(r.app.Name)
|
system, err := r.windowsSystemLayer(r.app.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -182,16 +189,19 @@ func (r *Resolver) executableLayersWindows() ([]layer, error) {
|
|||||||
if v, ok := r.overrideValue(BinPath); ok {
|
if v, ok := r.overrideValue(BinPath); ok {
|
||||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||||
}
|
}
|
||||||
|
var user []layer
|
||||||
local, err := r.windowsBase("LOCALAPPDATA")
|
local, err := r.windowsBase("LOCALAPPDATA")
|
||||||
if err != nil {
|
if err := skipMissingHome(err); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
user := []layer{{
|
if err == nil {
|
||||||
|
user = []layer{{
|
||||||
path: r.applyRoot(windowsJoin(local.path, "Yetano", "bin")),
|
path: r.applyRoot(windowsJoin(local.path, "Yetano", "bin")),
|
||||||
source: local.source,
|
source: local.source,
|
||||||
priority: PriorityUserLocal,
|
priority: PriorityUserLocal,
|
||||||
canonical: true,
|
canonical: true,
|
||||||
}}
|
}}
|
||||||
|
}
|
||||||
system, err := r.windowsSystemLayer("Yetano", "bin")
|
system, err := r.windowsSystemLayer("Yetano", "bin")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -164,12 +164,35 @@ func TestWindowsDesktopSimplerLayering(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestWindowsMissingHomeIsCleanError(t *testing.T) {
|
func TestWindowsMissingHomeIsCleanError(t *testing.T) {
|
||||||
|
// windowsBase's native SHGetKnownFolderPath fallback (see
|
||||||
|
// knownfolders_windows.go) is only consulted when actually running
|
||||||
|
// on a real Windows host (runtime.GOOS == "windows"), regardless of
|
||||||
|
// WithPlatform -- deliberately, so it reflects genuine behavior
|
||||||
|
// there instead of firing under simulation. That means this specific
|
||||||
|
// scenario (empty environment, no override) resolves a *real*
|
||||||
|
// known-folder path on an actual Windows host instead of erroring,
|
||||||
|
// which is correct, intended behavior, not a bug -- but it makes
|
||||||
|
// this test non-deterministic across hosts. Disable the native
|
||||||
|
// fallback here so the "no override, no env, no fallback available"
|
||||||
|
// path is exercised deterministically on every host, including real
|
||||||
|
// Windows (see the Windows-verification note in TODO.md).
|
||||||
|
withoutNativeKnownFolder(t)
|
||||||
|
|
||||||
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(map[string]string{}))
|
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(map[string]string{}))
|
||||||
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
|
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
|
||||||
t.Fatalf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
|
t.Fatalf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// withoutNativeKnownFolder disables nativeKnownFolder for the duration
|
||||||
|
// of t, restoring its previous value afterwards.
|
||||||
|
func withoutNativeKnownFolder(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
prev := nativeKnownFolder
|
||||||
|
nativeKnownFolder = nil
|
||||||
|
t.Cleanup(func() { nativeKnownFolder = prev })
|
||||||
|
}
|
||||||
|
|
||||||
func TestWindowsAPIOverride(t *testing.T) {
|
func TestWindowsAPIOverride(t *testing.T) {
|
||||||
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithConfigDir(`D:\portable\yet-config`))
|
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithConfigDir(`D:\portable\yet-config`))
|
||||||
got, err := r.ConfigDir()
|
got, err := r.ConfigDir()
|
||||||
|
|||||||
@@ -0,0 +1,257 @@
|
|||||||
|
// Package secretref resolves secret references in Yetano program
|
||||||
|
// configurations, so a token, password or key never has to be written
|
||||||
|
// into a config file in plain text:
|
||||||
|
//
|
||||||
|
// secret://<name> resolved through yaseva (`yaseva get <name>`)
|
||||||
|
// env:<VARIABLE> read from the process environment
|
||||||
|
// file:<path> read from a local file (~ expanded, trailing newline trimmed)
|
||||||
|
// base64:<value> the value itself, base64-encoded (standard or URL alphabet,
|
||||||
|
// padding optional): kept out of plain sight, but not protected
|
||||||
|
//
|
||||||
|
// yaseva is called as a subprocess on purpose: a program never opens
|
||||||
|
// the vault itself, does not need yaseva's Go toolchain requirements,
|
||||||
|
// and works with however the operator has configured/unlocked yaseva.
|
||||||
|
//
|
||||||
|
// Validate accepts only these forms. A program that must keep reading
|
||||||
|
// plain values it accepted before (e.g. yacry's provider_config) checks
|
||||||
|
// IsReference first and treats everything else as a literal.
|
||||||
|
//
|
||||||
|
// Every resolved value is registered with the Resolver's redactor so it
|
||||||
|
// can be scrubbed from errors, logs and reports.
|
||||||
|
package secretref
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInvalid is returned for a reference that is not one of the
|
||||||
|
// supported forms (including any plaintext value).
|
||||||
|
var ErrInvalid = errors.New("invalid secret reference")
|
||||||
|
|
||||||
|
// prefixes are the reference forms, in the order IsReference checks them.
|
||||||
|
var prefixes = []string{"secret://", "env:", "file:", "base64:"}
|
||||||
|
|
||||||
|
// IsReference reports whether s uses one of the reference forms
|
||||||
|
// (secret://, env:, file:, base64:), valid or not. Anything else is a
|
||||||
|
// literal value.
|
||||||
|
func IsReference(s string) bool {
|
||||||
|
for _, p := range prefixes {
|
||||||
|
if strings.HasPrefix(s, p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate checks that ref is a supported reference form. The empty
|
||||||
|
// string is valid and means "not set".
|
||||||
|
func Validate(ref string) error {
|
||||||
|
switch {
|
||||||
|
case ref == "":
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "secret://"):
|
||||||
|
name := strings.TrimPrefix(ref, "secret://")
|
||||||
|
if name == "" || strings.ContainsAny(name, " \t\r\n") || strings.HasPrefix(name, "-") {
|
||||||
|
return fmt.Errorf("%w: %q: empty or malformed secret name", ErrInvalid, ref)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "env:"):
|
||||||
|
if strings.TrimPrefix(ref, "env:") == "" {
|
||||||
|
return fmt.Errorf("%w: %q: empty variable name", ErrInvalid, ref)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "file:"):
|
||||||
|
if strings.TrimPrefix(ref, "file:") == "" {
|
||||||
|
return fmt.Errorf("%w: %q: empty path", ErrInvalid, ref)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "base64:"):
|
||||||
|
// The value is not repeated in the error: it is the secret.
|
||||||
|
if v, err := decodeBase64(strings.TrimPrefix(ref, "base64:")); err != nil || len(v) == 0 {
|
||||||
|
return fmt.Errorf("%w: base64: value is empty or not valid base64", ErrInvalid)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%w: plaintext secrets are not allowed; use secret://<name>, env:<VAR>, file:<path> or base64:<value>", ErrInvalid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolver resolves references. The zero value is not usable; use New.
|
||||||
|
type Resolver struct {
|
||||||
|
// YasevaBinary is the yaseva executable for secret:// references.
|
||||||
|
YasevaBinary string
|
||||||
|
// YasevaConfig, if set, is passed to yaseva as --config (default:
|
||||||
|
// yaseva's own config search, including $YASEVA_CONFIG).
|
||||||
|
YasevaConfig string
|
||||||
|
// Timeout bounds one yaseva call.
|
||||||
|
Timeout time.Duration
|
||||||
|
|
||||||
|
// Hooks for tests.
|
||||||
|
LookupEnv func(string) (string, bool)
|
||||||
|
ReadFile func(string) ([]byte, error)
|
||||||
|
Run func(ctx context.Context, bin string, args ...string) (stdout []byte, err error)
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
cache map[string][]byte
|
||||||
|
secrets [][]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a Resolver using yasevaBinary ("yaseva" if empty).
|
||||||
|
func New(yasevaBinary string) *Resolver {
|
||||||
|
if yasevaBinary == "" {
|
||||||
|
yasevaBinary = "yaseva"
|
||||||
|
}
|
||||||
|
return &Resolver{
|
||||||
|
YasevaBinary: yasevaBinary,
|
||||||
|
Timeout: 30 * time.Second,
|
||||||
|
LookupEnv: os.LookupEnv,
|
||||||
|
ReadFile: os.ReadFile,
|
||||||
|
Run: runCommand,
|
||||||
|
cache: map[string][]byte{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCommand(ctx context.Context, bin string, args ...string) ([]byte, error) {
|
||||||
|
cmd := exec.CommandContext(ctx, bin, args...)
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
msg := strings.TrimSpace(stderr.String())
|
||||||
|
if len(msg) > 200 {
|
||||||
|
msg = msg[:200]
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%s: %w: %s", bin, err, msg)
|
||||||
|
}
|
||||||
|
return stdout.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveString is Resolve for callers that want a string.
|
||||||
|
func (r *Resolver) ResolveString(ctx context.Context, ref string) (string, error) {
|
||||||
|
v, err := r.Resolve(ctx, ref)
|
||||||
|
return string(v), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve returns the secret value for ref. Results are cached for the
|
||||||
|
// lifetime of the Resolver so yaseva is asked at most once per name.
|
||||||
|
func (r *Resolver) Resolve(ctx context.Context, ref string) ([]byte, error) {
|
||||||
|
if err := Validate(ref); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ref == "" {
|
||||||
|
return nil, fmt.Errorf("%w: empty reference", ErrInvalid)
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
if v, ok := r.cache[ref]; ok {
|
||||||
|
r.mu.Unlock()
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
r.mu.Unlock()
|
||||||
|
|
||||||
|
var v []byte
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(ref, "secret://"):
|
||||||
|
cctx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
args := []string{"get", strings.TrimPrefix(ref, "secret://")}
|
||||||
|
if r.YasevaConfig != "" {
|
||||||
|
args = append([]string{"--config", r.YasevaConfig}, args...)
|
||||||
|
}
|
||||||
|
out, err := r.Run(cctx, r.YasevaBinary, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve %s: %w", ref, err)
|
||||||
|
}
|
||||||
|
v = trimNewline(out)
|
||||||
|
case strings.HasPrefix(ref, "env:"):
|
||||||
|
name := strings.TrimPrefix(ref, "env:")
|
||||||
|
s, ok := r.LookupEnv(name)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("resolve %s: environment variable not set", ref)
|
||||||
|
}
|
||||||
|
v = []byte(s)
|
||||||
|
case strings.HasPrefix(ref, "file:"):
|
||||||
|
p, err := ExpandHome(strings.TrimPrefix(ref, "file:"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b, err := r.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve %s: %w", ref, err)
|
||||||
|
}
|
||||||
|
v = trimNewline(b)
|
||||||
|
case strings.HasPrefix(ref, "base64:"):
|
||||||
|
v, _ = decodeBase64(strings.TrimPrefix(ref, "base64:")) // checked by Validate
|
||||||
|
}
|
||||||
|
if len(v) == 0 {
|
||||||
|
return nil, fmt.Errorf("resolve %s: empty secret", ref)
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.cache[ref] = v
|
||||||
|
if len(v) >= 4 {
|
||||||
|
r.secrets = append(r.secrets, v)
|
||||||
|
}
|
||||||
|
r.mu.Unlock()
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddSecret registers a value obtained elsewhere (e.g. a Verse
|
||||||
|
// invitation token) so Redact removes it from errors and reports.
|
||||||
|
func (r *Resolver) AddSecret(v string) {
|
||||||
|
if r == nil || len(v) < 4 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.secrets = append(r.secrets, []byte(v))
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redact replaces every secret value resolved so far with "***".
|
||||||
|
// Secrets shorter than 4 bytes are not registered (they would redact
|
||||||
|
// ordinary text); such secrets are weak anyway.
|
||||||
|
func (r *Resolver) Redact(s string) string {
|
||||||
|
if r == nil {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
for _, v := range r.secrets {
|
||||||
|
s = strings.ReplaceAll(s, string(v), "***")
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeBase64 accepts the standard and the URL alphabet, with or
|
||||||
|
// without padding.
|
||||||
|
func decodeBase64(s string) ([]byte, error) {
|
||||||
|
s = strings.TrimRight(strings.TrimSpace(s), "=")
|
||||||
|
if strings.ContainsAny(s, "-_") {
|
||||||
|
return base64.RawURLEncoding.DecodeString(s)
|
||||||
|
}
|
||||||
|
return base64.RawStdEncoding.DecodeString(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func trimNewline(b []byte) []byte {
|
||||||
|
b = bytes.TrimRight(b, "\r\n")
|
||||||
|
return bytes.Clone(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExpandHome expands a leading "~" or "~/" to the user's home directory.
|
||||||
|
func ExpandHome(p string) (string, error) {
|
||||||
|
if p == "~" || strings.HasPrefix(p, "~/") || strings.HasPrefix(p, `~\`) {
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(home, p[1:]), nil
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package secretref
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidate(t *testing.T) {
|
||||||
|
for _, ok := range []string{"", "secret://app/admin", "env:ADMIN_PW", "file:~/pw.txt", "base64:aHVudGVyMg==", "base64:aHVudGVyMg"} {
|
||||||
|
if err := Validate(ok); err != nil {
|
||||||
|
t.Errorf("%q: %v", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"hunter2", "secret://", "secret://a b", "secret://-flag", "env:", "file:", "SECRET://x", "base64:", "base64:!!", "base64:="} {
|
||||||
|
if err := Validate(bad); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Errorf("%q accepted", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolve(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
r := New("yaseva-test")
|
||||||
|
r.Run = func(_ context.Context, bin string, args ...string) ([]byte, error) {
|
||||||
|
calls++
|
||||||
|
if bin != "yaseva-test" || len(args) != 2 || args[0] != "get" || args[1] != "app/admin" {
|
||||||
|
t.Fatalf("unexpected call %s %v", bin, args)
|
||||||
|
}
|
||||||
|
return []byte("s3cr3t-pass\n"), nil
|
||||||
|
}
|
||||||
|
r.LookupEnv = func(k string) (string, bool) { return "from-env", k == "PW" }
|
||||||
|
dir := t.TempDir()
|
||||||
|
f := filepath.Join(dir, "pw")
|
||||||
|
if err := os.WriteFile(f, []byte("from-file\r\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
v, err := r.Resolve(ctx, "secret://app/admin")
|
||||||
|
if err != nil || string(v) != "s3cr3t-pass" {
|
||||||
|
t.Fatalf("secret: %q %v", v, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("yaseva called %d times, want 1 (cached)", calls)
|
||||||
|
}
|
||||||
|
if v, err := r.Resolve(ctx, "env:PW"); err != nil || string(v) != "from-env" {
|
||||||
|
t.Fatalf("env: %q %v", v, err)
|
||||||
|
}
|
||||||
|
if _, err := r.Resolve(ctx, "env:MISSING"); err == nil {
|
||||||
|
t.Fatal("missing env accepted")
|
||||||
|
}
|
||||||
|
if v, err := r.Resolve(ctx, "file:"+f); err != nil || string(v) != "from-file" {
|
||||||
|
t.Fatalf("file: %q %v", v, err)
|
||||||
|
}
|
||||||
|
if _, err := r.Resolve(ctx, "plaintext"); err == nil {
|
||||||
|
t.Fatal("plaintext resolved")
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := r.Redact("login failed with s3cr3t-pass and from-file")
|
||||||
|
if strings.Contains(msg, "s3cr3t-pass") || strings.Contains(msg, "from-file") {
|
||||||
|
t.Fatalf("not redacted: %s", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveEmptySecret(t *testing.T) {
|
||||||
|
r := New("")
|
||||||
|
r.Run = func(context.Context, string, ...string) ([]byte, error) { return []byte("\n"), nil }
|
||||||
|
if _, err := r.Resolve(context.Background(), "secret://x"); err == nil {
|
||||||
|
t.Fatal("empty secret accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveBase64(t *testing.T) {
|
||||||
|
r := New("")
|
||||||
|
for ref, want := range map[string]string{
|
||||||
|
"base64:aHVudGVyMg==": "hunter2",
|
||||||
|
"base64:aHVudGVyMg": "hunter2",
|
||||||
|
"base64:Pz8_Pw": "????", // URL alphabet
|
||||||
|
"base64:Pz8/Pw==": "????",
|
||||||
|
} {
|
||||||
|
v, err := r.Resolve(context.Background(), ref)
|
||||||
|
if err != nil || string(v) != want {
|
||||||
|
t.Errorf("%s: %q %v, want %q", ref, v, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if msg := r.Redact("pw hunter2"); strings.Contains(msg, "hunter2") {
|
||||||
|
t.Fatalf("not redacted: %s", msg)
|
||||||
|
}
|
||||||
|
if err := Validate("base64:!!"); err != nil && strings.Contains(err.Error(), "!!") {
|
||||||
|
t.Fatalf("error repeats the value: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsReference(t *testing.T) {
|
||||||
|
for s, want := range map[string]bool{
|
||||||
|
"secret://x": true, "env:X": true, "file:/x": true, "base64:eA==": true,
|
||||||
|
"plain-token": false, "": false, "SECRET://x": false, "envX": false,
|
||||||
|
} {
|
||||||
|
if got := IsReference(s); got != want {
|
||||||
|
t.Errorf("IsReference(%q) = %v, want %v", s, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestYasevaConfigIsPassed(t *testing.T) {
|
||||||
|
r := New("yaseva")
|
||||||
|
r.YasevaConfig = "/etc/yaseva.yaml"
|
||||||
|
var got []string
|
||||||
|
r.Run = func(_ context.Context, bin string, args ...string) ([]byte, error) {
|
||||||
|
got = append([]string{bin}, args...)
|
||||||
|
return []byte("tok\n"), nil
|
||||||
|
}
|
||||||
|
v, err := r.ResolveString(context.Background(), "secret://dns/httpnet")
|
||||||
|
if err != nil || v != "tok" {
|
||||||
|
t.Fatalf("ResolveString = %q, %v", v, err)
|
||||||
|
}
|
||||||
|
want := []string{"yaseva", "--config", "/etc/yaseva.yaml", "get", "dns/httpnet"}
|
||||||
|
if strings.Join(got, " ") != strings.Join(want, " ") {
|
||||||
|
t.Errorf("ran %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
// Package version is the shared "<program> version [--json]" command of
|
||||||
|
// the Yetano program standard (docs/program-conventions.md in the yetano
|
||||||
|
// meta-repository).
|
||||||
|
//
|
||||||
|
// The values themselves stay in each program's internal/version package,
|
||||||
|
// stamped at link time with -ldflags -X (see AGENTS.md "Versioning": the
|
||||||
|
// version is "git describe --tags --always --dirty" without the tag's
|
||||||
|
// "v"); the program hands them over:
|
||||||
|
//
|
||||||
|
// case "version":
|
||||||
|
// os.Exit(coreversion.Info{
|
||||||
|
// Program: "yasl",
|
||||||
|
// Version: version.Version,
|
||||||
|
// Commit: version.Commit,
|
||||||
|
// BuildDate: version.BuildDate,
|
||||||
|
// }.Run(args[1:], os.Stdout, os.Stderr))
|
||||||
|
//
|
||||||
|
// Output:
|
||||||
|
//
|
||||||
|
// yasl version 0.2.0
|
||||||
|
// commit: abc1234
|
||||||
|
// built: 2026-10-23T10:00:00Z
|
||||||
|
// go: go1.26.3 darwin/arm64
|
||||||
|
//
|
||||||
|
// and with --json one object (contracts only for Verse programs, see
|
||||||
|
// ADR-0012):
|
||||||
|
//
|
||||||
|
// {"program":"yasl","version":"0.2.0","commit":"abc1234",
|
||||||
|
// "build_date":"2026-10-23T10:00:00Z","go":"go1.26.3","platform":"darwin/arm64"}
|
||||||
|
package version
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"runtime"
|
||||||
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes of Run, matching core/doctor's.
|
||||||
|
const (
|
||||||
|
ExitOK = 0
|
||||||
|
ExitUsage = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// Info is one program's build metadata. Empty or "unknown" Commit and
|
||||||
|
// BuildDate fall back to the VCS data Go embeds (go build in a git
|
||||||
|
// checkout, go install), so even an unstamped build says what it is.
|
||||||
|
type Info struct {
|
||||||
|
Program string `json:"program"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
Commit string `json:"commit"`
|
||||||
|
BuildDate string `json:"build_date"`
|
||||||
|
Go string `json:"go"`
|
||||||
|
Platform string `json:"platform"`
|
||||||
|
// Contracts lists the wire contract majors a Verse program speaks,
|
||||||
|
// by contract name (ADR-0012 §4, verse compatibility.md §4).
|
||||||
|
Contracts map[string][]int `json:"contracts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// readBuildInfo is replaced in tests.
|
||||||
|
var readBuildInfo = debug.ReadBuildInfo
|
||||||
|
|
||||||
|
// Complete fills in what the program did not stamp: Go version,
|
||||||
|
// platform, the VCS revision and time, and "dev" for an empty Version.
|
||||||
|
// A leading "v" on a stamped tag version is dropped (only git tags
|
||||||
|
// carry one).
|
||||||
|
func (i Info) Complete() Info {
|
||||||
|
if i.Go == "" {
|
||||||
|
i.Go = runtime.Version()
|
||||||
|
}
|
||||||
|
if i.Platform == "" {
|
||||||
|
i.Platform = runtime.GOOS + "/" + runtime.GOARCH
|
||||||
|
}
|
||||||
|
if len(i.Version) > 1 && i.Version[0] == 'v' && i.Version[1] >= '0' && i.Version[1] <= '9' {
|
||||||
|
i.Version = i.Version[1:]
|
||||||
|
}
|
||||||
|
if i.Version == "" {
|
||||||
|
i.Version = "dev"
|
||||||
|
}
|
||||||
|
unknown := func(s string) bool { return s == "" || s == "unknown" }
|
||||||
|
if unknown(i.Commit) || unknown(i.BuildDate) {
|
||||||
|
if bi, ok := readBuildInfo(); ok {
|
||||||
|
var rev, at, modified string
|
||||||
|
for _, s := range bi.Settings {
|
||||||
|
switch s.Key {
|
||||||
|
case "vcs.revision":
|
||||||
|
rev = s.Value
|
||||||
|
case "vcs.time":
|
||||||
|
at = s.Value
|
||||||
|
case "vcs.modified":
|
||||||
|
modified = s.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if unknown(i.Commit) && rev != "" {
|
||||||
|
i.Commit = rev[:min(len(rev), 7)]
|
||||||
|
if modified == "true" {
|
||||||
|
i.Commit += "-dirty"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if unknown(i.BuildDate) && at != "" {
|
||||||
|
i.BuildDate = at
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i.Commit == "" {
|
||||||
|
i.Commit = "unknown"
|
||||||
|
}
|
||||||
|
if i.BuildDate == "" {
|
||||||
|
i.BuildDate = "unknown"
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
// String is the human-readable form "version" prints.
|
||||||
|
func (i Info) String() string {
|
||||||
|
i = i.Complete()
|
||||||
|
return fmt.Sprintf("%s version %s\ncommit: %s\nbuilt: %s\ngo: %s %s", i.Program, i.Version, i.Commit, i.BuildDate, i.Go, i.Platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Short is the one-line form for log lines and web UI footers:
|
||||||
|
// "0.2.0 (abc1234, built 2026-10-23T10:00:00Z)".
|
||||||
|
func (i Info) Short() string {
|
||||||
|
i = i.Complete()
|
||||||
|
return fmt.Sprintf("%s (%s, built %s)", i.Version, i.Commit, i.BuildDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run serves "<program> version [--json]" and returns the exit code.
|
||||||
|
func (i Info) Run(args []string, stdout, stderr io.Writer) int {
|
||||||
|
asJSON := false
|
||||||
|
for _, a := range args {
|
||||||
|
switch a {
|
||||||
|
case "--json", "-json":
|
||||||
|
asJSON = true
|
||||||
|
case "-h", "--help", "-help", "help":
|
||||||
|
fmt.Fprintf(stdout, "usage: %s version [--json]\n", i.Program)
|
||||||
|
return ExitOK
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "%s version: unexpected argument %q\nusage: %s version [--json]\n", i.Program, a, i.Program)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if asJSON {
|
||||||
|
enc := json.NewEncoder(stdout)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
_ = enc.Encode(i.Complete())
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, strings.TrimRight(i.String(), "\n"))
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package version
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func run(t *testing.T, i Info, args ...string) (int, string, string) {
|
||||||
|
t.Helper()
|
||||||
|
var out, errOut bytes.Buffer
|
||||||
|
code := i.Run(args, &out, &errOut)
|
||||||
|
return code, out.String(), errOut.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func noBuildInfo(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
old := readBuildInfo
|
||||||
|
readBuildInfo = func() (*debug.BuildInfo, bool) { return nil, false }
|
||||||
|
t.Cleanup(func() { readBuildInfo = old })
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestText(t *testing.T) {
|
||||||
|
noBuildInfo(t)
|
||||||
|
code, out, _ := run(t, Info{Program: "yatool", Version: "0.2.0", Commit: "abc1234", BuildDate: "2026-10-23T10:00:00Z"})
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("code %d", code)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"yatool version 0.2.0\n", "commit: abc1234\n", "built: 2026-10-23T10:00:00Z\n", "go: go"} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("output %q lacks %q", out, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestJSON(t *testing.T) {
|
||||||
|
noBuildInfo(t)
|
||||||
|
i := Info{Program: "yasta", Version: "v0.11.1", Commit: "eb3675a", BuildDate: "x",
|
||||||
|
Contracts: map[string][]int{"envelope": {1}, "session": {1, 2}}}
|
||||||
|
code, out, _ := run(t, i, "--json")
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("code %d", code)
|
||||||
|
}
|
||||||
|
var got map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(out), &got); err != nil {
|
||||||
|
t.Fatalf("%v: %s", err, out)
|
||||||
|
}
|
||||||
|
// The keys yavebu and others already read from yasta's output.
|
||||||
|
for _, k := range []string{"program", "version", "commit", "build_date", "go", "platform", "contracts"} {
|
||||||
|
if _, ok := got[k]; !ok {
|
||||||
|
t.Errorf("missing key %q in %s", k, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got["version"] != "0.11.1" {
|
||||||
|
t.Errorf("version %v, want the leading v dropped", got["version"])
|
||||||
|
}
|
||||||
|
if code, out, _ = run(t, Info{Program: "x"}, "--json"); code != ExitOK || strings.Contains(out, "contracts") {
|
||||||
|
t.Errorf("contracts must be omitted when empty: %s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultsAndBuildInfoFallback(t *testing.T) {
|
||||||
|
old := readBuildInfo
|
||||||
|
readBuildInfo = func() (*debug.BuildInfo, bool) {
|
||||||
|
return &debug.BuildInfo{Settings: []debug.BuildSetting{
|
||||||
|
{Key: "vcs.revision", Value: "0123456789abcdef"},
|
||||||
|
{Key: "vcs.time", Value: "2026-10-01T00:00:00Z"},
|
||||||
|
{Key: "vcs.modified", Value: "true"},
|
||||||
|
}}, true
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { readBuildInfo = old })
|
||||||
|
i := Info{Program: "x", Commit: "unknown"}.Complete()
|
||||||
|
if i.Version != "dev" || i.Commit != "0123456-dirty" || i.BuildDate != "2026-10-01T00:00:00Z" {
|
||||||
|
t.Errorf("got %+v", i)
|
||||||
|
}
|
||||||
|
if v := (Info{Version: "version-x"}).Complete().Version; v != "version-x" {
|
||||||
|
t.Errorf("a non-tag v must stay: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUsage(t *testing.T) {
|
||||||
|
noBuildInfo(t)
|
||||||
|
if code, _, errOut := run(t, Info{Program: "x"}, "--yaml"); code != ExitUsage || errOut == "" {
|
||||||
|
t.Errorf("unknown flag: code %d, err %q", code, errOut)
|
||||||
|
}
|
||||||
|
if code, out, _ := run(t, Info{Program: "x"}, "--help"); code != ExitOK || !strings.Contains(out, "usage") {
|
||||||
|
t.Errorf("--help: code %d, out %q", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShort(t *testing.T) {
|
||||||
|
noBuildInfo(t)
|
||||||
|
if s := (Info{Version: "0.1.0", Commit: "c", BuildDate: "d"}).Short(); s != "0.1.0 (c, built d)" {
|
||||||
|
t.Errorf("Short %q", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user