Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e757fdd025 | ||
|
|
e8bf23a064 | ||
|
|
72b656262d | ||
|
|
da2ec85381 | ||
|
|
e6b5324ad3 | ||
|
|
689469eb32 |
No files matched your search
@@ -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
|
||||
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
|
||||
|
||||
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()`
|
||||
always succeeds on those platforms.
|
||||
|
||||
## macOS Desktop RuntimeDir: $TMPDIR, not a persistent placeholder
|
||||
|
||||
Unlike Unix's XDG_RUNTIME_DIR, macOS has no documented per-app ephemeral
|
||||
runtime directory convention -- but it does hand every process a real
|
||||
equivalent: `$TMPDIR`, the per-user, securely permissioned (`0700`),
|
||||
OS-managed directory `confstr(_CS_DARWIN_USER_TEMP_DIR)` resolves and
|
||||
`NSTemporaryDirectory()` returns. `darwinDesktopRuntimeDir()` prefers it
|
||||
(joined with the app name) over the previous placeholder,
|
||||
`~/Library/Application Support/<App>/Runtime` -- a persistent directory
|
||||
that misrepresented "ephemeral" -- falling back to that placeholder only
|
||||
when `TMPDIR` is absent from the resolved environment (a
|
||||
simulated/test environment that never set it; a real macOS process
|
||||
always has it set).
|
||||
|
||||
## LogAliasDir is resolved separately from being created
|
||||
|
||||
`LogAliasDir()` (the optional `~/.local/log/<app>` convenience symlink
|
||||
target, spec section 39) stays a pure computation like every other
|
||||
`*Dir()` method -- resolving it never touches the filesystem. Creating
|
||||
the actual symlink is `EnsureLogAlias()`'s job, kept separate and
|
||||
explicit for the same reason every other `Ensure*` method is separate
|
||||
from its `*Dir()` counterpart (see "No implicit filesystem mutation" in
|
||||
the package doc comment): a caller that only wants to know the path
|
||||
(e.g. to show it in `doctor`/`Explain` output) should never risk
|
||||
creating a symlink as a side effect.
|
||||
|
||||
## Unix system-scope directories follow each OS's own convention
|
||||
|
||||
Linux SystemScope uses the FHS layout (`/etc`, `/var/lib`, `/var/cache`,
|
||||
|
||||
@@ -13,6 +13,7 @@ configuration resolution**: `core/paths` and `core/config`.
|
||||
yetano.dev/yetano/core
|
||||
yetano.dev/yetano/core/paths
|
||||
yetano.dev/yetano/core/config
|
||||
yetano.dev/yetano/core/manual
|
||||
```
|
||||
|
||||
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||
@@ -59,6 +60,13 @@ write location) and, for Config/Data/executables,
|
||||
search, highest priority first). These are not always the same
|
||||
location -- see "Windows" below.
|
||||
|
||||
Without a home directory (`HOME`/`USERPROFILE` unset, and no override
|
||||
for the user tier), the search lists simply omit the user tier and still
|
||||
report the system tier -- a system service started without `HOME` keeps
|
||||
finding `/etc/<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
|
||||
|
||||
Every canonical category is resolved through the same chain, highest
|
||||
@@ -108,6 +116,7 @@ native GUI app) uses `~/Library/...`:
|
||||
~/Library/Application Support/<App>/State
|
||||
~/Library/Caches/<App>
|
||||
~/Library/Logs/<App>
|
||||
$TMPDIR/<App> (Runtime -- see below)
|
||||
```
|
||||
|
||||
### Windows
|
||||
@@ -138,7 +147,18 @@ machine-local override layer. Data/State/Cache/Log/Runtime live under
|
||||
Unix, without an explicit override and without `XDG_RUNTIME_DIR` set, it
|
||||
returns `paths.ErrRuntimeDirUnavailable` -- callers decide what to do.
|
||||
Windows and macOS always resolve a runtime directory (no equivalent
|
||||
"may legitimately not exist" case there).
|
||||
"may legitimately not exist" case there); macOS Desktop resolves it from
|
||||
`$TMPDIR` (see ARCHITECTURE.md), the same OS-managed ephemeral directory
|
||||
`NSTemporaryDirectory()` returns.
|
||||
|
||||
### LogAliasDir
|
||||
|
||||
`LogAliasDir()` resolves the optional Unix convenience symlink target
|
||||
`~/.local/log/<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
|
||||
|
||||
@@ -155,10 +175,19 @@ existence/permission checks.
|
||||
Every platform code path is a plain function of an injectable
|
||||
`Environment` (env vars) and an injectable platform string
|
||||
(`paths.WithPlatform("windows")`), not `runtime.GOOS`/`os.Getenv`
|
||||
directly -- see ARCHITECTURE.md's "Platform simulation" section for why,
|
||||
directly -- see ARCHITECTURE.md's "Platform strategy" section for why,
|
||||
and the package's own tests for how Windows/macOS/FreeBSD path logic is
|
||||
verified while running on any host.
|
||||
|
||||
Combine `WithPlatform` with `WithRoot(t.TempDir())` to also sandbox real
|
||||
filesystem I/O (`Ensure*`, `FindFile`, `Explain`) while simulating a
|
||||
different platform's path *logic* than the host actually running the
|
||||
test. `root` there is always in the real host's native address family
|
||||
(whatever `t.TempDir()` returns), which need not match the simulated
|
||||
platform's family -- `WithRoot` handles that mismatch correctly (see
|
||||
ARCHITECTURE.md's "WithRoot: root's family is the real host's"), so the
|
||||
combination is always safe to use.
|
||||
|
||||
## core/config: finding and layering configuration files
|
||||
|
||||
```go
|
||||
@@ -216,6 +245,29 @@ ecosystem-wide, shared settings (`repositories.yaml`, `trust.yaml`,
|
||||
layered into, any one application's own configuration. An application
|
||||
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).
|
||||
|
||||
## Security
|
||||
|
||||
- Environment expansion is variable substitution only -- never shell
|
||||
|
||||
@@ -6,41 +6,53 @@ speculatively.
|
||||
|
||||
## Migration
|
||||
|
||||
- **Migrate `yet` onto `core/paths`/`core/config`.** `yet`'s
|
||||
`internal/store.Home()` (`$YETANO_HOME`, defaulting to
|
||||
`os.UserConfigDir()/yetano`) and `internal/config` (fixed
|
||||
`/etc/yetano/yetano.yaml` -> `~/.config/yetano/yetano.yaml` ->
|
||||
`./yetano.yaml` -> `--config` cascade) predate this library and
|
||||
overlap with what it now provides. Migrating is a deliberately
|
||||
separate follow-up, not part of this change -- `yet`'s existing
|
||||
behavior needs to be evaluated field-by-field (e.g. `$YETANO_HOME`'s
|
||||
default of `os.UserConfigDir()/yetano` is *not* the same location
|
||||
`core/paths` would resolve for an app named "yetano"/"yet"; that
|
||||
divergence needs a conscious decision, not a silent behavior change).
|
||||
- Once `yet` migrates, evaluate `yasta`, `yamocir`, `yaiam`, and
|
||||
`yalsh`-adjacent projects the same way (per the original task
|
||||
description) -- each on its own merits, not as a blanket sweep.
|
||||
- [x] **Migrate `yet` onto `core/paths`/`core/config`.** `internal/config`
|
||||
already used `core/config`/`core/paths` (shared `Application{Name:
|
||||
"yetano"}`). `internal/store`'s own `$YETANO_HOME` (formerly
|
||||
`os.UserConfigDir()/yetano`, one monolithic root) has now been split
|
||||
across three independently overridable `core/paths` categories for
|
||||
`Application{Name: "yet", Kind: core.CLI}`: `store.Home()` (`DataDir`;
|
||||
store/packages/profiles/sources/credentials/trust-policy/deployments/
|
||||
share-lib-etc), `store.CacheHome()` (`CacheDir`; the blob cache), and
|
||||
`store.BinDir()` (`BinDir`; managed command entrypoints, shared across
|
||||
every Yetano application). This is a deliberate default-path and
|
||||
env-var-shape change (`$YETANO_HOME` no longer exists; see
|
||||
`YET_DATA_HOME`/`YETANO_DATA_HOME`, `YET_CACHE_HOME`/
|
||||
`YETANO_CACHE_HOME`, `YET_BIN_HOME`/`YETANO_BIN_HOME` instead) --
|
||||
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.
|
||||
- The remaining applications across the `yetano`, `yak`, and `yamase`
|
||||
meta-repos (`yasl`, `yamocir`, `yabaratla`, `yaais`, `yamcp`, `yacry`,
|
||||
`yasta`, `yaiam`, `yaclav`, `yafowa`, `yak/yaki`, `yak/yakas`, the
|
||||
`yamase-*` services) are tracked, with their migration order and a
|
||||
per-application how-to, in the meta-repo's `TODO-pathchange.md`
|
||||
(`yetano/yetano`), not here.
|
||||
|
||||
## Platform tuning
|
||||
|
||||
- FreeBSD's flavor (`freebsd.go`) is a best-effort first pass. Other BSD
|
||||
and Unix-family `GOOS` values (`openbsd`, `netbsd`, `dragonfly`,
|
||||
`solaris`, `illumos`, ...) currently fall back to the Linux flavor
|
||||
(`flavor()`'s default case) -- verified to compile and behave
|
||||
sensibly, not verified against each OS's actual convention. Adding a
|
||||
dedicated flavor table for one of them is a small, additive change
|
||||
(a new `<os>.go` file plus one `case` in `flavor()`), never a
|
||||
redesign.
|
||||
- macOS Desktop's `RuntimeDir()` (`~/Library/Application
|
||||
Support/<App>/Runtime`) is a placeholder -- macOS has no strong native
|
||||
convention for a GUI app's ephemeral runtime directory the way
|
||||
XDG_RUNTIME_DIR does on Linux. Revisit if a real Desktop consumer
|
||||
needs something more specific (e.g. a `TemporaryItems`-based
|
||||
location).
|
||||
- `LogAliasDir()` (spec section 39: `~/.local/log/<app>` as a Unix
|
||||
convenience symlink target) is resolved but never created -- no
|
||||
symlink-creation API exists yet. Decide whether this is worth adding
|
||||
before any consumer actually wants it.
|
||||
- [x] macOS Desktop's `RuntimeDir()` now prefers `$TMPDIR` (the
|
||||
OS-managed, per-user, securely permissioned ephemeral directory every
|
||||
macOS process gets -- what `NSTemporaryDirectory()` returns), the real
|
||||
native equivalent to XDG_RUNTIME_DIR's role. It falls back to the
|
||||
previous `~/Library/Application Support/<App>/Runtime` placeholder only
|
||||
when `TMPDIR` is unset in the resolved environment (simulated/test
|
||||
environments that never set it).
|
||||
- [x] `LogAliasDir()` (spec section 39: `~/.local/log/<app>` as a Unix
|
||||
convenience symlink target) now has a creation API:
|
||||
`Resolver.EnsureLogAlias()` creates the `LogDir()` symlink if missing,
|
||||
leaves any pre-existing entry untouched, and is a no-op alias of
|
||||
`EnsureLogDir()` on Windows/macOS Desktop (where the two already
|
||||
coincide).
|
||||
- **Low priority, not an MVP blocker:** FreeBSD's flavor (`freebsd.go`)
|
||||
is a best-effort first pass. Other BSD and Unix-family `GOOS` values
|
||||
(`openbsd`, `netbsd`, `dragonfly`, `solaris`, `illumos`, ...) currently
|
||||
fall back to the Linux flavor (`flavor()`'s default case) -- verified
|
||||
to compile and behave sensibly, not verified against each OS's actual
|
||||
convention. 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
|
||||
|
||||
@@ -52,13 +64,71 @@ speculatively.
|
||||
launcher, spec section 20) is explicitly out of scope for `core` --
|
||||
path resolution and package activation stay separate concerns (spec
|
||||
section 20's own instruction).
|
||||
- The native `SHGetKnownFolderPath` fallback in
|
||||
`knownfolders_windows.go` has only been verified to compile
|
||||
(`GOOS=windows go build`/`go vet`), never run on an actual Windows
|
||||
host. It is a secondary fallback below environment variables, so a
|
||||
latent bug there would only matter in the edge case where
|
||||
`APPDATA`/`LOCALAPPDATA`/`PROGRAMDATA` are all unset in the process
|
||||
environment on real Windows.
|
||||
- [x] **The native `SHGetKnownFolderPath` fallback has now been run on a
|
||||
real Windows host** (Windows 10, Go 1.25), not just cross-compiled.
|
||||
With `APPDATA`/`LOCALAPPDATA`/`PROGRAMDATA` all unset, `ConfigDir()`/
|
||||
`DataDir()`/system-scope `ConfigDir()` correctly resolved the real
|
||||
roaming/local/`ProgramData` known folders via the native API (source
|
||||
reported as `windows-known-folder`), confirmed via `Explain()` across
|
||||
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
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ type Resolver struct {
|
||||
envExpansion bool
|
||||
env paths.Environment
|
||||
pathsOpts []paths.Option
|
||||
explicitPath string
|
||||
}
|
||||
|
||||
// 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...) }
|
||||
}
|
||||
|
||||
// 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.
|
||||
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
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"yetano.dev/yetano/core"
|
||||
@@ -25,21 +26,44 @@ type Layer struct {
|
||||
// the last fallback.
|
||||
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 {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// layers builds the full, ordered layer list (spec sections 21/22): the
|
||||
// working directory (if enabled), then core/paths's own ConfigSearchDirs
|
||||
// for this application (optionally dropping the system-tier layer), then
|
||||
// -- opt-in only -- the shared Yetano defaults directory.
|
||||
// layers builds the full, ordered layer list (spec sections 21/22): an
|
||||
// explicit override path (if set; see WithExplicitPath), then the
|
||||
// working directory (if enabled), then core/paths's own
|
||||
// ConfigSearchDirs for this application (optionally dropping the
|
||||
// system-tier layer), then -- opt-in only -- the shared Yetano defaults
|
||||
// directory.
|
||||
func (r *Resolver) layers() ([]Layer, error) {
|
||||
var out []Layer
|
||||
|
||||
if r.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 {
|
||||
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,
|
||||
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,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
|
||||
// ~/.local/log/<app> (spec section 39). It is never created
|
||||
// automatically; nothing else in this package treats it as canonical.
|
||||
// On Windows and macOS Desktop it is the same as LogDir (there is no
|
||||
// separate alias convention there).
|
||||
// ~/.local/log/<app> (spec section 39). Resolving it never creates
|
||||
// anything -- use EnsureLogAlias for that; nothing else in this package
|
||||
// treats it as canonical. On Windows and macOS Desktop it is the same as
|
||||
// LogDir (there is no separate alias convention there).
|
||||
func (r *Resolver) LogAliasDir() (string, error) {
|
||||
if r.isWindows() || r.isDarwinDesktop() {
|
||||
return r.LogDir()
|
||||
|
||||
+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) {
|
||||
root := t.TempDir()
|
||||
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),
|
||||
WithRuntimeDir(root+"/runtime-override"))
|
||||
WithRuntimeDir("/runtime-override"))
|
||||
|
||||
ensures := []func() (string, error){
|
||||
r.EnsureConfigDir, r.EnsureDataDir, r.EnsureStateDir,
|
||||
|
||||
+24
-4
@@ -80,7 +80,11 @@ func (r *Resolver) darwinDesktopStateDir() (value, error) {
|
||||
if err != nil {
|
||||
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) {
|
||||
@@ -113,15 +117,28 @@ func (r *Resolver) darwinDesktopLogDir() (value, error) {
|
||||
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) {
|
||||
if v, ok := r.overrideValue(RuntimePath); ok {
|
||||
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()
|
||||
if err != nil {
|
||||
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
|
||||
@@ -143,16 +160,19 @@ func (r *Resolver) darwinDesktopLayers(kind PathKind, base func(core.Scope, stri
|
||||
if v, ok := r.overrideValue(kind); ok {
|
||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||
}
|
||||
var user []layer
|
||||
home, err := r.homeDir()
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := []layer{{
|
||||
if err == nil {
|
||||
user = []layer{{
|
||||
path: r.applyRoot(unixJoin(base(core.UserScope, home), r.app.Name)),
|
||||
source: MacOSNative,
|
||||
priority: PriorityUser,
|
||||
canonical: true,
|
||||
}}
|
||||
}
|
||||
system := []layer{{
|
||||
path: r.applyRoot(unixJoin(base(core.SystemScope, ""), r.app.Name)),
|
||||
source: SystemDirectory,
|
||||
|
||||
+81
-14
@@ -76,6 +76,22 @@ func JoinFamily(platform string, elems ...string) string {
|
||||
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/
|
||||
// DataSearchDirs/ExecutableSearchDirs, in either address family) with a
|
||||
// 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
|
||||
}
|
||||
|
||||
// applyRootUnix rebases an absolute unix-family path under root, when
|
||||
// root is set. An empty root leaves p untouched.
|
||||
func applyRootUnix(root, p string) string {
|
||||
if root == "" {
|
||||
return p
|
||||
}
|
||||
return unixJoin(root, strings.TrimPrefix(p, "/"))
|
||||
// isWindowsPath reports whether p looks like a Windows-family path
|
||||
// (backslash-separated, no forward slash) -- the same content-based
|
||||
// heuristic JoinDirFile uses, applied here to root rather than to a
|
||||
// resolved category directory.
|
||||
func isWindowsPath(p string) bool {
|
||||
return strings.ContainsRune(p, '\\') && !strings.ContainsRune(p, '/')
|
||||
}
|
||||
|
||||
// applyRootWindows rebases an absolute windows-family path under root,
|
||||
// when root is set. An empty root leaves p untouched.
|
||||
func applyRootWindows(root, p string) string {
|
||||
// pathSegments splits an absolute path p (in the given family) into its
|
||||
// plain path components, discarding p's own absolute-path root marker
|
||||
// (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 == "" {
|
||||
return p
|
||||
}
|
||||
_, rest, ok := splitWindowsRoot(p)
|
||||
if !ok {
|
||||
return windowsJoin(root, p)
|
||||
segments := pathSegments(p, pIsWindows)
|
||||
elems := append([]string{root}, segments...)
|
||||
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) {
|
||||
if got, want := applyRootUnix("", "/etc/yet"), "/etc/yet"; got != want {
|
||||
t.Errorf("applyRootUnix(\"\", ...) = %q, want %q", got, want)
|
||||
func TestApplyRootRebaseUnix(t *testing.T) {
|
||||
if got, want := applyRootRebase("", "/etc/yet", false), "/etc/yet"; got != want {
|
||||
t.Errorf("applyRootRebase(\"\", ...) = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := applyRootUnix("/tmp/root", "/etc/yet"), "/tmp/root/etc/yet"; got != want {
|
||||
t.Errorf("applyRootUnix = %q, want %q", got, want)
|
||||
if got, want := applyRootRebase("/tmp/root", "/etc/yet", false), "/tmp/root/etc/yet"; got != want {
|
||||
t.Errorf("applyRootRebase = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRootWindows(t *testing.T) {
|
||||
if got, want := applyRootWindows("", `C:\ProgramData\yet`), `C:\ProgramData\yet`; got != want {
|
||||
t.Errorf("applyRootWindows(\"\", ...) = %q, want %q", got, want)
|
||||
func TestApplyRootRebaseWindows(t *testing.T) {
|
||||
if got, want := applyRootRebase("", `C:\ProgramData\yet`, true), `C:\ProgramData\yet`; 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 {
|
||||
t.Errorf("applyRootWindows = %q, want %q", got, want)
|
||||
if got, want := applyRootRebase(`C:\sandbox`, `C:\ProgramData\yet`, true), `C:\sandbox\ProgramData\yet`; got != want {
|
||||
t.Errorf("applyRootRebase = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := applyRootWindows(`C:\sandbox`, `\\server\share\yet`), `C:\sandbox\yet`; got != want {
|
||||
t.Errorf("applyRootWindows(UNC) = %q, want %q", got, want)
|
||||
if got, want := applyRootRebase(`C:\sandbox`, `\\server\share\yet`, true), `C:\sandbox\yet`; 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)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
import "yetano.dev/yetano/core"
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"yetano.dev/yetano/core"
|
||||
)
|
||||
|
||||
// layer is one directory in a search/priority hierarchy (see
|
||||
// AGENTS.md-style docs in paths.go: "canonical path vs. search paths").
|
||||
@@ -40,6 +44,22 @@ func composeSearch(user, system []layer, scope core.Scope) []layer {
|
||||
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
|
||||
// YETANO_*/<PREFIX>_* environment variable names (e.g. ConfigPath ->
|
||||
// "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) isDarwin() bool { return r.platform == "darwin" }
|
||||
|
||||
// applyRoot rebases an absolute path under the portable root (WithRoot),
|
||||
// if one is set, using the same address family as r.platform.
|
||||
// applyRoot rebases an absolute path (in r.platform's simulated address
|
||||
// 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 {
|
||||
if r.isWindows() {
|
||||
return applyRootWindows(r.root, p)
|
||||
}
|
||||
return applyRootUnix(r.root, p)
|
||||
return applyRootRebase(r.root, p, r.isWindows())
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
+21
-9
@@ -146,9 +146,12 @@ func (r *Resolver) logDirUnix() (value, error) {
|
||||
if err != nil {
|
||||
return value{}, err
|
||||
}
|
||||
// stateDirUnix already applied the root; join the "log" suffix onto
|
||||
// the already-rooted path so it isn't rebased twice.
|
||||
return value{path: unixJoin(state.path, "log"), source: state.source}, nil
|
||||
// stateDirUnix already applied the root, so joining the "log" suffix
|
||||
// must use JoinDirFile (not unixJoin) rather than rebasing again:
|
||||
// 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
|
||||
@@ -183,16 +186,19 @@ func (r *Resolver) configLayersUnix() ([]layer, error) {
|
||||
if v, ok := r.overrideValue(ConfigPath); ok {
|
||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||
}
|
||||
var user []layer
|
||||
userVal, err := r.xdgBase("XDG_CONFIG_HOME", ".config")
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := []layer{{
|
||||
if err == nil {
|
||||
user = []layer{{
|
||||
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
|
||||
source: userVal.source,
|
||||
priority: PriorityUser,
|
||||
canonical: true,
|
||||
}}
|
||||
}
|
||||
system := make([]layer, len(r.flavor().systemConfigDirs))
|
||||
for i, dir := range r.flavor().systemConfigDirs {
|
||||
system[i] = layer{
|
||||
@@ -209,16 +215,19 @@ func (r *Resolver) dataLayersUnix() ([]layer, error) {
|
||||
if v, ok := r.overrideValue(DataPath); ok {
|
||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||
}
|
||||
var user []layer
|
||||
userVal, err := r.xdgBase("XDG_DATA_HOME", ".local", "share")
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := []layer{{
|
||||
if err == nil {
|
||||
user = []layer{{
|
||||
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
|
||||
source: userVal.source,
|
||||
priority: PriorityUser,
|
||||
canonical: true,
|
||||
}}
|
||||
}
|
||||
dirs, source := r.xdgDataDirs()
|
||||
system := make([]layer, len(dirs))
|
||||
for i, dir := range dirs {
|
||||
@@ -236,16 +245,19 @@ func (r *Resolver) executableLayersUnix() ([]layer, error) {
|
||||
if v, ok := r.overrideValue(BinPath); ok {
|
||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||
}
|
||||
var user []layer
|
||||
home, err := r.homeDir()
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := []layer{{
|
||||
if err == nil {
|
||||
user = []layer{{
|
||||
path: r.applyRoot(unixJoin(home, ".local", "bin")),
|
||||
source: PlatformDefault,
|
||||
priority: PriorityUser,
|
||||
canonical: true,
|
||||
}}
|
||||
}
|
||||
system := []layer{{
|
||||
path: r.applyRoot(r.flavor().systemBinDir),
|
||||
source: SystemDirectory,
|
||||
|
||||
+16
-6
@@ -128,9 +128,10 @@ func (r *Resolver) configLayersWindows() ([]layer, error) {
|
||||
var user []layer
|
||||
if r.app.Kind != core.Desktop {
|
||||
local, err := r.windowsBase("LOCALAPPDATA")
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err == nil {
|
||||
user = append(user, layer{
|
||||
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
|
||||
source: local.source,
|
||||
@@ -138,16 +139,19 @@ func (r *Resolver) configLayersWindows() ([]layer, error) {
|
||||
canonical: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
roaming, err := r.windowsBase("APPDATA")
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err == nil {
|
||||
user = append(user, layer{
|
||||
path: r.applyRoot(windowsJoin(roaming.path, r.app.Name)),
|
||||
source: roaming.source,
|
||||
priority: PriorityUser,
|
||||
canonical: true,
|
||||
})
|
||||
}
|
||||
system, err := r.windowsSystemLayer(r.app.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -161,16 +165,19 @@ func (r *Resolver) dataLayersWindows() ([]layer, error) {
|
||||
if v, ok := r.overrideValue(DataPath); ok {
|
||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||
}
|
||||
var user []layer
|
||||
local, err := r.windowsBase("LOCALAPPDATA")
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := []layer{{
|
||||
if err == nil {
|
||||
user = []layer{{
|
||||
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
|
||||
source: local.source,
|
||||
priority: PriorityUserLocal,
|
||||
canonical: true,
|
||||
}}
|
||||
}
|
||||
system, err := r.windowsSystemLayer(r.app.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -182,16 +189,19 @@ func (r *Resolver) executableLayersWindows() ([]layer, error) {
|
||||
if v, ok := r.overrideValue(BinPath); ok {
|
||||
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
|
||||
}
|
||||
var user []layer
|
||||
local, err := r.windowsBase("LOCALAPPDATA")
|
||||
if err != nil {
|
||||
if err := skipMissingHome(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := []layer{{
|
||||
if err == nil {
|
||||
user = []layer{{
|
||||
path: r.applyRoot(windowsJoin(local.path, "Yetano", "bin")),
|
||||
source: local.source,
|
||||
priority: PriorityUserLocal,
|
||||
canonical: true,
|
||||
}}
|
||||
}
|
||||
system, err := r.windowsSystemLayer("Yetano", "bin")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -164,12 +164,35 @@ func TestWindowsDesktopSimplerLayering(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{}))
|
||||
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
|
||||
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) {
|
||||
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithConfigDir(`D:\portable\yet-config`))
|
||||
got, err := r.ConfigDir()
|
||||
|
||||
Reference in new issue
Block a user