19 Commits
Author SHA1 Message Date
terminarandClaude Opus 5.5 c11197bb37 configfamily: one config file per program plus an optional family file
The generic part of yamase-core/pkg/configfile (yamase ADR-0074): per
tier a program merges the family file's top level, its section of the
family file and its own <program>.yaml, then --config. Includes
unknown-option rules for shared files, the config command on top of
configcmd.Layered with "create --shared", and doctor/logging helpers.
yaiam is the first user; yamase can move onto it later.

configcmd: a layered Optional program without any file now validates
its defaults and passes doctor instead of failing, as the single-file
path already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 20:26:25 +01:00
terminarandClaude Opus 5.5 5471863163 cobracmd: unknown subcommands of a command group are usage errors (exit 2)
cobra rejects an unknown subcommand only at the root; "prog group nosuch"
printed the group's help and exited 0. Execute now calls StrictGroups
first (found in yamase-ctl while rolling out cobracmd/v0.1.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:48:52 +01:00
terminarandClaude Opus 5.5 5288c4ce74 cobracmd: standard completion and exit codes for cobra programs; bash install line via eval
New module yetano.dev/yetano/core/cobracmd (own go.mod, cobra stays out
of the main module): Completion replaces cobra's default completion
command, which exits 0 for an unknown shell, with one that accepts only
bash|zsh|fish|powershell (exit 2 otherwise); Execute maps cobra's usage
errors to exit 2, other errors to 1.

completion: the bash script's install line is eval "$(prog completion
bash)" -- bash 3.2 on macOS cannot source a process substitution.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:34:39 +01:00
terminarandClaude Opus 5.5 fa52990e3e configcmd: config show, Doctor, KnownKey and a Layered hook
"config show [--json] [--show-secrets]" prints the configuration with
the origin of every value (secrets redacted), for every program.
Spec.Layered lets a program whose configuration is merged from several
inputs (family file, a section of it, its own file -- the yamase
family) run path, validate and show over all layers, with its own
unknown-option rules; unknown options are warnings there. Doctor(report,
spec, explicit) is the config part of a doctor command. UnknownKey
carries the layer it is in; KnownKey tells whether a dotted key is an
option of a config struct.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:29:19 +01:00
terminarandClaude Opus 5.5 185211e304 config: Merge with per-value origins; configcmd: UnknownKeysNode
config.Merge(sources...) overlays explicit, ordered sources with the
LoadMerged rules (LoadMerged now uses the same code) and returns the
origin of every leaf, for a "config show" that says where each value
is set. config.ReadFile reads one file as a mapping, Resolver.Paths()
exposes the core/paths resolver (e.g. DataDir for defaults).
configcmd.UnknownKeysNode checks one section of a parsed document.
Needed by the yamase family's layered configuration (yamase ADR-0074).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:57:50 +01:00
terminarandClaude Opus 5.5 b7f7ba6b36 TODO: follow-ups now live in the meta-repo TODO.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:36:16 +02:00
terminarandClaude Opus 5.5 88d37410f7 tui: shared terminal-UI kernel as nested module yetano.dev/yetano/core/tui
Themes (slate/dialog/midnight) and their lipgloss styles, Paint/Outer,
ListState and the text helpers that yet, yavebu and yalsh menuconfig
each carried as a hand-kept copy (yavebu's had already drifted). Values
are yet's (grey slate); Paint is menuconfig's profile-aware version.
Own go.mod and tui/vX.Y.Z tags keep Charm out of the main module.
Programs are not switched yet; tui/README.md has the steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:54:25 +02:00
terminarandClaude Opus 5.5 8c63d42a27 gui: native WebView host as nested module yetano.dev/yetano/core/gui
Extracted from prototypes/yetano-webview (AP1): packages assets,
document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows
Win32/WebView2 pure Go). No local HTTP listener or port: assets go
through the WebView's resource handler, app routes through the native
message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the
WebView dependencies out of the main core module. Adds backend-free
tests for the window's dispatch/destroy guards and a yet-gui migration
guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:47:26 +02:00
terminarandClaude Opus 5.5 90132e2d76 configcmd and version: the config and version standard commands; darwin /var/run
core/configcmd: "<program> config create|validate|upgrade|path" from a
Spec (name, application, minimal/full templates, Validate, Schema),
taken over from yamase-core/pkg/configcmd and generalized: Filename,
Optional (programs that run on defaults) and None (no configuration).

core/version: "<program> version [--json]" over the values each
program stamps into its internal/version; JSON keys match yasta's
existing output (yavebu reads it), VCS fallback for unstamped builds.

paths: macOS CLI/Service system-scope RuntimeDir is /var/run/<app>
instead of /run/<app>, which macOS does not have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:36:48 +02:00
terminarandClaude Opus 5.5 ca0f06f978 Ignore resume.sh (local session helper)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:32:05 +02:00
terminarandClaude Opus 5.5 58dfe0f5a6 README: yavebu uses core/secretref now
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 12:20:07 +02:00
terminarandClaude Opus 5.5 43775950a4 secretref: secret://, env:, file:, base64: references (from yavebu) for yacry and yadenes
Adds IsReference for programs that keep accepting literals, and
YasevaConfig (passed as --config).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 12:17:04 +02:00
terminarandClaude Opus 5.5 13c1862c74 completion, doctor: the shared standard commands
core/completion prints bash, zsh, fish or PowerShell completion scripts
from a static command tree ("<program> completion <shell>"); core/doctor
is one report shape (resolved paths incl. the standard core/paths ones,
named checks), printed as a table or --json, exit 0/1/2. Together with
core/manual they implement the Yetano program standard
(docs/program-conventions.md in the meta-repo).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:30:45 +02:00
terminarandClaude Opus 5.5 e757fdd025 manual: the shared "<program> manual" command (ADR-0012)
FromFS turns embedded README.md + docs/**/*.md into topics (README is
"readme", titles from the first heading); Run serves "manual",
"manual <topic>" and "manual --json [topic]" -- the JSON shape yet
reads for an installed program's manual (yet manual --package, TUI,
yet-gui), same as "yet manual --json".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:22:03 +02:00
terminarandClaude Opus 5.5 e8bf23a064 paths: skip the user search tier when there is no home directory
ConfigSearchDirs/DataSearchDirs/ExecutableSearchDirs (and therefore
core/config's Resolve/ResolveAll/LoadMerged) failed outright with
ErrNoHomeDirectory when HOME/USERPROFILE was unset, so a service
started without HOME could no longer find its working-directory or
/etc/<app> config -- a regression against the hand-rolled lookups
being migrated onto core, which just skipped the user location.
Missing-home now only drops the user tier from the search lists; the
canonical <Category>Dir() methods still report ErrNoHomeDirectory.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-22 22:24:51 +02:00
terminarandClaude Opus 5.5 72b656262d TODO: point remaining application migrations at the meta-repo's TODO-pathchange.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-22 21:54:07 +02:00
terminarandClaude Sonnet 5 da2ec85381 Refine macOS/LogAlias platform tuning, fix a real WithRoot bug found on Windows
Platform tuning:
- macOS Desktop's RuntimeDir() now prefers $TMPDIR (the OS-managed,
  per-user ephemeral directory NSTemporaryDirectory() returns) over
  the previous ~/Library/Application Support/<App>/Runtime placeholder.
- Resolver.EnsureLogAlias() creates the optional LogAliasDir() symlink
  to LogDir(), idempotently, leaving any pre-existing entry alone.

Verified the SHGetKnownFolderPath fallback (knownfolders_windows.go)
on a real Windows host for the first time: with APPDATA/LOCALAPPDATA/
PROGRAMDATA all unset, it correctly resolves the real known folders.
go vet's one unsafeptr finding there is a documented, permanent,
unavoidable characteristic of this raw-syscall pattern, not a bug.

That same real-Windows run surfaced a genuine, previously-invisible
bug: WithRoot assumed root's own address family always matched the
*simulated* platform's, which silently broke (mixed separators, or an
outright invalid mid-path drive letter) whenever the real host's
native family differed from what WithPlatform was simulating -- e.g.
WithPlatform("linux") with WithRoot(t.TempDir()) on a real Windows
host. This was invisible on macOS/Linux, where t.TempDir() happens to
already share the simulated Unix family.

Fixed applyRoot (now applyRootRebase) to decompose the resolved path
into segments and re-join them onto root using root's own family,
inferred from its content like JoinDirFile already does, not from the
simulated platform. Two call sites chaining onto an already-rooted
value (logDirUnix, darwin.go's State/Runtime fallback) switched from a
hardcoded unixJoin to JoinDirFile for the same reason. core/config's
working-directory layer had the identical bug one level up; fixed via
a new paths.JoinDirFileFamily.

TODO.md/ARCHITECTURE.md/README.md updated accordingly; core/TODO.md's
remaining items are now all explicitly out-of-scope or deliberately
deprioritized, not open work.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 16:37:30 +02:00
terminarandClaude Sonnet 5 e6b5324ad3 TODO: mark the yet core/paths migration done
yet's internal/store now resolves Home/CacheHome/BinDir via
core/paths (Application{Name: "yet", Kind: core.CLI}) instead of its
own $YETANO_HOME/os.UserConfigDir() logic, split across three
independently overridable categories. See yetano.dev/yetano/yet's
own commit for the actual migration and its new --system scope flag.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 15:14:58 +02:00
terminarandClaude Sonnet 5 689469eb32 config: add WithExplicitPath for a CLI's own --config flag
A highest-priority, must-exist override layer above the working
directory -- the common "flag always wins, but a typo'd path should
fail loudly" pattern most Yetano CLIs need, generalized here instead
of reimplementing it in each application (first consumer: yet's own
--config flag, see the yet submodule).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 16:50:22 +02:00
82 changed files with 11733 additions and 130 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# local claude --resume helper
resume.sh
+124
View File
@@ -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`,
@@ -162,3 +234,55 @@ test file). This is spec section 47's explicit requirement, and it's
why `Explain` and `Ensure*` are entirely separate code paths: the former
must never accidentally gain a side effect by sharing implementation
with the latter.
## Standard commands: one implementation, program-specific data
`manual`, `completion`, `doctor`, `configcmd` and `version` implement
the commands every Yetano program offers (docs/program-conventions.md in
the meta-repository). Each takes the program's own part as plain data
(an embedded FS, a command tree, a report, a `configcmd.Spec`, a
`version.Info`) and returns an exit code; none depends on cobra or on a
program's flag parser, so a flag-only daemon and a cobra CLI wire them
the same way. They never mutate the filesystem except where the command
exists to do so (`config create`, `config upgrade --write`).
`configcmd` keeps the config schema in the program: core only knows the
YAML tree, the templates and, via reflection on the program's struct,
which keys exist. It started as `yamase-core/pkg/configcmd` and moved
here unchanged in behavior when the other meta-repos needed it.
`configfamily` is the layered configuration of a program family (a
family file, a section of it and a per-program file in every tier) on
top of `configcmd.Layered`. It is the generic part of
`yamase-core/pkg/configfile` (yamase ADR-0074), taken over when yaiam
split into several programs; what is specific to one family -- yamase's
data-dir and storage-role defaults -- stays in that family's code.
## core/gui: a nested module, not a package of this one
The WebView host needs cgo and Cocoa/WebKit on macOS and
`go-webview2`/`x/sys/windows` on Windows; a CLI or daemon importing
`core/paths` must not inherit any of that. So `gui/` has its own
`go.mod` (`yetano.dev/yetano/core/gui`), its own prefixed tags
(`gui/vX.Y.Z`) and its own Go version, while living in the same
repository (one vanity import, one history). It does not import the main
module today; a consumer passes `DataPath` (WebView2 user data) from its
own `core/paths` resolver instead.
Unlike `core/paths`, the GUI host *does* use one build-tagged file per OS
(`window_darwin.go` + `darwin.m`, `window_windows.go`, `window_other.go`):
these are real native bindings that can only be compiled for their OS,
the same exception the root AGENTS.md makes for
`paths/knownfolders_windows.go`. Everything above the window (`assets`,
`document`, `bridge`) is platform-free and unit-tested on any host;
browser behavior is verified by the prototype's in-window selftest.
## core/tui: only what is already identical
`tui/` is a nested module for the same reason as `gui/` (Charm stays out
of the main module's graph). It holds only code that at least two
programs carried byte-identically (themes, styles, paint/outer, list
state, text helpers), not a framework: the app frame, menus and screens
differ per program and move here only once two programs share them. The
long-term `core/ui` (UI-neutral model) / `core/tui` / `core/gui` split of
`docs/yetano-ui/` can grow from this without breaking it.
+263 -5
View File
@@ -6,13 +6,38 @@ and platform integration -- not just a grab-bag of utility functions (see
`AGENTS.md` in the meta-repository root, and [ARCHITECTURE.md](ARCHITECTURE.md)
for the full design rationale).
The first area covered is **platform-independent path, file, and
configuration resolution**: `core/paths` and `core/config`.
It covers **platform-independent path, file, and configuration
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`).
Two **separate, nested modules** keep this module at its single
dependency: the native WebView GUI host `yetano.dev/yetano/core/gui`
(tags `gui/vX.Y.Z`, cgo, see [gui/README.md](gui/README.md)) and the
shared terminal-UI kernel `yetano.dev/yetano/core/tui` (tags
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)).
```text
yetano.dev/yetano/core
yetano.dev/yetano/core/paths
yetano.dev/yetano/core/config
yetano.dev/yetano/core/manual
yetano.dev/yetano/core/completion
yetano.dev/yetano/core/doctor
yetano.dev/yetano/core/configcmd
yetano.dev/yetano/core/configfamily
yetano.dev/yetano/core/version
yetano.dev/yetano/core/secretref
yetano.dev/yetano/core/cobracmd (separate module)
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
yetano.dev/yetano/core/gui/assets
yetano.dev/yetano/core/gui/document
yetano.dev/yetano/core/gui/bridge
yetano.dev/yetano/core/gui/window
yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z)
```
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
@@ -59,6 +84,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 +140,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 +171,19 @@ 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 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
@@ -155,10 +200,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
@@ -198,6 +252,27 @@ LOCALAPPDATA/APPDATA/PROGRAMDATA layering `core/paths` already resolves.
layer can write `key: null` to intentionally unset a lower layer's
value).
### Merging your own layers, with origins
An application whose layers are not one file name per directory (the
yamase family reads a shared `yamase.yaml`, one section of it, and a
per-program file in every tier) builds its own ordered list and merges
it with the same rules:
```go
data, err := config.ReadFile(path) // one file as a mapping
merged, origins := config.Merge(
config.Source{Name: "/etc/app/shared.yaml", Data: shared},
config.Source{Name: "/etc/app/app.yaml", Data: data},
)
// origins["tls.cert-file"] == the Name of the source that set it
```
`Origins` maps every leaf's dotted key to the source it came from (a
list is one leaf), for a "config show" that says where each value is
set. `Resolver.Paths()` returns the underlying `core/paths` resolver,
e.g. for a default derived from `DataDir()`.
### Environment expansion
String values may reference `${VAR}` or `$VAR` (enabled by default,
@@ -216,6 +291,145 @@ 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).
## 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.
`config show [--json] [--show-secrets]` prints the configuration with
the file every value comes from (`Effective.Show`; secrets -- keys
`secrets`, `secret`, `token`, `password` -- are redacted unless
`--show-secrets`, references like `env:X` stay visible), and
`configcmd.Doctor(report, spec, explicit)` is the config part of a
`doctor` command (paths, layers, "config file found", unknown options).
A program whose configuration is merged from more than one file name
per directory -- a family-wide file, a section of it and a per-program
file, as in the yamase family -- sets `Spec.Layered`: `Layers` (what
`config path` lists), `Load` (merge, e.g. with `config.Merge`, into an
`Effective`), optionally `Unknown` (its own unknown-option rules),
`Validate(merged)` and `Used(key)`. `path`, `validate` and `show` then
work on all layers, unknown options become warnings (shared files carry
options of other programs), and `create`/`upgrade` keep working on the
program's own file. `KnownKey(schema, "a.b[0].c")` tells whether a
dotted key is an option of a config struct.
## core/configfamily: one file per program, an optional family file
`core/configfamily` is that layered setup ready-made, for a family of
programs that share one set of config directories (the yamase-* or
yaiam-* programs). Each program is responsible for its own file
(`<program>.yaml`); the family file (`<family>.yaml`) is optional and
holds, at its top level, what several programs share, plus one section
per program (`web:` for `yaiam-web`). Per tier -- system, then user,
then `--config` -- a program merges: family file top level, its section,
its own file. The working directory is never read.
```go
family := configfamily.Family{
Name: "yaiam", Programs: []string{"ctl", "web", "authd"},
Shared: config.Shared{}, SharedTemplate: config.SharedTemplate,
}
spec := configfamily.Spec{
Program: family.Service("yaiam-web"), Optional: true,
Minimal: webMinimal, Full: webFull, Schema: config.WebConfig{},
Validate: func(merged []byte) error { ... },
}
os.Exit(configfamily.Run(spec, configFlag, args, os.Stdout, os.Stderr))
```
`Load(program, explicit)` returns the merged layers (`Loaded.YAML()`
for the program's own parser, `Describe()` for log lines) or
`ErrNotFound`; `Loaded.Unknown(schema)` reports options no layer may
carry -- an option of `Family.Shared` is valid in every layer, other
programs' sections are not this program's business. `Run` adds `config
create --shared` (writes `Family.SharedTemplate`) to core/configcmd's
commands; `Doctor`, `LogLayers` and `WarnUnknown` are the doctor and
startup parts. Defaults that depend on more than the files (yamase's
data-dir and storage roles) stay with the family's own code.
## core/cobracmd: cobra programs (separate module)
`yetano.dev/yetano/core/cobracmd` (own `go.mod`, tags `cobracmd/vX.Y.Z`,
so the main module stays free of cobra) fixes the two places where cobra
behaves differently from the standard: `cobracmd.Completion(root)`
replaces cobra's default `completion` command with one that takes exactly
`bash|zsh|fish|powershell` (cobra's own exits 0 for `completion tcsh`),
and `os.Exit(cobracmd.Execute(root))` maps errors to the standard exit
codes -- 2 for usage errors (unknown command, flag or shell, wrong
argument count, or an error wrapped with `cobracmd.Usage`), 1 otherwise.
## 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
- Environment expansion is variable substitution only -- never shell
@@ -234,4 +448,48 @@ opts in explicitly with `config.WithYetanoDefaults(true)`.
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
force-moved to a different commit.
force-moved to a different commit. The nested `gui` and `tui` modules
have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change
there needs no main-module tag and vice versa.
## 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.
## core/gui (separate module)
`yetano.dev/yetano/core/gui` is the native WebView host for desktop
programs (macOS: Cocoa + WKWebView; Windows: Win32 + WebView2): embedded
assets served through the WebView's own resource handler, the page's
`fetch`/XHR routed to Go handlers over the native message binding,
streaming, abort and reload handling -- never a local HTTP listener or
port. Packages `assets`, `document`, `bridge`, `window`; extracted from
`prototypes/yetano-webview` (AP1). Details, invariants, measured platform
pitfalls and the yet-gui migration: [gui/README.md](gui/README.md).
## core/tui (separate module)
`yetano.dev/yetano/core/tui` is the kernel the Charm-v2 terminal UIs
(yet, yavebu, yalsh menuconfig) had as hand-kept copies: the themes
`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`,
`ListState` and text helpers. No app shell or screens yet -- see
[tui/README.md](tui/README.md), which also has the migration steps.
+132 -47
View File
@@ -6,41 +6,71 @@ 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.
- [x] The remaining applications across the `yetano`, `yak`, and
`yamase` meta-repos were migrated on 2026-09-22; the open
follow-ups are in the meta-repo's `TODO.md` ("core/paths:
Folge-Punkte"; the former `TODO-pathchange.md` is in its git history).
## 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.
- [x] `core/gui`: the native WebView host from
`prototypes/yetano-webview`, as the nested module
`yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it.
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
(steps in [gui/README.md](gui/README.md)).
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
ListState, text helpers) as the nested module
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
- [ ] Move yet's and yavebu's `internal/tui` onto `core/tui` (steps in
[tui/README.md](tui/README.md)); yalsh menuconfig after an owner
decision on `yalsh.dev` -> `yetano.dev` imports.
## 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 +82,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
@@ -66,18 +154,15 @@ speculatively.
and is tested, but there is no ecosystem-wide "portable install"
concept wired up yet (spec section 41's "optional later:
`YETANO_HOME` or portable mode").
- The future `yet` package store model (spec sections 2/37/38: package
store vs. application data vs. config vs. state vs. cache vs. runtime
vs. executables, as distinct concepts) is intentionally not
implemented here -- `core/paths` only provides the primitives (scoped,
prioritized directories) a future store implementation would sit on
top of.
- The `yet` package store (spec sections 2/37/38) lives in `yet`
(`internal/store`), built on these primitives; `core/paths` itself
stays store-agnostic.
- Plugin/extension search paths: no dedicated category exists yet;
`paths.FindFile` is generic enough that a caller can build one today
(e.g. over `DataSearchDirs()` with a `plugins/` suffix) without
needing a new `PathKind`.
- Atomic package activation, versioning/rollback for that future store:
out of scope, same as above.
- Atomic package activation, versioning/rollback for the store: `yet`'s
business, not core's.
## Central Yetano config
+208
View File
@@ -0,0 +1,208 @@
// Package cobracmd gives cobra-based Yetano programs the parts of the
// program standard (docs/program-conventions.md in the yetano
// meta-repository) that cobra does differently by default:
//
// - Completion replaces cobra's default "completion" command with one
// that takes exactly bash, zsh, fish or powershell. cobra's own
// command prints its help and exits 0 for "completion tcsh"; the
// standard wants exit 2 for an unknown shell.
// - Execute runs the root command and returns the standard exit code:
// 0 on success, 2 for a usage error (unknown command, flag or shell,
// wrong number of arguments), 1 for any other error.
//
// It is a separate module (yetano.dev/yetano/core/cobracmd) so that the
// main core module stays free of cobra.
//
// func main() {
// root := newRootCommand()
// cobracmd.Completion(root)
// os.Exit(cobracmd.Execute(root))
// }
//
// A command that wants to report a usage error itself returns
// cobracmd.Usage(err).
package cobracmd
import (
"errors"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
)
// Exit codes, matching core/doctor's.
const (
ExitOK = 0
ExitProblem = 1
ExitUsage = 2
)
// Shells are the shells "completion" accepts.
var Shells = []string{"bash", "zsh", "fish", "powershell"}
// UsageError marks an error as a usage error (exit 2).
type UsageError struct{ Err error }
func (e *UsageError) Error() string { return e.Err.Error() }
func (e *UsageError) Unwrap() error { return e.Err }
// Usage wraps err as a usage error; nil stays nil.
func Usage(err error) error {
if err == nil {
return nil
}
return &UsageError{Err: err}
}
// cobraUsage are the prefixes of the usage errors cobra and pflag
// produce themselves (unknown command, argument validators, flags).
var cobraUsage = []string{
"unknown command ",
"unknown flag: ",
"unknown shorthand flag: ",
"flag needs an argument: ",
"invalid argument ",
"bad flag syntax: ",
"required flag(s) ",
"if any flags in the group ",
"accepts ",
"requires at least ",
"requires at most ",
}
// IsUsage reports whether err is a usage error: wrapped with Usage, or
// one of cobra's/pflag's own argument and flag errors.
func IsUsage(err error) bool {
if err == nil {
return false
}
var u *UsageError
if errors.As(err, &u) {
return true
}
msg := err.Error()
for _, p := range cobraUsage {
if strings.HasPrefix(msg, p) {
return true
}
}
return false
}
// Execute runs root and returns the exit code: 0, 2 for a usage error,
// 1 for any other error. cobra prints the error itself unless the
// command sets SilenceErrors.
//
// Before running, it makes every command group below root strict (see
// StrictGroups): cobra itself rejects an unknown subcommand only at the
// root ("prog nosuch"), while "prog group nosuch" printed the group's
// help and exited 0.
func Execute(root *cobra.Command) int {
StrictGroups(root)
err := root.Execute()
switch {
case err == nil:
return ExitOK
case IsUsage(err):
return ExitUsage
default:
return ExitProblem
}
}
// StrictGroups makes every command below root that only groups
// subcommands (it has subcommands, no Run/RunE and no Args of its own)
// reject an unknown subcommand as a usage error; called without one it
// still prints its help (exit 0). Execute calls it; it is exported for
// programs that run root.Execute themselves.
func StrictGroups(root *cobra.Command) {
var walk func(c *cobra.Command)
walk = func(c *cobra.Command) {
for _, sub := range c.Commands() {
if sub.HasSubCommands() && !sub.Runnable() && sub.Args == nil {
sub.Args = func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return Usage(fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()))
}
return nil
}
sub.RunE = func(cmd *cobra.Command, _ []string) error { return cmd.Help() }
}
walk(sub)
}
}
walk(root)
}
// Completion replaces cobra's default completion command on root with
// "completion <bash|zsh|fish|powershell>": exactly one argument, one of
// Shells; anything else is a usage error. The script is cobra's own
// (subcommands and flags, with descriptions), preceded by its install
// line.
func Completion(root *cobra.Command) {
root.CompletionOptions.DisableDefaultCmd = true
for _, c := range root.Commands() {
if c.Name() == "completion" {
root.RemoveCommand(c)
}
}
name := root.Name()
root.AddCommand(&cobra.Command{
Use: "completion <" + strings.Join(Shells, "|") + ">",
Short: "Print a shell completion script",
Long: installHelp(name),
ValidArgs: Shells,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return Usage(fmt.Errorf("%s completion: exactly one shell expected (%s)", name, strings.Join(Shells, ", ")))
}
for _, s := range Shells {
if args[0] == s {
return nil
}
}
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, args[0], strings.Join(Shells, ", ")))
},
DisableFlagsInUseLine: true,
RunE: func(cmd *cobra.Command, args []string) error {
return Script(root, args[0], cmd.OutOrStdout())
},
})
}
// Script writes root's completion script for shell to w.
func Script(root *cobra.Command, shell string, w io.Writer) error {
name := root.Name()
switch shell {
case "bash":
fmt.Fprintf(w, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", name, name)
return root.GenBashCompletionV2(w, true)
case "zsh":
// cobra's script starts with "#compdef", which must stay the
// first line for zsh's fpath autoloading.
if err := root.GenZshCompletion(w); err != nil {
return err
}
_, err := fmt.Fprintf(w, "# Install with: source <(%s completion zsh) (after compinit)\n", name)
return err
case "fish":
fmt.Fprintf(w, "# %s fish completion. Install with:\n# %s completion fish | source\n", name, name)
return root.GenFishCompletion(w, true)
case "powershell":
fmt.Fprintf(w, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", name, name)
return root.GenPowerShellCompletionWithDesc(w)
default:
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, shell, strings.Join(Shells, ", ")))
}
}
func installHelp(name string) string {
return fmt.Sprintf(`Print a completion script for bash, zsh, fish or PowerShell.
eval "$(%[1]s completion bash)" # ~/.bashrc
source <(%[1]s completion zsh) # ~/.zshrc, after compinit
%[1]s completion fish | source # ~/.config/fish/config.fish
%[1]s completion powershell | Out-String | Invoke-Expression # $PROFILE`, name)
}
+113
View File
@@ -0,0 +1,113 @@
package cobracmd
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
)
func newRoot() *cobra.Command {
root := &cobra.Command{Use: "yatool", SilenceUsage: true, SilenceErrors: true}
root.AddCommand(&cobra.Command{Use: "serve", RunE: func(*cobra.Command, []string) error { return nil }})
root.AddCommand(&cobra.Command{Use: "one <arg>", Args: cobra.ExactArgs(1), RunE: func(*cobra.Command, []string) error { return nil }})
root.AddCommand(&cobra.Command{Use: "fail", RunE: func(*cobra.Command, []string) error { return errors.New("broken") }})
root.AddCommand(&cobra.Command{Use: "bad", RunE: func(*cobra.Command, []string) error { return Usage(errors.New("wrong")) }})
group := &cobra.Command{Use: "queue", Short: "queue commands"}
group.AddCommand(&cobra.Command{Use: "list", RunE: func(*cobra.Command, []string) error { return nil }})
root.AddCommand(group)
Completion(root)
return root
}
func run(args ...string) (int, string) {
root := newRoot()
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs(args)
return Execute(root), out.String()
}
func TestExitCodes(t *testing.T) {
for _, tc := range []struct {
args []string
want int
}{
{[]string{"serve"}, ExitOK},
{[]string{"fail"}, ExitProblem},
{[]string{"bad"}, ExitUsage},
{[]string{"nosuch"}, ExitUsage},
{[]string{"serve", "--nosuch"}, ExitUsage},
{[]string{"one"}, ExitUsage},
{[]string{"one", "a", "b"}, ExitUsage},
{[]string{"completion"}, ExitUsage},
{[]string{"completion", "tcsh"}, ExitUsage},
{[]string{"completion", "bash", "zsh"}, ExitUsage},
{[]string{"queue"}, ExitOK},
{[]string{"queue", "list"}, ExitOK},
{[]string{"queue", "nosuch"}, ExitUsage},
{[]string{"queue", "--nosuch"}, ExitUsage},
} {
if got, out := run(tc.args...); got != tc.want {
t.Errorf("%v: exit %d, want %d (%s)", tc.args, got, tc.want, out)
}
}
}
func TestCompletionScripts(t *testing.T) {
for shell, want := range map[string][]string{
"bash": {`eval "$(yatool completion bash)"`, "__start_yatool"},
"zsh": {"#compdef yatool", "source <(yatool completion zsh)"},
"fish": {"yatool completion fish | source", "complete -c yatool"},
"powershell": {"Invoke-Expression", "Register-ArgumentCompleter"},
} {
code, out := run("completion", shell)
if code != ExitOK {
t.Fatalf("%s: exit %d", shell, code)
}
for _, w := range want {
if !strings.Contains(out, w) {
t.Errorf("%s script lacks %q", shell, w)
}
}
}
if _, out := run("completion", "zsh"); !strings.HasPrefix(out, "#compdef") {
t.Errorf("zsh script must start with #compdef: %.40q", out)
}
}
func TestCompletionReplacesDefault(t *testing.T) {
root := newRoot()
n := 0
for _, c := range root.Commands() {
if c.Name() == "completion" {
n++
}
}
if n != 1 {
t.Fatalf("%d completion commands, want 1", n)
}
// Calling it twice (e.g. a shared root builder) still leaves one.
Completion(root)
n = 0
for _, c := range root.Commands() {
if c.Name() == "completion" {
n++
}
}
if n != 1 {
t.Fatalf("after a second Completion: %d completion commands, want 1", n)
}
}
func TestIsUsage(t *testing.T) {
if IsUsage(nil) || IsUsage(errors.New("disk full")) {
t.Error("plain errors are no usage errors")
}
if !IsUsage(Usage(errors.New("x"))) || Usage(nil) != nil {
t.Error("Usage wrapping")
}
}
+10
View File
@@ -0,0 +1,10 @@
module yetano.dev/yetano/core/cobracmd
go 1.25.0
require github.com/spf13/cobra v1.10.2
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect
)
+10
View File
@@ -0,0 +1,10 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+165
View File
@@ -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# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\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
}
+50
View File
@@ -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)
}
}
+18
View File
@@ -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,9 +162,26 @@ 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 }
// Filename returns the configuration file name this Resolver searches
// for in every layer.
func (r *Resolver) Filename() string { return r.filename }
// Paths returns the core/paths Resolver this Resolver locates its
// directories with (same application, environment and options), for a
// caller that also needs another category, e.g. DataDir for defaults
// derived from it.
func (r *Resolver) Paths() *paths.Resolver { return r.paths }
+75
View File
@@ -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
View File
@@ -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,
})
+1 -13
View File
@@ -25,19 +25,7 @@ func mergeMaps(base, over map[string]any) map[string]any {
if base == nil {
base = map[string]any{}
}
for k, v := range over {
if v == nil {
delete(base, k)
continue
}
if overMap, ok := v.(map[string]any); ok {
if baseMap, ok := base[k].(map[string]any); ok {
base[k] = mergeMaps(baseMap, overMap)
continue
}
}
base[k] = v
}
mergeTracked(base, over, "", "", nil)
return base
}
+42
View File
@@ -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)
}
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
)
// Source is one input of Merge: a parsed YAML mapping and the name of
// where it came from (a file path, "path [section]", "default", ...),
// which Merge records as the origin of every value it contributes.
type Source struct {
Name string
Data map[string]any
}
// Origins maps the dotted path of every leaf of a merged configuration
// ("storage.inbound.root") to the Name of the Source that set it. A
// leaf is any value that is not a mapping: scalars and lists alike,
// since a list is replaced as a whole, never merged element by element.
type Origins map[string]string
// Merge overlays sources lowest priority first, with the same semantics
// as LoadMerged (see mergeMaps: maps merge key by key, scalars and lists
// are replaced, an explicit null removes the key), and returns the
// merged mapping together with the origin of each of its leaves. The
// sources' maps are not modified.
func Merge(sources ...Source) (map[string]any, Origins) {
merged := map[string]any{}
origins := Origins{}
for _, s := range sources {
mergeTracked(merged, s.Data, "", s.Name, origins)
}
return merged, origins
}
// ReadFile reads path and parses it as a YAML mapping (an empty file is
// an empty mapping). Unlike LoadMerged's layers, a missing file is an
// error: the caller asked for this file.
func ReadFile(path string) (map[string]any, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: read %s: %w", path, err)
}
var m map[string]any
if err := yaml.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("config: parse %s: %w", path, err)
}
if m == nil {
m = map[string]any{}
}
return m, nil
}
// mergeTracked overlays over onto base in place, recording the origin
// of every leaf it sets in origins (nil: not tracked).
func mergeTracked(base, over map[string]any, prefix, name string, origins Origins) {
for k, v := range over {
key := joinKey(prefix, k)
if v == nil {
delete(base, k)
origins.drop(key)
continue
}
if overMap, ok := v.(map[string]any); ok {
baseMap, ok := base[k].(map[string]any)
if !ok {
origins.drop(key)
baseMap = map[string]any{}
base[k] = baseMap
}
mergeTracked(baseMap, overMap, key, name, origins)
continue
}
origins.drop(key)
base[k] = v
if origins != nil {
origins[key] = name
}
}
}
// drop forgets the origin of key and of everything below it.
func (o Origins) drop(key string) {
delete(o, key)
prefix := key + "."
for k := range o {
if strings.HasPrefix(k, prefix) {
delete(o, k)
}
}
}
func joinKey(prefix, k string) string {
if prefix == "" {
return k
}
return prefix + "." + k
}
+106
View File
@@ -0,0 +1,106 @@
package config
import (
"os"
"path/filepath"
"reflect"
"testing"
)
func TestMergeTracksOrigins(t *testing.T) {
low := Source{Name: "system", Data: map[string]any{
"hostname": "mail.example.org",
"tls": map[string]any{"cert-file": "a.crt", "key-file": "a.key"},
"secrets": []any{"one", "two"},
"limits": map[string]any{"max": 10},
"drop": "me",
}}
high := Source{Name: "program", Data: map[string]any{
"tls": map[string]any{"cert-file": "b.crt"},
"secrets": []any{"three"},
"limits": "flat",
"drop": nil,
}}
merged, origins := Merge(low, high)
want := map[string]any{
"hostname": "mail.example.org",
"tls": map[string]any{"cert-file": "b.crt", "key-file": "a.key"},
"secrets": []any{"three"},
"limits": "flat",
}
if !reflect.DeepEqual(merged, want) {
t.Errorf("merged = %#v\nwant %#v", merged, want)
}
wantOrigins := Origins{
"hostname": "system",
"tls.cert-file": "program",
"tls.key-file": "system",
"secrets": "program",
"limits": "program",
}
if !reflect.DeepEqual(origins, wantOrigins) {
t.Errorf("origins = %#v\nwant %#v", origins, wantOrigins)
}
}
func TestMergeMapReplacesScalarAndBack(t *testing.T) {
merged, origins := Merge(
Source{Name: "a", Data: map[string]any{"x": "scalar"}},
Source{Name: "b", Data: map[string]any{"x": map[string]any{"y": 1}}},
)
if !reflect.DeepEqual(merged, map[string]any{"x": map[string]any{"y": 1}}) {
t.Errorf("merged = %#v", merged)
}
if !reflect.DeepEqual(origins, Origins{"x.y": "b"}) {
t.Errorf("origins = %#v", origins)
}
merged, origins = Merge(
Source{Name: "a", Data: map[string]any{"x": map[string]any{"y": 1, "z": 2}}},
Source{Name: "b", Data: map[string]any{"x": "scalar"}},
)
if !reflect.DeepEqual(merged, map[string]any{"x": "scalar"}) {
t.Errorf("merged = %#v", merged)
}
if !reflect.DeepEqual(origins, Origins{"x": "b"}) {
t.Errorf("origins = %#v", origins)
}
}
func TestMergeNullRemovesSubtree(t *testing.T) {
merged, origins := Merge(
Source{Name: "a", Data: map[string]any{"x": map[string]any{"y": 1, "z": 2}, "w": 3}},
Source{Name: "b", Data: map[string]any{"x": nil}},
)
if !reflect.DeepEqual(merged, map[string]any{"w": 3}) {
t.Errorf("merged = %#v", merged)
}
if !reflect.DeepEqual(origins, Origins{"w": "a"}) {
t.Errorf("origins = %#v", origins)
}
}
func TestMergeDoesNotModifySources(t *testing.T) {
inner := map[string]any{"y": 1}
low := Source{Name: "a", Data: map[string]any{"x": inner}}
Merge(low, Source{Name: "b", Data: map[string]any{"x": map[string]any{"z": 2}}})
if !reflect.DeepEqual(inner, map[string]any{"y": 1}) {
t.Errorf("source map modified: %#v", inner)
}
}
func TestReadFile(t *testing.T) {
dir := t.TempDir()
if _, err := ReadFile(filepath.Join(dir, "missing.yaml")); err == nil {
t.Error("ReadFile of a missing file succeeded")
}
empty := filepath.Join(dir, "empty.yaml")
if err := os.WriteFile(empty, nil, 0o644); err != nil {
t.Fatal(err)
}
m, err := ReadFile(empty)
if err != nil || m == nil || len(m) != 0 {
t.Errorf("ReadFile(empty) = %#v, %v; want empty map", m, err)
}
}
+499
View File
@@ -0,0 +1,499 @@
// 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
// <program> config show [--json] [--show-secrets]
//
// 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.
//
// "config show" prints the configuration with the origin of every value.
// A program merged from several inputs (a family-wide file, a section
// of it, its own file) sets Spec.Layered so that path, validate and show
// work on all of them (see Layered).
//
// 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", "upgrade", "show" and Doctor
// 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
// Layered, when set, makes path, validate and show work on a
// configuration merged from several inputs (see Layered); create
// and upgrade still work on Filename. nil: the program reads the
// single file Find selects.
Layered *Layered
}
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", "show":
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":
if s.Layered != nil {
if code := parse(s.newFlagSet("validate", stderr), rest); code >= 0 {
return code
}
return s.layeredValidate(explicit, stdout, stderr)
}
return s.validate(explicit, rest, stdout, stderr)
case "upgrade":
return s.upgrade(explicit, rest, stdout, stderr)
case "path":
if s.Layered != nil {
if code := parse(s.newFlagSet("path", stderr), rest); code >= 0 {
return code
}
return s.layeredPath(explicit, stdout, stderr)
}
return s.path(explicit, rest, stdout, stderr)
case "show":
return s.show(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", "show"}
func usage(s Spec, w io.Writer) {
pathHelp := "list the locations searched for " + s.filename() + ", highest priority first"
if s.Layered != nil {
pathHelp = "list every configuration layer, highest priority first"
}
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 %[3]s
show [--json] [--show-secrets]
print the configuration with the file every value comes from;
secrets are redacted unless --show-secrets
`, s.Name, s.filename(), pathHelp)
}
// 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
}
+429
View File
@@ -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)
}
}
+316
View File
@@ -0,0 +1,316 @@
package configcmd
import (
"errors"
"fmt"
"io"
"strings"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/doctor"
"yetano.dev/yetano/core/paths"
)
// Layered describes a program whose configuration is merged from
// several inputs that are not one file name per directory -- e.g. a
// family-wide file, one section of it and a per-program file in every
// tier (the yamase family, yamase ADR-0074). With Spec.Layered set,
// "config path", "config validate" and "config show" work on all
// layers; "config create" and "config upgrade" keep working on the
// program's own file (Spec.Filename).
//
// Unknown options are warnings for a layered program, not problems:
// files shared between programs (of different versions) legitimately
// carry options one program does not read.
type Layered struct {
// Layers lists every input, highest priority first, whether it
// exists or not (for "config path" and doctor). explicit is the
// --config value.
Layers func(explicit string) ([]LayerInfo, error)
// Load merges the existing layers. With none at all it returns an
// error wrapping ErrNotFound.
Load func(explicit string) (*Effective, error)
// Unknown reports the unknown options of e's layers. nil: every
// existing layer's file is checked against Spec.Schema.
Unknown func(e *Effective) ([]UnknownKey, error)
// Validate parses and validates the merged configuration (YAML) the
// way the program does at startup, including files it names. For an
// Optional program without any file it gets nil (the defaults).
Validate func(merged []byte) error
// Used reports whether the program reads the option key, for "config
// show". nil: KnownKey(Spec.Schema, key).
Used func(key string) bool
}
// LayerInfo is one input of a layered configuration.
type LayerInfo struct {
// Name is how the layer is shown and recorded as an origin: the
// path, plus e.g. " [section]" for a part of a file.
Name string
// Path is the file that holds it.
Path string
// Source names the tier ("system-directory", "--config", ...).
Source string
// Exists reports whether the layer contributes anything.
Exists bool
}
// Effective is a merged configuration: its layers, the merged mapping
// and the origin (LayerInfo.Name, or a default's name) of every leaf.
type Effective struct {
// Name is the program's name, for "config show"'s header.
Name string
// Layers are all layers, highest priority first.
Layers []LayerInfo
Merged map[string]any
Origins coreconfig.Origins
// Loader is the Layered loader's own value for this configuration
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
Loader any
}
// Used returns the layers that contributed, highest priority first.
func (e *Effective) Used() []LayerInfo {
var out []LayerInfo
for _, l := range e.Layers {
if l.Exists {
out = append(out, l)
}
}
return out
}
// Describe names the layers that contributed, lowest priority first
// ("a.yaml + b.yaml [section]"), for log lines and messages.
func (e *Effective) Describe() string {
used := e.Used()
names := make([]string, len(used))
for i, l := range used {
names[len(used)-1-i] = l.Name
}
return strings.Join(names, " + ")
}
// YAML returns the merged configuration as YAML, for the program's own
// parser.
func (e *Effective) YAML() ([]byte, error) {
data, err := yaml.Marshal(e.Merged)
if err != nil {
return nil, fmt.Errorf("config: marshal merged configuration: %w", err)
}
return data, nil
}
// effective loads the configuration "config show" and Doctor report:
// Layered.Load, or else the single file Find selects as the only layer.
func (s Spec) effective(explicit string) (*Effective, error) {
if s.Layered != nil {
return s.Layered.Load(explicit)
}
file, err := s.Find(explicit)
if err != nil {
return nil, err
}
data, err := coreconfig.ReadFile(file.Path)
if err != nil {
return nil, err
}
merged, origins := coreconfig.Merge(coreconfig.Source{Name: file.Path, Data: data})
src := file.Source.String()
return &Effective{
Name: s.Name,
Layers: []LayerInfo{{Name: file.Path, Path: file.Path, Source: src, Exists: true}},
Merged: merged,
Origins: origins,
}, nil
}
// UnknownIn returns the unknown options of e's layers: Layered.Unknown
// if set, else every existing layer's file against s.Schema.
func (s Spec) UnknownIn(e *Effective) ([]UnknownKey, error) {
if s.Layered != nil && s.Layered.Unknown != nil {
return s.Layered.Unknown(e)
}
if s.Schema == nil {
return nil, nil
}
var out []UnknownKey
for i := len(e.Layers) - 1; i >= 0; i-- {
l := e.Layers[i]
if !l.Exists {
continue
}
keys, err := UnknownKeysFile(l.Path, s.Schema)
if err != nil {
return nil, err
}
for _, k := range keys {
k.Layer = l.Name
out = append(out, k)
}
}
return out, nil
}
func (s Spec) layeredPath(explicit string, stdout, stderr io.Writer) int {
layers, err := s.Layered.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"
if l.Exists {
mark, state, found = "*", "used", true
}
fmt.Fprintf(stdout, "%s %s (%s, %s)\n", mark, l.Name, l.Source, state)
}
if !found {
fmt.Fprintf(stdout, "no configuration file found -- \"%s config create\" writes one\n", s.Name)
}
return ExitOK
}
func (s Spec) layeredValidate(explicit string, stdout, stderr io.Writer) int {
e, err := s.Layered.Load(explicit)
if err != nil && s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
if s.Layered.Validate != nil {
if err := s.Layered.Validate(nil); 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
}
if err != nil {
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
return ExitProblem
}
unknown, err := s.UnknownIn(e)
if err != nil {
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
return ExitProblem
}
for _, k := range unknown {
fmt.Fprintf(stdout, "warning: unknown option %s (%s, line %d), ignored -- the default applies\n", k.Key, k.Layer, k.Line)
}
if s.Layered.Validate != nil {
data, err := e.YAML()
if err == nil {
err = s.Layered.Validate(data)
}
if err != nil {
fmt.Fprintf(stderr, "%s config validate: %s: %v\n", s.Name, e.Describe(), err)
return ExitProblem
}
}
fmt.Fprintf(stdout, "%s: valid\n", e.Describe())
return ExitOK
}
func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int {
fs := s.newFlagSet("show", stderr)
asJSON := fs.Bool("json", false, "print a JSON array of {key, value, source, used}")
secrets := fs.Bool("show-secrets", false, "print secret values instead of <redacted>")
if code := parse(fs, args); code >= 0 {
return code
}
e, err := s.effective(explicit)
if err != nil {
if s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults\n", s.Name)
return ExitOK
}
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
return ExitProblem
}
used := s.usedFunc()
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
return ExitProblem
}
return ExitOK
}
// usedFunc is Layered.Used, else KnownKey against the schema (every key
// counts as used without one).
func (s Spec) usedFunc() func(string) bool {
if s.Layered != nil && s.Layered.Used != nil {
return s.Layered.Used
}
if s.Schema == nil {
return nil
}
return func(key string) bool { return KnownKey(s.Schema, key) }
}
// Doctor records the program's core/paths locations and every
// configuration layer in r, checks that the configuration loads and has
// no unknown options, and returns it (nil when it does not load).
// Nothing is created. A layered program's unknown options are reported
// as a failed check like any program's: doctor is where an operator
// looks for them.
func Doctor(r *doctor.Report, s Spec, explicit string) *Effective {
r.AddPaths(s.App)
if s.Layered != nil {
layers, err := s.Layered.Layers(explicit)
if err != nil {
r.AddPath("config search", "", err)
}
for _, l := range layers {
name := "config search (" + l.Source + ")"
if l.Exists {
name = "config file (" + l.Source + ")"
}
r.AddPath(name, l.Name, nil)
}
} else if layers, err := s.Layers(explicit); err != nil {
r.AddPath("config search", "", err)
} else {
for _, l := range layers {
src := l.Source.String()
if l.Source == paths.APIOverride {
src = "--config"
}
r.AddPath("config search ("+src+")", l.Path, nil)
}
}
e, err := s.effective(explicit)
if err != nil && s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
r.Check("config file found", true, "none, "+s.Name+" runs on its built-in defaults")
return nil
}
if err != nil {
note := err.Error()
if errors.Is(err, ErrNotFound) {
note = "none of the searched files exists; pass --config <file> or run \"" + s.Name + " config create\""
}
r.Check("config file found", false, note)
return nil
}
r.Check("config file found", true, e.Describe())
if s.Schema != nil || (s.Layered != nil && s.Layered.Unknown != nil) {
unknown, err := s.UnknownIn(e)
switch {
case err != nil:
r.Check("config has no unknown options", false, err.Error())
case len(unknown) == 0:
r.Check("config has no unknown options", true, "")
default:
parts := make([]string, len(unknown))
for i, k := range unknown {
parts[i] = k.String()
}
r.Check("config has no unknown options", false, "ignored, the defaults apply: "+strings.Join(parts, ", "))
}
}
return e
}
+213
View File
@@ -0,0 +1,213 @@
package configcmd
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/doctor"
)
func TestShowSingleFile(t *testing.T) {
root := t.TempDir()
s := testSpec(root)
file := filepath.Join(root, "etc", "yamase", "yamase-test.yaml")
writeFile(t, file, minimalTemplate+"log-level: debug\nunread: 1\n")
code, out, errOut := run(t, s, "", "show")
if code != ExitOK {
t.Fatalf("show: exit %d: %s", code, errOut)
}
for _, want := range []string{
`log-level: "debug"`,
"# " + file,
`root: "/var/lib/yamase/queue"`,
"unread: 1",
"not used by yamase-test",
} {
if !strings.Contains(out, want) {
t.Errorf("show output lacks %q:\n%s", want, out)
}
}
code, out, _ = run(t, s, "", "show", "--json")
var values []Value
if code != ExitOK || json.Unmarshal([]byte(out), &values) != nil || len(values) == 0 {
t.Errorf("show --json: exit %d, output %q", code, out)
}
}
// fakeLayered serves two layers of one directory, as a family-wide file
// plus a program file.
func fakeLayered(dir string) *Layered {
shared := filepath.Join(dir, "family.yaml")
own := filepath.Join(dir, "own.yaml")
layers := func(string) ([]LayerInfo, error) {
return []LayerInfo{
{Name: own, Path: own, Source: "test", Exists: statOK(own)},
{Name: shared, Path: shared, Source: "test", Exists: statOK(shared)},
}, nil
}
return &Layered{
Layers: layers,
Load: func(explicit string) (*Effective, error) {
ls, _ := layers(explicit)
var sources []coreconfig.Source
for i := len(ls) - 1; i >= 0; i-- {
if !ls[i].Exists {
continue
}
data, err := coreconfig.ReadFile(ls[i].Path)
if err != nil {
return nil, err
}
sources = append(sources, coreconfig.Source{Name: ls[i].Name, Data: data})
}
if len(sources) == 0 {
return nil, ErrNotFound
}
merged, origins := coreconfig.Merge(sources...)
return &Effective{Name: "yamase-test", Layers: ls, Merged: merged, Origins: origins}, nil
},
Validate: func(merged []byte) error {
var s schema
if err := yaml.Unmarshal(merged, &s); err != nil {
return err
}
if len(s.Listen) == 0 {
return errNoListener
}
return nil
},
}
}
type testErr string
func (e testErr) Error() string { return string(e) }
const errNoListener = testErr("listen: at least one listener is required")
func statOK(path string) bool { return statExistsForTest(path) }
func TestLayered(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "cfg")
s := testSpec(root)
s.Layered = fakeLayered(dir)
if code, out, _ := run(t, s, "", "path"); code != ExitOK || !strings.Contains(out, "no configuration file found") {
t.Errorf("path without files: exit %d, %q", code, out)
}
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, ErrNotFound.Error()) {
t.Errorf("validate without files: exit %d, %q", code, errOut)
}
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\nlisten:\n - address: \":25\"\n")
writeFile(t, filepath.Join(dir, "own.yaml"), "log-level: debug\nlog-levle: x\n")
code, out, _ := run(t, s, "", "path")
if code != ExitOK || strings.Count(out, "(test, used)") != 2 {
t.Errorf("path: exit %d, %q", code, out)
}
// Unknown options are warnings for a layered program.
code, out, errOut := run(t, s, "", "validate")
if code != ExitOK || !strings.Contains(out, "warning: unknown option log-levle ("+filepath.Join(dir, "own.yaml")+", line 2)") || !strings.Contains(out, ": valid") {
t.Errorf("validate: exit %d, stdout %q, stderr %q", code, out, errOut)
}
code, out, _ = run(t, s, "", "show")
if code != ExitOK || !strings.Contains(out, `log-level: "debug"`) || !strings.Contains(out, "# "+filepath.Join(dir, "family.yaml")) {
t.Errorf("show: exit %d:\n%s", code, out)
}
if !strings.Contains(out, "layers, lowest priority first: "+filepath.Join(dir, "family.yaml")+" + "+filepath.Join(dir, "own.yaml")) {
t.Errorf("show header:\n%s", out)
}
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\n")
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "listen") {
t.Errorf("validate of an invalid merge: exit %d, %q", code, errOut)
}
}
func TestDoctor(t *testing.T) {
root := t.TempDir()
s := testSpec(root)
r := doctor.Report{Program: "yamase-test"}
if e := Doctor(&r, s, ""); e != nil {
t.Error("Doctor without a file returned a configuration")
}
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-levle: x\n")
r = doctor.Report{Program: "yamase-test"}
e := Doctor(&r, s, "")
if e == nil {
t.Fatal("Doctor with a file returned nil")
}
var out bytes.Buffer
r.Run([]string{"--json"}, &out, &out)
if !strings.Contains(out.String(), "log-levle (") || !strings.Contains(out.String(), "config file found") {
t.Errorf("doctor report = %s", out.String())
}
}
func TestValuesRedaction(t *testing.T) {
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
"srs": map[string]any{"secrets": []any{"plain", "env:X", "base64:abc"}},
"yaais": map[string]any{"token": "file:/run/t", "password": "hunter2"},
}})
e := &Effective{Name: "p", Merged: merged, Origins: origins}
got := map[string]any{}
for _, v := range e.Values(nil, false) {
got[v.Key] = v.Value
}
want := map[string]any{
"srs.secrets": []any{"<redacted>", "env:X", "<redacted>"},
"yaais.token": "file:/run/t",
"yaais.password": "<redacted>",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Values = %v, want %v", got, want)
}
}
type inlineBase struct {
Enabled bool `yaml:"enabled"`
}
func TestKnownKey(t *testing.T) {
type cfg struct {
Throttle struct {
inlineBase `yaml:",inline"`
Window string `yaml:"window"`
} `yaml:"throttle"`
Listen []struct {
Address string `yaml:"address"`
} `yaml:"listen"`
Backends map[string]struct{ Root string } `yaml:"backends"`
Custom selfDecoding `yaml:"custom"`
}
for key, want := range map[string]bool{
"throttle.enabled": true,
"throttle.window": true,
"throttle.nope": false,
"listen[0].address": true,
"listen[].address": true,
"backends.any.root": true,
"backends.any.nope": false,
"custom.anything": true,
"missing": false,
} {
if got := KnownKey(cfg{}, key); got != want {
t.Errorf("KnownKey(%q) = %v, want %v", key, got, want)
}
}
}
func statExistsForTest(path string) bool {
_, err := os.Stat(path)
return err == nil
}
+174
View File
@@ -0,0 +1,174 @@
package configcmd
import (
"encoding/json"
"fmt"
"io"
"reflect"
"regexp"
"sort"
"strings"
)
// Value is one leaf of a merged configuration, as "config show" reports
// it.
type Value struct {
Key string `json:"key"`
Value any `json:"value"`
Source string `json:"source"`
// Used reports whether the program reads this option; an option in a
// shared file that only other programs read has Used false.
Used bool `json:"used"`
}
// DefaultOrigin is the origin of a leaf no layer set (a value a loader
// filled in).
const DefaultOrigin = "default"
// Values returns every leaf of e, sorted by key, with its origin.
// used reports whether the program reads a key (nil: every key); a
// default it does not read is left out. Secret values (keys secrets,
// secret, token, password) are replaced by "<redacted>" unless
// showSecrets; a reference that only says where a secret is (env:,
// file:, secret://) is shown.
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
var out []Value
walkLeaves("", e.Merged, func(key string, v any) {
source := e.Origins[key]
if source == "" {
source = DefaultOrigin
}
u := used == nil || used(key)
if !u && source == DefaultOrigin {
return
}
if !showSecrets && isSecretKey(key) {
v = redact(v)
}
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
})
return out
}
// Show writes the merged configuration: indented YAML with every
// value's origin as a comment, or with asJSON a JSON array of Values.
func (e *Effective) Show(w io.Writer, used func(string) bool, asJSON, showSecrets bool) error {
values := e.Values(used, showSecrets)
if asJSON {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
return enc.Encode(values)
}
fmt.Fprintf(w, "# %s: effective configuration\n# layers, lowest priority first: %s\n", e.Name, e.Describe())
var printed []string // the parent path last printed, by depth
for _, v := range values {
parts := strings.Split(v.Key, ".")
for depth, name := range parts[:len(parts)-1] {
if depth < len(printed) && printed[depth] == name {
continue
}
printed = append(printed[:depth], name)
fmt.Fprintf(w, "%s%s:\n", strings.Repeat(" ", depth), name)
}
printed = printed[:len(parts)-1]
line := fmt.Sprintf("%s%s: %s", strings.Repeat(" ", len(parts)-1), parts[len(parts)-1], renderValue(v.Value))
note := v.Source
if !v.Used {
note += ", not used by " + e.Name
}
fmt.Fprintf(w, "%s%s# %s\n", line, strings.Repeat(" ", max(44-len(line), 1)), note)
}
return nil
}
func walkLeaves(prefix string, m map[string]any, fn func(string, any)) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
key := k
if prefix != "" {
key = prefix + "." + k
}
if sub, ok := m[k].(map[string]any); ok && len(sub) > 0 {
walkLeaves(key, sub, fn)
continue
}
fn(key, m[k])
}
}
// renderValue formats a leaf as a single-line YAML value (JSON is a subset
// of YAML's flow style).
func renderValue(v any) string {
var b strings.Builder
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return fmt.Sprint(v)
}
return strings.TrimSuffix(b.String(), "\n")
}
var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true, "password": true}
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
// redact replaces secret values, keeping references that only say where
// the secret is.
func redact(v any) any {
switch x := v.(type) {
case string:
for _, ref := range []string{"env:", "file:", "secret://"} {
if strings.HasPrefix(x, ref) {
return x
}
}
return "<redacted>"
case []any:
out := make([]any, len(x))
for i, e := range x {
out[i] = redact(e)
}
return out
}
return "<redacted>"
}
// listIndex matches the "[n]" (or "[]") of a list entry in a dotted key.
var listIndex = regexp.MustCompile(`\[\d*\]`)
// KnownKey reports whether the dotted option key ("storage.inbound.root",
// "listen[0].address") exists in schema (a configuration struct) by its
// yaml tags. A map accepts any key; a list, an interface or a type that
// decodes itself accepts everything below it; an embedded ",inline"
// struct contributes its fields.
func KnownKey(schema any, key string) bool {
if schema == nil {
return false
}
return knownPath(reflect.TypeOf(schema), strings.Split(listIndex.ReplaceAllString(key, ""), "."))
}
func knownPath(t reflect.Type, path []string) bool {
t = deref(t)
if len(path) == 0 {
return true
}
if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) {
return true
}
switch t.Kind() {
case reflect.Struct:
ft, ok := fieldType(t, path[0])
return ok && knownPath(ft, path[1:])
case reflect.Map:
return knownPath(t.Elem(), path[1:])
case reflect.Interface, reflect.Slice, reflect.Array:
return true
}
return false
}
+152
View File
@@ -0,0 +1,152 @@
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
// Layer names the layer the key is in, for a layered configuration
// (LayerInfo.Name); "" for a single file.
Layer string
}
func (k UnknownKey) String() string {
if k.Layer != "" {
return fmt.Sprintf("%s (%s, line %d)", k.Key, k.Layer, k.Line)
}
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
}
// UnknownKeysNode is UnknownKeys for an already parsed mapping node
// (e.g. one section of a larger file): keys are reported relative to n,
// with their line in the original document.
func UnknownKeysNode(n *yaml.Node, schema any) []UnknownKey {
if n == nil || n.Kind != yaml.MappingNode || schema == nil {
return nil
}
var out []UnknownKey
walkUnknown(nil, reflect.TypeOf(schema), n, &out)
return out
}
// 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, ", ")
}
+126
View File
@@ -0,0 +1,126 @@
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{
{Key: "log-levle", Line: 2},
{Key: "listen[0].tsl", Line: 5},
{Key: "storage.mailstore.rot", Line: 9},
{Key: "backends.inbound.extra", Line: 11},
{Key: "throttle.enabeld", Line: 15},
{Key: "Ignored", Line: 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)
}
}
func TestUnknownKeysNode(t *testing.T) {
var doc yaml.Node
if err := yaml.Unmarshal([]byte("other: 1\nsection:\n log-level: info\n log-levle: debug\n"), &doc); err != nil {
t.Fatal(err)
}
section := doc.Content[0].Content[3]
got := UnknownKeysNode(section, testConfig{})
if len(got) != 1 || got[0].Key != "log-levle" || got[0].Line != 4 {
t.Errorf("UnknownKeysNode = %v, want log-levle on line 4 (relative key, document line)", got)
}
if got := UnknownKeysNode(nil, testConfig{}); got != nil {
t.Errorf("UnknownKeysNode(nil) = %v", got)
}
}
+321
View File
@@ -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
}
+218
View File
@@ -0,0 +1,218 @@
package configfamily
import (
"errors"
"flag"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/configcmd"
"yetano.dev/yetano/core/doctor"
"yetano.dev/yetano/core/paths"
)
// Spec is one program's part of the config command.
type Spec struct {
Program Program
// Optional says the program also runs without any configuration
// file, on built-in defaults: validate, show and doctor then report
// that instead of failing.
Optional bool
// Minimal is the template "config create" writes by default: what
// the program needs to start. Full is "config create --full",
// documenting every option the program reads; "config upgrade"
// offers its options a file does not mention yet.
Minimal, Full string
// Validate parses and validates the merged configuration (YAML, see
// Loaded.YAML) the same way the program does at startup. For an
// Optional program without a file it gets nil.
Validate func(merged []byte) error
// Schema is the program's configuration struct (e.g. config.Config{}):
// it enables unknown-option detection and tells "config show" which
// options the program reads.
Schema any
// Options are passed through to core/config; tests use them to
// inject a platform, environment and root.
Options []coreconfig.Option
}
// Core returns the core/configcmd Spec this Spec stands for: create and
// upgrade work on the program's own file, path, validate and show on
// all layers through core's Layered hook.
func (s Spec) Core() configcmd.Spec {
c := coreSpec(s.Program, s.Options)
c.Optional = s.Optional
c.Minimal, c.Full, c.Schema = s.Minimal, s.Full, s.Schema
c.Layered = &configcmd.Layered{
Layers: func(explicit string) ([]configcmd.LayerInfo, error) {
layers, err := Layers(s.Program, explicit, s.Options...)
if err != nil {
return nil, err
}
out := make([]configcmd.LayerInfo, len(layers))
for i, l := range layers {
out[i] = l.Info()
}
return out, nil
},
Load: func(explicit string) (*configcmd.Effective, error) {
l, err := s.Load(explicit)
if err != nil {
return nil, err
}
return l.Effective(), nil
},
Unknown: func(e *configcmd.Effective) ([]configcmd.UnknownKey, error) {
l, ok := e.Loader.(*Loaded)
if !ok || s.Schema == nil {
return nil, nil
}
return l.Unknown(s.Schema)
},
Validate: s.Validate,
Used: func(key string) bool {
return s.Schema == nil || configcmd.KnownKey(s.Schema, key)
},
}
return c
}
// Load is the package's Load for this program.
func (s Spec) Load(explicit string) (*Loaded, error) {
return Load(s.Program, explicit, s.Options...)
}
// Run serves "<program> config <args...>" and returns the exit code.
// explicit is the program's --config value ("" if not given). Only
// "create --shared" is this package's own; everything else is
// core/configcmd's.
func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
shared := s.Program.Family.SharedTemplate != ""
if len(args) > 0 && shared {
switch args[0] {
case "create":
if slices.Contains(args[1:], "--shared") || slices.Contains(args[1:], "-shared") {
return s.createShared(args[1:], stdout, stderr)
}
case "help", "-h", "-help", "--help":
configcmd.Run(s.Core(), explicit, args, stdout, stderr)
fmt.Fprintf(stdout, " create --shared [--force] [--output <file>]\n write a commented starter %s, the options the %s programs share\n", s.Program.Family.SharedFilename(), s.Program.Family.Name)
return configcmd.ExitOK
}
}
return configcmd.Run(s.Core(), explicit, args, stdout, stderr)
}
// Doctor is core/configcmd's Doctor for this program: it records the
// paths and every configuration layer in r, checks that the
// configuration loads and has no unknown options, and returns it (nil
// when there is none or it does not load).
func Doctor(r *doctor.Report, s Spec, explicit string) *Loaded {
e := configcmd.Doctor(r, s.Core(), explicit)
if e == nil {
return nil
}
l, _ := e.Loader.(*Loaded)
return l
}
// WarnUnknown logs every unknown option of every layer of l: the
// program keeps running with the defaults for those keys, but the
// operator sees why a setting has no effect.
func WarnUnknown(log *slog.Logger, l *Loaded, schema any) {
unknown, err := l.Unknown(schema)
if err != nil {
return // Load already read and parsed every file
}
for _, k := range unknown {
log.Warn("configuration: unknown option, ignored (the default applies)", "option", k.Key, "line", k.Line, "path", k.Layer)
}
}
// LogLayers logs the files l was merged from, lowest priority first.
func LogLayers(log *slog.Logger, l *Loaded) {
used := l.Used()
for i := len(used) - 1; i >= 0; i-- {
log.Info("configuration file", "path", used[i].Name(), "source", used[i].SourceName())
}
}
// createShared writes Family.SharedTemplate: to --output, else to the
// family file the program reads first, else into the user config
// directory -- the system one when running as root or without a home.
func (s Spec) createShared(args []string, stdout, stderr io.Writer) int {
name := s.Program.Name
fs := flag.NewFlagSet(name+" config create", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.Bool("shared", true, "write "+s.Program.Family.SharedFilename()+", the options the programs share")
force := fs.Bool("force", false, "overwrite an existing file")
output := fs.String("output", "", "write to this file")
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return configcmd.ExitOK
}
return configcmd.ExitUsage
}
if fs.NArg() != 0 {
fmt.Fprintf(stderr, "%s config create: unexpected argument %q\n", name, fs.Arg(0))
return configcmd.ExitUsage
}
path := *output
if path == "" {
layers, err := Layers(s.Program, "", s.Options...)
if err != nil {
fmt.Fprintf(stderr, "%s config create: %v\n", name, err)
return configcmd.ExitProblem
}
var user, system string
for _, l := range layers {
if l.Kind != SharedLayer {
continue
}
if l.Exists && path == "" {
path = l.Path
}
if l.Source == paths.SystemDirectory {
system = l.Path
} else if user == "" {
user = l.Path
}
}
if path == "" {
path = user
if os.Geteuid() == 0 || user == "" {
path = system
}
}
if path == "" {
fmt.Fprintf(stderr, "%s config create: no configuration directory known; pass --output <file>\n", name)
return configcmd.ExitProblem
}
}
if _, err := os.Stat(path); err == nil && !*force {
fmt.Fprintf(stderr, "%s config create: %s exists; pass --force to overwrite it\n", name, path)
return configcmd.ExitProblem
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
fmt.Fprintf(stderr, "%s config create: %v\n", name, err)
return configcmd.ExitProblem
}
// 0640: a configuration may name credentials files and should not be
// world-readable by default.
if err := os.WriteFile(path, []byte(s.Program.Family.SharedTemplate), 0o640); err != nil {
fmt.Fprintf(stderr, "%s config create: %v\n", name, err)
return configcmd.ExitProblem
}
fmt.Fprintf(stdout, "%s: wrote the shared configuration -- review it, then run \"%s config validate\"\n", path, name)
return configcmd.ExitOK
}
+111
View File
@@ -0,0 +1,111 @@
// Package configfamily locates and merges the configuration of a program
// that belongs to a family of programs sharing one set of config
// directories -- the yamase-* or yaiam-* programs (yamase ADR-0074). Each
// program is responsible for its own file; a family-wide file is
// optional and holds what several programs share.
//
// In each config directory of the family (core/config's tiers, without
// the working directory) a program reads:
//
// - <family>.yaml, its top level: options several programs share
// (storage, logging, ...), minus the program sections;
// - <family>.yaml, the program's section (its name without the
// "<family>-" prefix: "web:" for yaiam-web);
// - <program>.yaml, the program's own file.
//
// Load merges them lowest priority first -- system tier, then user tier,
// then the file --config names -- with core/config's merge rules (maps
// merge key by key, scalars and lists are replaced, null removes a key).
// The working directory is never read; no environment expansion is
// done. Parsing and validating the merged result stays with the program
// (Loaded.YAML), since its options are its own business.
//
// Spec and Run serve the standard "config" command on top of this: path,
// validate and show work on all layers, create and upgrade on the
// program's own file, and "config create --shared" writes the family
// file from Family.SharedTemplate.
package configfamily
import (
"slices"
"strings"
"yetano.dev/yetano/core"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/configcmd"
)
// ErrNotFound is returned (wrapped, with the searched files) by Load
// when no layer exists at all.
var ErrNotFound = configcmd.ErrNotFound
// Family describes a family of programs.
type Family struct {
// Name is the family's name: the core.Application name every
// program shares (it names the config directories) and the prefix
// of the program names ("yaiam" for yaiam-web).
Name string
// Programs are the section names of the family's programs in the
// family file ("web", "authd", ...). These top-level keys are never
// part of the shared layer.
Programs []string
// Shared is the schema (a struct value) of the options the family
// file holds at its top level. Its options are valid in every layer
// of every program, even one that does not read them. nil: none.
Shared any
// SharedTemplate is what "config create --shared" writes as the
// family file. "": the command is not offered.
SharedTemplate string
}
// SharedFilename is the family-wide file, "<Name>.yaml".
func (f Family) SharedFilename() string { return f.Name + ".yaml" }
// IsProgramSection reports whether key is a program section of the
// family file.
func (f Family) IsProgramSection(key string) bool { return slices.Contains(f.Programs, key) }
// IsSharedKey reports whether key (dotted) is an option of the family's
// shared schema.
func (f Family) IsSharedKey(key string) bool {
return f.Shared != nil && configcmd.KnownKey(f.Shared, key)
}
// Service returns the Program for a long-running service of the family.
// Scope stays at its UserScope default, so the user config dir is
// searched before the system one -- Kind and Scope are independent.
func (f Family) Service(name string) Program {
return Program{Family: f, App: core.Application{Name: f.Name, Kind: core.Service}, Name: name}
}
// CLI returns the Program for a command-line tool of the family.
func (f Family) CLI(name string) Program {
return Program{Family: f, App: core.Application{Name: f.Name, Kind: core.CLI}, Name: name}
}
// Program is one program of a family.
type Program struct {
Family Family
// App is the family-wide core.Application (Name is Family.Name);
// only its Kind differs between services and command-line tools.
App core.Application
// Name is the program's own name, e.g. "yaiam-web".
Name string
}
// Filename is the program's own file, "<Name>.yaml".
func (p Program) Filename() string { return p.Name + ".yaml" }
// Section is the key of the program's section in the family file: its
// name without the "<family>-" prefix.
func (p Program) Section() string { return strings.TrimPrefix(p.Name, p.Family.Name+"-") }
// coreSpec is core/configcmd's Spec for p's own file: the family
// directories without the working directory and "<Name>.yaml".
func coreSpec(p Program, opts []coreconfig.Option) configcmd.Spec {
opts = append(append([]coreconfig.Option(nil), opts...), coreconfig.WithWorkingDirectory(false))
return configcmd.Spec{Name: p.Name, App: p.App, Filename: p.Filename(), Options: opts}
}
+252
View File
@@ -0,0 +1,252 @@
package configfamily
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/doctor"
"yetano.dev/yetano/core/paths"
)
type sharedSchema struct {
Storage struct {
Path string `yaml:"path"`
} `yaml:"storage"`
LogLevel string `yaml:"log-level"`
}
type webSchema struct {
Listen string `yaml:"listen"`
Storage struct {
Path string `yaml:"path"`
} `yaml:"storage"`
}
var family = Family{
Name: "fam",
Programs: []string{"web", "authd"},
Shared: sharedSchema{},
SharedTemplate: "# shared\nlog-level: info\n",
}
func testOptions(root string) []coreconfig.Option {
return []coreconfig.Option{
coreconfig.WithEnvironment(map[string]string{"HOME": "/home/test"}),
coreconfig.WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
}
}
func testSpec(root string) Spec {
return Spec{
Program: family.Service("fam-web"),
Optional: true,
Minimal: "listen: \":8080\"\n",
Full: "listen: \":8080\"\nstorage:\n path: \"\"\n",
Validate: func(merged []byte) error {
var w webSchema
if err := yaml.Unmarshal(merged, &w); err != nil {
return err
}
if w.Listen == "bad" {
return errors.New("listen is bad")
}
return nil
},
Schema: webSchema{},
Options: testOptions(root),
}
}
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), 0o600); err != nil {
t.Fatal(err)
}
}
func dirs(root string) (system, user string) {
return filepath.Join(root, "etc", "fam"), filepath.Join(root, "home", "test", ".config", "fam")
}
func TestLayersOrder(t *testing.T) {
root := t.TempDir()
system, user := dirs(root)
writeFile(t, filepath.Join(user, "fam.yaml"), "web:\n listen: \":1\"\n")
explicit := filepath.Join(root, "explicit.yaml")
writeFile(t, explicit, "listen: \":2\"\n")
layers, err := Layers(family.Service("fam-web"), explicit, testOptions(root)...)
if err != nil {
t.Fatal(err)
}
want := []struct {
kind LayerKind
path string
ok bool
}{
{ExplicitLayer, explicit, true},
{ProgramLayer, filepath.Join(user, "fam-web.yaml"), false},
{SectionLayer, filepath.Join(user, "fam.yaml"), true},
{SharedLayer, filepath.Join(user, "fam.yaml"), true},
{ProgramLayer, filepath.Join(system, "fam-web.yaml"), false},
{SectionLayer, filepath.Join(system, "fam.yaml"), false},
{SharedLayer, filepath.Join(system, "fam.yaml"), false},
}
if len(layers) != len(want) {
t.Fatalf("got %d layers, want %d: %+v", len(layers), len(want), layers)
}
for i, w := range want {
l := layers[i]
if l.Kind != w.kind || l.Path != w.path || l.Exists != w.ok {
t.Errorf("layer %d = %+v, want kind %d path %s exists %v", i, l, w.kind, w.path, w.ok)
}
}
if _, err := Layers(family.Service("fam-web"), filepath.Join(root, "missing.yaml"), testOptions(root)...); err == nil {
t.Error("a missing --config file is not an error")
}
}
func TestLoadMergesByPriority(t *testing.T) {
root := t.TempDir()
system, user := dirs(root)
writeFile(t, filepath.Join(system, "fam.yaml"),
"log-level: info\nstorage:\n path: /var/lib/fam/db\nweb:\n listen: \":1\"\nauthd:\n listen: \":9\"\n")
writeFile(t, filepath.Join(system, "fam-web.yaml"), "listen: \":2\"\n")
writeFile(t, filepath.Join(user, "fam.yaml"), "log-level: debug\n")
l, err := Load(family.Service("fam-web"), "", testOptions(root)...)
if err != nil {
t.Fatal(err)
}
if got := l.Merged["listen"]; got != ":2" {
t.Errorf("listen = %v, want the program file's :2 over the section's :1", got)
}
if got := l.Merged["log-level"]; got != "debug" {
t.Errorf("log-level = %v, want the user tier's debug", got)
}
if _, ok := l.Merged["authd"]; ok {
t.Error("another program's section leaked into the merged configuration")
}
if _, ok := l.Merged["web"]; ok {
t.Error("the program's own section was merged as a key instead of its content")
}
if got := l.Origins["listen"]; got != filepath.Join(system, "fam-web.yaml") {
t.Errorf("origin of listen = %q", got)
}
if !strings.Contains(l.Describe(), "[web]") {
t.Errorf("Describe() = %q, want the section layer named", l.Describe())
}
}
func TestLoadWithoutFiles(t *testing.T) {
_, err := Load(family.Service("fam-web"), "", testOptions(t.TempDir())...)
if !errors.Is(err, ErrNotFound) {
t.Errorf("Load = %v, want ErrNotFound", err)
}
}
func TestUnknown(t *testing.T) {
root := t.TempDir()
system, _ := dirs(root)
// log-level is a shared option fam-web does not read: valid
// everywhere. typo is unknown in every layer; other programs'
// sections are not fam-web's business.
writeFile(t, filepath.Join(system, "fam.yaml"),
"log-level: info\ntypo1: x\nweb:\n listen: \":1\"\n typo2: x\nauthd:\n anything: x\n")
writeFile(t, filepath.Join(system, "fam-web.yaml"), "listen: \":2\"\nlog-level: debug\ntypo3: x\n")
l, err := Load(family.Service("fam-web"), "", testOptions(root)...)
if err != nil {
t.Fatal(err)
}
unknown, err := l.Unknown(webSchema{})
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, k := range unknown {
got[k.Key] = true
}
for _, want := range []string{"typo1", "web.typo2", "typo3"} {
if !got[want] {
t.Errorf("unknown options %v lack %s", unknown, want)
}
}
if len(unknown) != 3 {
t.Errorf("unknown options = %v, want exactly typo1, web.typo2, typo3", unknown)
}
}
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 TestConfigCommandOptionalWithoutFiles(t *testing.T) {
s := testSpec(t.TempDir())
if code, out, errOut := run(t, s, "", "validate"); code != 0 || !strings.Contains(out, "built-in defaults") {
t.Errorf("validate: exit %d, out %q, err %q", code, out, errOut)
}
if code, out, _ := run(t, s, "", "path"); code != 0 || !strings.Contains(out, "fam-web.yaml") || !strings.Contains(out, "fam.yaml [web]") {
t.Errorf("path: exit %d, out %q", code, out)
}
r := doctor.Report{Program: "fam-web"}
if l := Doctor(&r, s, ""); l != nil {
t.Error("Doctor returned a configuration without any file")
}
if r.Problems() != 0 {
t.Errorf("Doctor reports problems for an optional program without a file: %+v", r)
}
s.Optional = false
if code, _, _ := run(t, s, "", "validate"); code != 1 {
t.Errorf("validate of a required configuration without files: exit %d, want 1", code)
}
}
func TestConfigCommandValidateAndCreate(t *testing.T) {
root := t.TempDir()
system, user := dirs(root)
s := testSpec(root)
if code, out, errOut := run(t, s, "", "create"); code != 0 || !strings.Contains(out, filepath.Join(user, "fam-web.yaml")) {
t.Fatalf("create: exit %d, out %q, err %q", code, out, errOut)
}
if code, out, errOut := run(t, s, "", "create", "--shared"); code != 0 || !strings.Contains(out, filepath.Join(user, "fam.yaml")) {
t.Fatalf("create --shared: exit %d, out %q, err %q", code, out, errOut)
}
if code, _, _ := run(t, s, "", "create", "--shared"); code != 1 {
t.Errorf("create --shared over an existing file: exit %d, want 1", code)
}
if code, out, errOut := run(t, s, "", "validate"); code != 0 || !strings.Contains(out, "valid") {
t.Errorf("validate: exit %d, out %q, err %q", code, out, errOut)
}
writeFile(t, filepath.Join(system, "fam-web.yaml"), "listen: bad\n")
writeFile(t, filepath.Join(user, "fam-web.yaml"), "storage:\n path: /x\n")
if code, _, errOut := run(t, s, "", "validate"); code != 1 || !strings.Contains(errOut, "listen is bad") {
t.Errorf("validate of an invalid merge: exit %d, err %q", code, errOut)
}
}
func TestSection(t *testing.T) {
if got := family.Service("fam-authd").Section(); got != "authd" {
t.Errorf("Section() = %q", got)
}
if got := family.CLI("fam-ctl").Filename(); got != "fam-ctl.yaml" {
t.Errorf("Filename() = %q", got)
}
}
+249
View File
@@ -0,0 +1,249 @@
package configfamily
import (
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/configcmd"
"yetano.dev/yetano/core/paths"
)
// LayerKind says which part of which file a Layer is.
type LayerKind int
const (
// SharedLayer is the top level of the family file, without the
// program sections.
SharedLayer LayerKind = iota
// SectionLayer is the program's section of the family file.
SectionLayer
// ProgramLayer is the program's own file.
ProgramLayer
// ExplicitLayer is the file --config names.
ExplicitLayer
)
// Layer is one input of a program's configuration.
type Layer struct {
Kind LayerKind
// Path is the file. A SectionLayer has the family file's path.
Path string
// Section is the program section's key for a SectionLayer, else "".
Section string
// Source is the tier the file's directory belongs to (user, system,
// ...; paths.APIOverride for --config).
Source paths.Source
// Exists reports whether the layer contributes anything: the file
// exists (for a SectionLayer: and has the section).
Exists bool
}
// Name is how a value's origin is shown: the path, with the section in
// brackets for a SectionLayer.
func (l Layer) Name() string {
if l.Kind == SectionLayer {
return l.Path + " [" + l.Section + "]"
}
return l.Path
}
// SourceName is the tier for display ("--config" for an explicit file).
func (l Layer) SourceName() string {
if l.Kind == ExplicitLayer {
return "--config"
}
return l.Source.String()
}
// Info returns l as core/configcmd's LayerInfo.
func (l Layer) Info() configcmd.LayerInfo {
return configcmd.LayerInfo{Name: l.Name(), Path: l.Path, Source: l.SourceName(), Exists: l.Exists}
}
// Layers returns every layer of p's configuration, highest priority
// first, whether it exists or not:
//
// --config <file>
// user tier: <program>.yaml, <family>.yaml [<section>], <family>.yaml
// system tier: <program>.yaml, <family>.yaml [<section>], <family>.yaml
//
// A --config file that does not exist is an error.
func Layers(p Program, explicit string, opts ...coreconfig.Option) ([]Layer, error) {
var out []Layer
if explicit != "" {
if _, err := os.Stat(explicit); err != nil {
return nil, fmt.Errorf("config: --config %s: %w", explicit, err)
}
out = append(out, Layer{Kind: ExplicitLayer, Path: explicit, Source: paths.APIOverride, Exists: true})
}
programFiles, err := tierFiles(p, p.Filename(), opts)
if err != nil {
return nil, err
}
sharedFiles, err := tierFiles(p, p.Family.SharedFilename(), opts)
if err != nil {
return nil, err
}
if len(programFiles) != len(sharedFiles) {
return nil, fmt.Errorf("config: %d tiers for %s but %d for %s", len(programFiles), p.Filename(), len(sharedFiles), p.Family.SharedFilename())
}
for i, pf := range programFiles {
sf := sharedFiles[i]
section := Layer{Kind: SectionLayer, Path: sf.Path, Section: p.Section(), Source: sf.Source}
if sf.Exists {
data, err := coreconfig.ReadFile(sf.Path)
if err != nil {
return nil, err
}
_, section.Exists = data[p.Section()]
}
out = append(out,
Layer{Kind: ProgramLayer, Path: pf.Path, Source: pf.Source, Exists: pf.Exists},
section,
Layer{Kind: SharedLayer, Path: sf.Path, Source: sf.Source, Exists: sf.Exists},
)
}
return out, nil
}
// tierFiles is core/config's layer list for filename in the family's
// directories, without the working directory.
func tierFiles(p Program, filename string, opts []coreconfig.Option) ([]coreconfig.Layer, error) {
r, err := coreconfig.New(p.App, append(append([]coreconfig.Option(nil), opts...),
coreconfig.WithFilename(filename),
coreconfig.WithWorkingDirectory(false),
coreconfig.WithEnvExpansion(false))...)
if err != nil {
return nil, err
}
return r.ResolveAll()
}
// Loaded is a program's merged configuration.
type Loaded struct {
Program Program
// Layers are all layers, highest priority first (see Layers).
Layers []Layer
// Merged is the merged configuration.
Merged map[string]any
// Origins names the layer (Layer.Name) every leaf of Merged came
// from.
Origins coreconfig.Origins
}
// Load reads and merges every existing layer of p's configuration,
// lowest priority first. explicit is the --config value ("" if not
// given). With no layer at all it returns ErrNotFound, wrapped with the
// searched files; a program that runs on built-in defaults treats that
// as "no file", not as a failure.
func Load(p Program, explicit string, opts ...coreconfig.Option) (*Loaded, error) {
layers, err := Layers(p, explicit, opts...)
if err != nil {
return nil, err
}
var sources []coreconfig.Source
for i := len(layers) - 1; i >= 0; i-- {
l := layers[i]
if !l.Exists {
continue
}
data, err := layerData(p.Family, l)
if err != nil {
return nil, err
}
sources = append(sources, coreconfig.Source{Name: l.Name(), Data: data})
}
if len(sources) == 0 {
return nil, notFound(p, layers)
}
merged, origins := coreconfig.Merge(sources...)
return &Loaded{Program: p, Layers: layers, Merged: merged, Origins: origins}, nil
}
// layerData is the part of l's file that l contributes.
func layerData(f Family, l Layer) (map[string]any, error) {
data, err := coreconfig.ReadFile(l.Path)
if err != nil {
return nil, err
}
switch l.Kind {
case SharedLayer:
shared := make(map[string]any, len(data))
for k, v := range data {
if !f.IsProgramSection(k) {
shared[k] = v
}
}
return shared, nil
case SectionLayer:
v := data[l.Section]
if v == nil {
return map[string]any{}, nil
}
section, ok := v.(map[string]any)
if !ok {
return nil, fmt.Errorf("config: %s: %s: want a mapping of options", l.Path, l.Section)
}
return section, nil
}
return data, nil
}
func notFound(p Program, layers []Layer) error {
seen := map[string]bool{}
var b strings.Builder
for _, l := range layers {
if l.Kind == SectionLayer || seen[l.Path] {
continue
}
seen[l.Path] = true
b.WriteString("\n " + l.Path)
}
return fmt.Errorf("%w for %s; searched:%s", ErrNotFound, p.Name, b.String())
}
// Effective returns l as core/configcmd's Effective (for config show,
// path, validate and doctor), with l itself as its Loader.
func (l *Loaded) Effective() *configcmd.Effective {
layers := make([]configcmd.LayerInfo, len(l.Layers))
for i, layer := range l.Layers {
layers[i] = layer.Info()
}
return &configcmd.Effective{Name: l.Program.Name, Layers: layers, Merged: l.Merged, Origins: l.Origins, Loader: l}
}
// Used returns the layers that contributed, highest priority first.
func (l *Loaded) Used() []Layer {
var out []Layer
for _, layer := range l.Layers {
if layer.Exists {
out = append(out, layer)
}
}
return out
}
// YAML returns the merged configuration as YAML, for the program's own
// parser.
func (l *Loaded) YAML() ([]byte, error) {
data, err := yaml.Marshal(l.Merged)
if err != nil {
return nil, fmt.Errorf("config: marshal merged configuration: %w", err)
}
return data, nil
}
// Describe names the files that contributed, lowest priority first, for
// log lines and error messages ("a.yaml + b.yaml [web]").
func (l *Loaded) Describe() string {
used := l.Used()
names := make([]string, len(used))
for i, layer := range used {
names[len(used)-1-i] = layer.Name()
}
return strings.Join(names, " + ")
}
+89
View File
@@ -0,0 +1,89 @@
package configfamily
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/configcmd"
)
// Unknown returns the unknown options of every layer that contributed,
// checked against schema (the program's configuration struct). The
// program starts anyway with the default for them.
//
// - the program's own file, --config and its section of the family
// file: every key schema does not have, except an option of the
// family's shared schema, which is valid in every layer;
// - the family file's top level: a key neither the shared schema nor
// schema has -- an option some other program reads is not unknown,
// and neither are the other programs' sections.
func (l *Loaded) Unknown(schema any) ([]configcmd.UnknownKey, error) {
f := l.Program.Family
var out []configcmd.UnknownKey
for i := len(l.Layers) - 1; i >= 0; i-- {
layer := l.Layers[i]
if !layer.Exists {
continue
}
root, err := parseMapping(layer.Path)
if err != nil {
return nil, err
}
var keys []configcmd.UnknownKey
switch layer.Kind {
case SharedLayer:
shared := &yaml.Node{Kind: yaml.MappingNode}
for j := 0; j+1 < len(root.Content); j += 2 {
if !f.IsProgramSection(root.Content[j].Value) {
shared.Content = append(shared.Content, root.Content[j], root.Content[j+1])
}
}
keys = configcmd.UnknownKeysNode(shared, schema)
case SectionLayer:
keys = configcmd.UnknownKeysNode(mappingValue(root, layer.Section), schema)
default:
keys = configcmd.UnknownKeysNode(root, schema)
}
for _, k := range keys {
if f.IsSharedKey(k.Key) {
continue // a family option, valid in every layer
}
if layer.Kind == SectionLayer {
k.Key = layer.Section + "." + k.Key
}
k.Layer = layer.Name()
out = append(out, k)
}
}
return out, nil
}
// parseMapping parses path and returns its top-level mapping node (an
// empty one for an empty file).
func parseMapping(path string) (*yaml.Node, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: read %s: %w", path, err)
}
var doc yaml.Node
if err := yaml.Unmarshal(raw, &doc); err != nil {
return nil, fmt.Errorf("config: parse %s: %w", path, err)
}
if doc.Kind == yaml.DocumentNode && len(doc.Content) == 1 && doc.Content[0].Kind == yaml.MappingNode {
return doc.Content[0], nil
}
return &yaml.Node{Kind: yaml.MappingNode}, nil
}
// mappingValue returns the value node of key in mapping n (an empty
// mapping if absent).
func mappingValue(n *yaml.Node, key string) *yaml.Node {
for i := 0; i+1 < len(n.Content); i += 2 {
if n.Content[i].Value == key {
return n.Content[i+1]
}
}
return &yaml.Node{Kind: yaml.MappingNode}
}
+198
View File
@@ -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
}
+51
View File
@@ -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)
}
}
}
+158
View File
@@ -0,0 +1,158 @@
# yetano.dev/yetano/core/gui
The native WebView host shared by Yetano desktop programs: a native window
whose WebView shows embedded HTML/CSS/JS/WASM and sends the page's
`fetch`/`XMLHttpRequest` to Go handlers. **No local web server, no port, no
localhost listener** -- not in the program, not as a fallback. Every request
goes either through the WebView's native resource handler (custom scheme /
request interception) or through the native message binding.
Extracted from the AP1 prototype `prototypes/yetano-webview` (meta-repo
`docs/yetano-ui/AP1-GO-WEBVIEW-PROTOTYP.md`), which remains its native
selftest bench; its README holds the measured evidence per platform.
## Separate module
```text
module yetano.dev/yetano/core/gui tags: gui/v0.1.0, gui/v0.2.0, ...
```
This directory is its own Go module, nested in the core repository, so the
main `yetano.dev/yetano/core` module keeps its single dependency
(`gopkg.in/yaml.v3`) and stays free of cgo. Its dependencies:
`golang.org/x/net/html` (tokenizer), `golang.org/x/sys/windows`,
`github.com/jchv/go-webview2/pkg/edge` (Windows only, MIT; loads
Microsoft's embedded WebView2Loader via `go-winloader`, ISC). Go 1.26.
```sh
GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/gui@gui/v0.1.0
```
Tags carry the `gui/` prefix (Go's rule for a module in a subdirectory);
the main module's `vX.Y.Z` tags do not version this one. Never move a tag.
## API
| Package | What |
|---|---|
| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. |
| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). |
| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. |
## Wiring
```go
res, _ := assets.NewResolver(assets.NewFSSource("embed", webFS))
router := bridge.NewRouter(res)
router.SetDocument("index.html", true) // entry served via the resource handler
router.Handle("POST /rpc/add", addHandler)
sess := bridge.NewSession(router, bridge.Options{})
var origin string // requests only arrive after Navigate
w, err := window.New(window.Options{
Title: "app", DataPath: webview2Dir, // Windows: from core/paths, see below
OnMessage: func(msg string) { sess.Post(json.RawMessage(msg)) },
Resource: func(ctx context.Context, r *window.ResourceRequest, rw window.ResourceWriter) {
router.ServeNative(ctx, origin, r.Method, r.URL, r.Header, r.Body, rw)
},
})
if err != nil { sess.Close(); return err }
origin = w.BaseURL()
sess.Attach(w)
w.Init(bridge.InitScript(bridge.PageConfig{Transport: "native", Origin: origin, External: "reject"}))
w.Navigate(origin + "/")
w.Run() // main goroutine
sess.Close() // first: lock, cancel calls, bounded wait
w.Destroy() // then: native window, on the UI thread
```
The WebView2 user-data folder (`DataPath`) belongs under the program's
`core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming).
## Invariants
- **No listener, no ports, no localhost.** After a transport change,
re-check the running process (`lsof -nP -a -p PID -i`, `netstat -ano`).
- **Paths are checked, not cleaned** (`assets.ValidatePath`): `..`, `.`,
empty segments, `\`, `:`, NUL, absolute paths -> 400. `assets.Join` lets
trusted CSS use `..` inside the root; never for paths from the page.
- **Exactly one end per call/stream**; every end that does not come from Go
is reported to Go (`abort`). Calls of an old document generation fail
with `ErrStale`, their answers are dropped (Go and JS side).
- **Close order:** `Session.Close()` -> `Window.Destroy()` on the UI thread.
`Close` never waits for the UI thread.
- **Threads:** `window.New/Init/Navigate/Run/Destroy` only on the main
goroutine (package `window` locks it in `init`). `Eval` only inside a
`Dispatch`ed function. `Dispatch` after `Destroy` is a no-op.
- Routes are registered before the document starts (`Router.Freeze` in
`NewSession`); duplicates are errors; handler panics become a 500.
- Transport `native`: entry and `/assets/` via the resource handler, app
routes via the bridge (WebView2 buffers intercepted responses until EOF,
so streaming only works over the bridge on Windows).
## Measured platform pitfalls
| Pitfall | Handled in |
|---|---|
| WKWebView silently ignores `location.reload()` of a `data:` document | transport inline: reload via a Go route that navigates again |
| WebKit hands Blob/FormData bodies to `WKURLSchemeHandler` empty | `bridge.js` `needsSerialize` |
| WebKit tasks must not be touched after `stopURLSchemeTask` | `darwin.m` `onTask` looks them up in `tasks` |
| WebView2 reads intercepted response streams to EOF; `E_PENDING` fails the request | app routes stream over the bridge |
| WebView2 has no cancel for intercepted requests | `goStream.onDrop` cancels the `ctx` when the stream is released |
| A stale `WM_QUIT` makes the next `pkg/edge.Embed` crash | `settle()` before create and after `Destroy` |
| `PostThreadMessage` is lost during move/resize | `Dispatch` via `PostMessage` to the window |
## Platforms
| Platform | Backend | Origin | Status |
|---|---|---|---|
| macOS | `window/darwin.m`: NSWindow + WKWebView, cgo | `yetano://app` | natively verified (prototype selftest, yet-gui) |
| Windows | `window/window_windows.go`: Win32 + WebView2 via `pkg/edge`, pure Go | `https://yetano.invalid` | natively verified (Windows 11 amd64) |
| Linux/FreeBSD | -- | -- | builds; `window.New` returns `ErrUnsupported` (see TODO) |
## Tests
```sh
go vet ./... && GOOS=windows go vet ./... && go test -race ./...
```
Unit tests cover everything backend-free: resolver/path rules/MIME
(`assets`), HTML/CSS rewriting (`document`), router and the bridge protocol
against a fake UI (`bridge`), dispatch/destroy guards (`window`). Real
browser behavior is tested by the prototype's in-window selftest
(`make selftest`, `make selftest-windows` in `prototypes/yetano-webview`)
and yet-gui's (`make gui-selftest`).
## TODO
- Linux/FreeBSD backend: WebKitGTK, `webkit_web_context_register_uri_scheme`
(a `GInputStream`, so real streaming) + `WebKitUserContentManager` for
the message binding; own cgo host like `darwin.m`.
- Windows: own environment creation instead of `pkg/edge.Embed` (custom
`yetano://app` scheme, fixed-version runtime, no `log.Fatal` on COM
errors, explicit `Controller.Close`); `Snapshot` via `CapturePreview`.
- Bridge: back-pressure for streams, streaming uploads, XHR progress.
- AP2 (Lua/HTML templating) hooks in before `document.Prepare`.
The full list with background lives in the prototype's `TODO.md`.
## Migrating yet-gui (`yet/gui/internal` -> core/gui)
`yet/gui/internal/{assets,document,bridge,window}` is a byte-identical copy
(apart from the import path) of what is now in this module.
1. `cd yet/gui && GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/gui@gui/v0.1.0`
2. Replace the imports `yetano.dev/yetano/yet/gui/internal/<pkg>` with
`yetano.dev/yetano/core/gui/<pkg>` (`gofmt -r` or `sed`); the API is
unchanged, no call site changes.
3. `git rm -r gui/internal/{assets,document,bridge,window} gui/internal/README.md`,
`go mod tidy`.
4. `make gui-check`, `make gui-selftest` (macOS) and
`make gui-selftest-windows` -- the in-window selftests are the proof,
a cross-build is not.
5. Drop the "keep both copies in sync" notes (yet `docs/gui.md`, the
prototype's `AGENTS.md` already points here).
A host fix from then on is a core/gui change plus a new `gui/vX.Y.Z` tag,
picked up by `go get` in every consumer.
+56
View File
@@ -0,0 +1,56 @@
package assets
import (
"bytes"
"fmt"
"net/http"
"path"
"strings"
)
// Known types by extension. The extension wins; sniffing only fills gaps.
var mimeByExt = map[string]string{
".html": "text/html; charset=utf-8",
".htm": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".json": "application/json",
".txt": "text/plain; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".ico": "image/x-icon",
".ttf": "font/ttf",
".otf": "font/otf",
".woff": "font/woff",
".woff2": "font/woff2",
".wasm": "application/wasm",
}
// strict extensions must never resolve to a generic type, and binary ones are
// checked against their magic bytes.
var wasmMagic = []byte{0x00, 'a', 's', 'm'}
// DetectMIME returns the MIME type for name/data.
func DetectMIME(name string, data []byte) (string, error) {
ext := strings.ToLower(path.Ext(name))
if m, ok := mimeByExt[ext]; ok {
if ext == ".wasm" && !bytes.HasPrefix(data, wasmMagic) {
return "", fmt.Errorf("%s: .wasm without WebAssembly magic bytes", name)
}
return m, nil
}
return http.DetectContentType(data), nil
}
// BaseMIME strips parameters ("text/css; charset=utf-8" -> "text/css").
func BaseMIME(m string) string {
if i := strings.IndexByte(m, ';'); i >= 0 {
m = m[:i]
}
return strings.TrimSpace(m)
}
+103
View File
@@ -0,0 +1,103 @@
package assets
import (
"errors"
"fmt"
"path"
"strings"
)
// ErrInvalidPath marks a virtual asset path that is rejected before any
// source is consulted (traversal, backslash, drive letter, UNC, NUL, ...).
var ErrInvalidPath = errors.New("invalid asset path")
// URL prefixes that address the asset root. "/assets/x" and "assets:x" are
// the same identity "x".
const (
PrefixSlash = "/assets/"
PrefixScheme = "assets:"
)
// IsAssetRef reports whether ref uses one of the two asset reference forms.
func IsAssetRef(ref string) bool {
return strings.HasPrefix(ref, PrefixSlash) || strings.HasPrefix(ref, PrefixScheme)
}
// SplitRef removes query and fragment from a reference. They never take part
// in the lookup.
func SplitRef(ref string) (p, suffix string) {
if i := strings.IndexAny(ref, "?#"); i >= 0 {
return ref[:i], ref[i:]
}
return ref, ""
}
// FromRef turns "/assets/a/b.png?x#y" or "assets:a/b.png" into the canonical
// virtual path "a/b.png". The path is validated with ValidatePath; nothing is
// cleaned silently and nothing is percent-decoded here.
func FromRef(ref string) (string, error) {
p, _ := SplitRef(ref)
switch {
case strings.HasPrefix(p, PrefixSlash):
p = p[len(PrefixSlash):]
case strings.HasPrefix(p, PrefixScheme):
p = p[len(PrefixScheme):]
default:
return "", fmt.Errorf("%w: %q is not an asset reference", ErrInvalidPath, ref)
}
if err := ValidatePath(p); err != nil {
return "", err
}
return p, nil
}
// ValidatePath accepts only canonical, relative, forward-slash paths inside
// the asset root. It rejects instead of cleaning: "a/../b" is an error, not
// "b".
func ValidatePath(p string) error {
bad := func(why string) error { return fmt.Errorf("%w: %q: %s", ErrInvalidPath, p, why) }
switch {
case p == "":
return bad("empty")
case strings.ContainsRune(p, 0):
return bad("NUL byte")
case strings.Contains(p, `\`):
return bad("backslash")
case strings.HasPrefix(p, "/"):
return bad("absolute")
case strings.Contains(p, ":"):
return bad("drive letter or scheme")
case strings.HasSuffix(p, "/"):
return bad("directory")
}
for _, seg := range strings.Split(p, "/") {
switch seg {
case "":
return bad("empty segment")
case ".", "..":
return bad("dot segment")
}
}
if path.Clean(p) != p {
return bad("not canonical")
}
return nil
}
// Join resolves ref relative to the directory of base, both virtual paths.
// Unlike ValidatePath it may use ".." segments, as long as the canonical
// result stays inside the root. This is for references found inside trusted
// asset content (CSS url(), @import), not for paths coming from the browser.
func Join(base, ref string) (string, error) {
if strings.ContainsAny(ref, "\\\x00") {
return "", fmt.Errorf("%w: %q", ErrInvalidPath, ref)
}
joined := path.Join(path.Dir(base), ref)
if joined == "." || joined == ".." || strings.HasPrefix(joined, "../") || strings.HasPrefix(joined, "/") {
return "", fmt.Errorf("%w: %q relative to %q leaves the asset root", ErrInvalidPath, ref, base)
}
if err := ValidatePath(joined); err != nil {
return "", err
}
return joined, nil
}
+272
View File
@@ -0,0 +1,272 @@
// Package assets resolves virtual asset paths against an ordered list of
// sources (embedded folder, ZIP, embedded ZIP, explicit directory root).
package assets
import (
"archive/zip"
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"strings"
)
// DefaultMaxSize bounds a single resolved resource (also the uncompressed
// budget for a ZIP entry).
const DefaultMaxSize = 32 << 20
// Resource is one resolved asset.
type Resource struct {
Name string // canonical virtual path
MIME string
Bytes []byte
Source string // name of the source that served it
}
// Source is one place assets can come from. Open must return an error
// wrapping fs.ErrNotExist for a missing file; any other error is a real
// failure and stops the lookup.
type Source interface {
Name() string
ReadFile(name string, max int64) ([]byte, error)
Close() error
}
// Resolver looks a path up in its sources in order. It falls back to the
// next source only on "not found".
type Resolver struct {
sources []Source
max int64
}
// NewResolver builds a resolver over sources (at least one).
func NewResolver(sources ...Source) (*Resolver, error) {
if len(sources) == 0 {
return nil, errors.New("assets: no sources configured")
}
return &Resolver{sources: sources, max: DefaultMaxSize}, nil
}
// Sources lists the source names in lookup order (for the diagnostic report).
func (r *Resolver) Sources() []string {
out := make([]string, len(r.sources))
for i, s := range r.sources {
out[i] = s.Name()
}
return out
}
// Resolve returns the resource for a canonical virtual path.
func (r *Resolver) Resolve(ctx context.Context, name string) (*Resource, error) {
if err := ValidatePath(name); err != nil {
return nil, err
}
for _, s := range r.sources {
if err := ctx.Err(); err != nil {
return nil, err
}
data, err := s.ReadFile(name, r.max)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err)
}
m, err := DetectMIME(name, data)
if err != nil {
return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err)
}
return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil
}
return nil, fmt.Errorf("asset %q: %w (searched %s)", name, fs.ErrNotExist, strings.Join(r.Sources(), ", "))
}
// ResolveIn returns the resource from one named source only (diagnostics:
// "same bytes from every source").
func (r *Resolver) ResolveIn(name, source string) (*Resource, error) {
if err := ValidatePath(name); err != nil {
return nil, err
}
for _, s := range r.sources {
if s.Name() != source {
continue
}
data, err := s.ReadFile(name, r.max)
if err != nil {
return nil, err
}
m, err := DetectMIME(name, data)
if err != nil {
return nil, err
}
return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil
}
return nil, fmt.Errorf("no source %q", source)
}
// Close closes all sources (ZIP archives, directory roots).
func (r *Resolver) Close() error {
var errs []error
for _, s := range r.sources {
errs = append(errs, s.Close())
}
return errors.Join(errs...)
}
func readLimited(rd io.Reader, max int64, name string) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(rd, max+1))
if err != nil {
return nil, err
}
if int64(len(data)) > max {
return nil, fmt.Errorf("%s exceeds size limit of %d bytes", name, max)
}
return data, nil
}
// --- fs.FS source (embed.FS, or any fs.FS) -------------------------------
type fsSource struct {
name string
fsys fs.FS
}
// NewFSSource wraps an fs.FS whose root is the asset root (for embed.FS use
// fs.Sub(efs, "assets") first).
func NewFSSource(name string, fsys fs.FS) Source { return &fsSource{name: name, fsys: fsys} }
func (s *fsSource) Name() string { return s.name }
func (s *fsSource) Close() error { return nil }
func (s *fsSource) ReadFile(name string, max int64) ([]byte, error) {
f, err := s.fsys.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if st.IsDir() {
return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist)
}
return readLimited(f, max, name)
}
// --- directory source ----------------------------------------------------
type dirSource struct {
name string
root *os.Root
}
// NewDirSource opens dir as an explicit asset root. os.Root keeps every
// lookup (including symlinks) inside dir.
func NewDirSource(dir string) (Source, error) {
root, err := os.OpenRoot(dir)
if err != nil {
return nil, fmt.Errorf("asset dir %s: %w", dir, err)
}
return &dirSource{name: "dir:" + dir, root: root}, nil
}
func (s *dirSource) Name() string { return s.name }
func (s *dirSource) Close() error { return s.root.Close() }
func (s *dirSource) ReadFile(name string, max int64) ([]byte, error) {
f, err := s.root.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if st.IsDir() {
return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist)
}
return readLimited(f, max, name)
}
// --- ZIP source ----------------------------------------------------------
type zipSource struct {
name string
zr *zip.Reader
prefix string
closer io.Closer
files map[string]*zip.File
}
// NewZipFileSource opens a ZIP file on disk (never extracted). prefix is the
// directory inside the archive that is the asset root ("" = archive root).
func NewZipFileSource(file, prefix string) (Source, error) {
rc, err := zip.OpenReader(file)
if err != nil {
return nil, fmt.Errorf("asset zip %s: %w", file, err)
}
s, err := newZipSource("zip:"+file, &rc.Reader, prefix, rc)
if err != nil {
rc.Close()
return nil, err
}
return s, nil
}
// NewZipBytesSource reads a ZIP held in memory (e.g. an embedded assets.zip).
func NewZipBytesSource(name string, data []byte, prefix string) (Source, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, fmt.Errorf("asset zip %s: %w", name, err)
}
return newZipSource(name, zr, prefix, nil)
}
func newZipSource(name string, zr *zip.Reader, prefix string, closer io.Closer) (*zipSource, error) {
if prefix != "" {
if err := ValidatePath(prefix); err != nil {
return nil, fmt.Errorf("zip root: %w", err)
}
prefix += "/"
}
s := &zipSource{name: name, zr: zr, prefix: prefix, closer: closer, files: map[string]*zip.File{}}
for _, f := range zr.File {
if !strings.HasPrefix(f.Name, prefix) || strings.HasSuffix(f.Name, "/") {
continue
}
rel := f.Name[len(prefix):]
// Entries with unsafe names ("../x", "/etc/x", "a\\b") are never
// reachable: they simply do not get an identity.
if ValidatePath(rel) != nil {
continue
}
s.files[rel] = f
}
return s, nil
}
func (s *zipSource) Name() string { return s.name }
func (s *zipSource) Close() error {
if s.closer != nil {
return s.closer.Close()
}
return nil
}
func (s *zipSource) ReadFile(name string, max int64) ([]byte, error) {
f, ok := s.files[name]
if !ok {
return nil, fmt.Errorf("%s: %w", name, fs.ErrNotExist)
}
if f.UncompressedSize64 > uint64(max) {
return nil, fmt.Errorf("%s: uncompressed size %d exceeds budget %d", name, f.UncompressedSize64, max)
}
rc, err := f.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return readLimited(rc, max, name)
}
+219
View File
@@ -0,0 +1,219 @@
package assets
import (
"archive/zip"
"bytes"
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"testing/fstest"
)
func TestValidatePath(t *testing.T) {
ok := []string{"a", "images/logo.png", "a/b/c.wasm", "%2e%2e/x", "dir.with.dots/f"}
bad := []string{"", "/abs", "../x", "a/../b", "./a", "a//b", "a/", `a\b`, "C:/x", "c:x", "a\x00b", "assets:x", ".."}
for _, p := range ok {
if err := ValidatePath(p); err != nil {
t.Errorf("ValidatePath(%q) = %v, want ok", p, err)
}
}
for _, p := range bad {
if err := ValidatePath(p); !errors.Is(err, ErrInvalidPath) {
t.Errorf("ValidatePath(%q) = %v, want ErrInvalidPath", p, err)
}
}
}
func TestFromRefBothForms(t *testing.T) {
for _, ref := range []string{"/assets/images/a.png", "assets:images/a.png", "/assets/images/a.png?v=1#x", "assets:images/a.png#frag"} {
got, err := FromRef(ref)
if err != nil || got != "images/a.png" {
t.Errorf("FromRef(%q) = %q, %v", ref, got, err)
}
}
for _, ref := range []string{"/other/x", "assets:../x", "/assets/", "/assets//etc/passwd"} {
if _, err := FromRef(ref); err == nil {
t.Errorf("FromRef(%q) accepted", ref)
}
}
}
func TestJoinRelativeInsideRoot(t *testing.T) {
cases := map[[2]string]string{
{"css/app.css", "../images/bg.png"}: "images/bg.png",
{"css/app.css", "fonts.css"}: "css/fonts.css",
{"css/a/b.css", "../../x.png"}: "x.png",
}
for in, want := range cases {
if got, err := Join(in[0], in[1]); err != nil || got != want {
t.Errorf("Join(%q,%q) = %q, %v; want %q", in[0], in[1], got, err, want)
}
}
for _, ref := range []string{"../../x.png", "../../../etc/passwd", `..\x`} {
if _, err := Join("css/app.css", ref); err == nil {
t.Errorf("Join escaped root with %q", ref)
}
}
}
func TestMIME(t *testing.T) {
want := map[string]string{
"a.css": "text/css", "a.js": "text/javascript", "a.svg": "image/svg+xml", "a.png": "image/png",
"a.ttf": "font/ttf", "a.woff2": "font/woff2", "a.json": "application/json", "a.ico": "image/x-icon",
}
for name, m := range want {
got, err := DetectMIME(name, []byte("x"))
if err != nil || BaseMIME(got) != m {
t.Errorf("%s: %q %v, want %s", name, got, err, m)
}
}
if m, err := DetectMIME("a.wasm", []byte("\x00asm\x01\x00\x00\x00")); err != nil || m != "application/wasm" {
t.Errorf("wasm: %q %v", m, err)
}
if _, err := DetectMIME("a.wasm", []byte("not wasm")); err == nil {
t.Error("fake .wasm accepted")
}
if m, _ := DetectMIME("noext", []byte("\x89PNG\r\n\x1a\n")); m != "image/png" {
t.Errorf("sniff fallback: %q", m)
}
}
func zipBytes(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, data := range files {
w, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
w.Write([]byte(data))
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestAllSourcesSameIdentity(t *testing.T) {
files := map[string]string{"index.html": "<p>hi</p>", "wasm/a.wasm": "\x00asm\x01\x00\x00\x00", "css/app.css": "body{}"}
mfs := fstest.MapFS{}
dir := t.TempDir()
for name, data := range files {
mfs[name] = &fstest.MapFile{Data: []byte(data)}
os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o755)
os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644)
}
zipPath := filepath.Join(t.TempDir(), "assets.zip")
os.WriteFile(zipPath, zipBytes(t, files), 0o644)
dirSrc, err := NewDirSource(dir)
if err != nil {
t.Fatal(err)
}
zipSrc, err := NewZipFileSource(zipPath, "")
if err != nil {
t.Fatal(err)
}
embZip, err := NewZipBytesSource("embedzip", zipBytes(t, files), "")
if err != nil {
t.Fatal(err)
}
for _, s := range []Source{NewFSSource("embed", mfs), dirSrc, zipSrc, embZip} {
r, _ := NewResolver(s)
for name, data := range files {
res, err := r.Resolve(context.Background(), name)
if err != nil || string(res.Bytes) != data || res.Source != s.Name() {
t.Errorf("%s %s: %v", s.Name(), name, err)
}
}
if err := r.Close(); err != nil {
t.Errorf("close %s: %v", s.Name(), err)
}
}
}
func TestFallbackOnlyOnNotFound(t *testing.T) {
first := fstest.MapFS{"a.txt": {Data: []byte("first")}}
second := fstest.MapFS{"a.txt": {Data: []byte("second")}, "b.txt": {Data: []byte("b")}}
r, _ := NewResolver(NewFSSource("one", first), NewFSSource("two", second))
if res, _ := r.Resolve(context.Background(), "a.txt"); string(res.Bytes) != "first" {
t.Error("override order not respected")
}
if res, _ := r.Resolve(context.Background(), "b.txt"); res.Source != "two" {
t.Error("no fallback on not-found")
}
if _, err := r.Resolve(context.Background(), "c.txt"); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("missing: %v", err)
}
// A real read error in the first source must not fall through.
boom := &errSource{err: errors.New("permission denied")}
r2, _ := NewResolver(boom, NewFSSource("two", second))
if _, err := r2.Resolve(context.Background(), "b.txt"); err == nil || !strings.Contains(err.Error(), "permission denied") {
t.Errorf("read error swallowed: %v", err)
}
}
type errSource struct{ err error }
func (e *errSource) Name() string { return "err" }
func (e *errSource) Close() error { return nil }
func (e *errSource) ReadFile(string, int64) ([]byte, error) { return nil, e.err }
func TestCorruptZipIsError(t *testing.T) {
p := filepath.Join(t.TempDir(), "bad.zip")
os.WriteFile(p, []byte("not a zip"), 0o644)
if _, err := NewZipFileSource(p, ""); err == nil {
t.Error("corrupt zip accepted")
}
}
func TestZipUnsafeNamesAndBudget(t *testing.T) {
data := zipBytes(t, map[string]string{"../evil.txt": "x", "/abs.txt": "x", `a\b.txt`: "x", "assets/ok.txt": "ok", "big.bin": strings.Repeat("x", 2048)})
s, err := NewZipBytesSource("z", data, "")
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"evil.txt", "abs.txt"} {
if _, err := s.ReadFile(name, 1<<20); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("%s reachable: %v", name, err)
}
}
if _, err := s.ReadFile("big.bin", 1024); err == nil || !strings.Contains(err.Error(), "budget") {
t.Errorf("budget not enforced: %v", err)
}
// Explicit zip root for archives that contain an assets/ folder.
s2, _ := NewZipBytesSource("z", data, "assets")
if b, err := s2.ReadFile("ok.txt", 1024); err != nil || string(b) != "ok" {
t.Errorf("zip root: %q %v", b, err)
}
}
func TestDirSymlinkEscape(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlink creation needs privileges on Windows")
}
outside := t.TempDir()
os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644)
root := t.TempDir()
if err := os.Symlink(filepath.Join(outside, "secret.txt"), filepath.Join(root, "link.txt")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(root, "linkdir")); err != nil {
t.Fatal(err)
}
s, err := NewDirSource(root)
if err != nil {
t.Fatal(err)
}
defer s.Close()
for _, name := range []string{"link.txt", "linkdir/secret.txt"} {
if b, err := s.ReadFile(name, 1024); err == nil {
t.Errorf("%s escaped root: %q", name, b)
}
}
}
+422
View File
@@ -0,0 +1,422 @@
// Yetano WebView bridge, protocol v1. Installed as a document-start script
// before any page script. Replaces window.fetch and window.XMLHttpRequest for
// page-local URLs ("/..." and "assets:...") and routes them through the single
// native binding __yetano_post to the Go host. No network listener is used.
(function () {
'use strict';
if (window.yetano && window.yetano.__installed) return;
window.__yetano_install_count = (window.__yetano_install_count || 0) + 1;
var cfg = window.__yetano_config || {};
var PROTO = 1;
var origFetch = typeof window.fetch === 'function' ? window.fetch.bind(window) : null;
var OrigXHR = window.XMLHttpRequest;
var nonce = Math.random().toString(36).slice(2) + Date.now().toString(36);
var gen = 0;
var seq = 0;
var pending = new Map();
var stats = { staleDropped: 0, requests: 0 };
var readyResolve, readyReject, readySettled = false;
var ready = new Promise(function (res, rej) { readyResolve = res; readyReject = rej; });
ready.catch(function () {}); // the rejection is reported to callers, not as unhandled
function settleReady(ok, v) {
if (readySettled) return;
readySettled = true;
clearTimeout(helloTimer);
(ok ? readyResolve : readyReject)(v);
}
function post(msg) {
var fn = window.__yetano_post;
if (typeof fn !== 'function') return Promise.reject(new Error('native binding __yetano_post missing'));
try { return Promise.resolve(fn(msg)); } catch (e) { return Promise.reject(e); }
}
// ---- receive ---------------------------------------------------------
window.__yetano_recv = function (m) {
if (!m || typeof m !== 'object') return;
if (m.t === 'ready') {
if (m.nonce !== nonce) return;
if (m.error) { settleReady(false, new Error('yetano bridge: ' + m.error)); return; }
gen = m.gen;
settleReady(true, { generation: m.gen, session: m.session, protocol: m.v });
return;
}
if (m.t !== 'res' && m.t !== 'err' && m.t !== 'chunk' && m.t !== 'end') return;
var p = pending.get(m.id);
if (!p || m.gen !== gen) { stats.staleDropped++; return; }
switch (m.t) {
case 'res':
if (m.stream) p.startStream(m);
else p.resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: b64dec(m.body || '') });
break;
case 'chunk': p.chunk(b64dec(m.data || '')); break;
case 'end': p.end(); break;
default: {
var e = m.code === 'timeout' ? new DOMException('yetano: ' + m.message, 'TimeoutError')
: m.code === 'abort' ? new DOMException('yetano: ' + m.message, 'AbortError')
: new TypeError('yetano bridge ' + m.code + ': ' + m.message);
p.fail(e);
}
}
};
var helloTimer = setTimeout(function () {
settleReady(false, new Error('yetano bridge: handshake timed out'));
}, cfg.handshakeTimeoutMs || 5000);
post({ t: 'hello', v: cfg.protocolOverride || PROTO, nonce: nonce }).catch(function (e) {
settleReady(false, new Error('yetano bridge: hello failed: ' + e));
});
// ---- helpers ---------------------------------------------------------
function b64enc(u8) {
var s = '';
for (var i = 0; i < u8.length; i += 0x8000) {
s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
}
return btoa(s);
}
function b64dec(s) {
var bin = atob(s);
var u8 = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
return u8;
}
function abortError(signal) {
return (signal && signal.reason !== undefined) ? signal.reason : new DOMException('The operation was aborted.', 'AbortError');
}
// Local URLs are recognized on the raw string, before any URL() resolution
// (an inline entry document has an opaque data: origin). Absolute URLs on
// the app origin (native transport) count as local, too.
var NATIVE = cfg.transport === 'native';
function localURL(u) {
if (typeof u !== 'string') return null;
if (u.indexOf('assets:') === 0) return u;
if (cfg.origin && u.indexOf(cfg.origin + '/') === 0) return u.slice(cfg.origin.length);
if (u.charAt(0) === '/' && u.charAt(1) !== '/') return u;
return null;
}
// For the native transport: "assets:x" is not loadable by the browser.
function nativeURL(local) {
return local.indexOf('assets:') === 0 ? '/assets/' + local.slice(7) : local;
}
function externalBlocked(u) {
return new TypeError('yetano: external request blocked by policy: ' + u);
}
async function toBytes(body, headers) {
function setType(t) { if (!headers['content-type']) headers['content-type'] = t; }
if (typeof body === 'string') { setType('text/plain;charset=UTF-8'); return new TextEncoder().encode(body); }
if (body instanceof URLSearchParams) { setType('application/x-www-form-urlencoded;charset=UTF-8'); return new TextEncoder().encode(body.toString()); }
if (body instanceof ArrayBuffer) return new Uint8Array(body);
if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
if (typeof Blob !== 'undefined' && body instanceof Blob) { if (body.type) setType(body.type); return new Uint8Array(await body.arrayBuffer()); }
if (typeof FormData !== 'undefined' && body instanceof FormData) {
// Let the browser produce multipart/form-data (with its boundary).
var mp = new Response(body);
headers['content-type'] = mp.headers.get('content-type');
return new Uint8Array(await mp.arrayBuffer());
}
if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) throw new TypeError('yetano: streaming request bodies are not supported (AP1 limit)');
setType('text/plain;charset=UTF-8');
return new TextEncoder().encode(String(body));
}
// request sends one call. The promise settles exactly once: with the
// response head (body bytes, or a ReadableStream for streamed responses)
// or with an error (abort, timeout, stale generation, transport). A stream
// ends exactly once, too: end, error, abort or reader cancel. Every end
// that is not initiated by Go is reported to Go (abort message).
async function request(d) {
await ready;
if (d.signal && d.signal.aborted) throw abortError(d.signal);
var id = String(++seq);
var myGen = gen;
stats.requests++;
return new Promise(function (resolve, reject) {
var timer = null, ctrl = null, settled = false;
function cleanup() {
pending.delete(id);
if (timer) { clearTimeout(timer); timer = null; }
if (d.signal) d.signal.removeEventListener('abort', onAbort);
}
function fail(e) {
if (!pending.has(id)) return;
cleanup();
if (ctrl) { try { ctrl.error(e); } catch (x) {} } else if (!settled) { settled = true; reject(e); }
}
function onAbort() { fail(abortError(d.signal)); post({ t: 'abort', id: id, gen: myGen }); }
pending.set(id, {
resolve: function (v) { if (!pending.has(id)) return; cleanup(); settled = true; resolve(v); },
fail: fail,
startStream: function (m) {
if (timer) { clearTimeout(timer); timer = null; } // the timeout covers the response head
var body = new ReadableStream({
start: function (c) { ctrl = c; },
cancel: function () { if (!pending.has(id)) return; cleanup(); post({ t: 'abort', id: id, gen: myGen }); }
});
settled = true;
resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: body, streaming: true });
},
chunk: function (u8) { if (ctrl) ctrl.enqueue(u8); },
end: function () { if (!pending.has(id)) return; cleanup(); if (ctrl) ctrl.close(); }
});
if (d.signal) d.signal.addEventListener('abort', onAbort, { once: true });
var t = d.timeoutMs != null ? d.timeoutMs : (cfg.defaultTimeoutMs || 30000);
if (t > 0) {
timer = setTimeout(function () {
fail(new DOMException('yetano: request timed out after ' + t + ' ms', 'TimeoutError'));
post({ t: 'abort', id: id, gen: myGen, reason: 'timeout' });
}, t);
}
post({
t: 'req', id: id, gen: myGen, method: d.method, url: d.url, headers: d.headers,
body: d.body ? b64enc(d.body) : null, timeoutMs: t
}).catch(function (e) { fail(new TypeError('yetano bridge: transport failed: ' + e)); });
});
}
// ---- fetch -----------------------------------------------------------
// bridgeFetch: local requests as bridge messages (abort, timeout and
// document generation reach the Go handler; bodies are buffered).
async function bridgeFetch(input, init) {
init = init || {};
var url = typeof input === 'string' ? input
: (typeof URL !== 'undefined' && input instanceof URL) ? input.href
: (input && input.url);
var local = localURL(url);
if (local === null) {
if (cfg.external === 'passthrough' && origFetch) return origFetch(input, init);
throw externalBlocked(url);
}
var method = String(init.method || 'GET').toUpperCase();
var headers = {};
new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; });
var body = null;
if (init.body != null) {
if (method === 'GET' || method === 'HEAD') throw new TypeError('yetano: ' + method + ' request cannot have a body');
body = await toBytes(init.body, headers);
}
var r = await request({ method: method, url: local, headers: headers, body: body, signal: init.signal, timeoutMs: init.yetanoTimeout });
var nullBody = method === 'HEAD' || r.status === 204 || r.status === 205 || r.status === 304;
return new Response(nullBody ? null : r.body, { status: r.status, statusText: r.statusText, headers: r.headers });
}
bridgeFetch.yetano = true;
// nativeFetch (native transport): assets come from the native resource
// handler (no size limit, real Response, ES modules); app routes use the
// bridge (abort/timeout/generation reach Go, streaming via chunk messages
// on every backend). init.yetanoTransport = 'native' | 'bridge' overrides.
function isAsset(local) { return local.indexOf('assets:') === 0 || local.indexOf('/assets/') === 0; }
async function nativeFetch(input, init) {
var url = typeof input === 'string' ? input
: (typeof URL !== 'undefined' && input instanceof URL) ? input.href
: (input && input.url);
var local = localURL(url);
if (local === null) {
if (cfg.external === 'passthrough') return origFetch(input, init);
throw externalBlocked(url);
}
var via = (init && init.yetanoTransport) || (isAsset(local) ? 'native' : 'bridge');
if (via === 'bridge') return bridgeFetch(input, init);
if (typeof input === 'string' || (typeof URL !== 'undefined' && input instanceof URL)) input = nativeURL(local);
// WebKit hands Blob/FormData bodies to a URL scheme handler as empty
// (observed); serialize them here so every backend receives the bytes.
if (init && needsSerialize(init.body)) {
var headers = {};
new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; });
var bytes = await toBytes(init.body, headers);
init = Object.assign({}, init, { body: bytes, headers: headers });
}
return origFetch(input, init);
}
nativeFetch.yetano = true;
function needsSerialize(b) {
return b != null && ((typeof Blob !== 'undefined' && b instanceof Blob) || (typeof FormData !== 'undefined' && b instanceof FormData));
}
var yetanoFetch = NATIVE ? nativeFetch : bridgeFetch;
window.fetch = yetanoFetch;
// ---- XMLHttpRequest -------------------------------------------------
// Local URLs go through the bridge (native transport: assets through the
// real XHR from the app origin); external URLs are delegated to the real
// XHR only with cfg.external === 'passthrough'. Re-opening or aborting an
// instance invalidates its earlier call (token), so a late reply for an old
// request never lands in the reused object.
function YetanoXHR() {
var et = new EventTarget();
this._et = et;
this.upload = new EventTarget();
this.readyState = 0; this.status = 0; this.statusText = '';
this.response = null; this.responseText = ''; this.responseType = ''; this.responseURL = '';
this.timeout = 0; this.withCredentials = false;
this._token = 0; this._reqHeaders = {}; this._respHeaders = {}; this._ctl = null; this._sent = false;
}
YetanoXHR.UNSENT = 0; YetanoXHR.OPENED = 1; YetanoXHR.HEADERS_RECEIVED = 2; YetanoXHR.LOADING = 3; YetanoXHR.DONE = 4;
['UNSENT', 'OPENED', 'HEADERS_RECEIVED', 'LOADING', 'DONE'].forEach(function (k, i) { YetanoXHR.prototype[k] = i; });
YetanoXHR.prototype.addEventListener = function (t, f, o) { this._et.addEventListener(t, f, o); };
YetanoXHR.prototype.removeEventListener = function (t, f, o) { this._et.removeEventListener(t, f, o); };
YetanoXHR.prototype.dispatchEvent = function (e) { return this._et.dispatchEvent(e); };
YetanoXHR.prototype._fire = function (type, loaded, total) {
var ev = (type === 'readystatechange') ? new Event(type)
: new ProgressEvent(type, { lengthComputable: total != null, loaded: loaded || 0, total: total || 0 });
var h = this['on' + type];
if (typeof h === 'function') { try { h.call(this, ev); } catch (e) { setTimeout(function () { throw e; }); } }
this._et.dispatchEvent(ev);
};
YetanoXHR.prototype._state = function (s) { this.readyState = s; this._fire('readystatechange'); };
YetanoXHR.prototype.open = function (method, url, async) {
if (async === false) throw new DOMException('yetano: synchronous XMLHttpRequest is not supported', 'InvalidAccessError');
this._token++;
if (this._ctl) { this._ctl.abort(); this._ctl = null; }
if (this._native) { this._native.abort(); this._native = null; }
this._method = String(method || 'GET').toUpperCase();
this._url = String(url);
this._reqHeaders = {}; this._respHeaders = {}; this._sent = false;
this.status = 0; this.statusText = ''; this.response = null; this.responseText = '';
this._state(1);
};
YetanoXHR.prototype.setRequestHeader = function (k, v) {
if (this.readyState !== 1 || this._sent) throw new DOMException('setRequestHeader: invalid state', 'InvalidStateError');
k = String(k).toLowerCase();
this._reqHeaders[k] = this._reqHeaders[k] ? this._reqHeaders[k] + ', ' + v : String(v);
};
YetanoXHR.prototype.overrideMimeType = function (m) { this._mime = m; };
YetanoXHR.prototype.getResponseHeader = function (k) {
var v = this._respHeaders[String(k).toLowerCase()];
return v === undefined ? null : v;
};
YetanoXHR.prototype.getAllResponseHeaders = function () {
var h = this._respHeaders;
return Object.keys(h).sort().map(function (k) { return k + ': ' + h[k] + '\r\n'; }).join('');
};
YetanoXHR.prototype.abort = function () {
var wasActive = this._sent && this.readyState !== 4;
this._token++;
if (this._ctl) { this._ctl.abort(); this._ctl = null; }
if (this._native) { this._native.abort(); this._native = null; }
if (wasActive) { this._sent = false; this._state(4); this._fire('abort'); this._fire('loadend'); }
this.readyState = 0;
};
YetanoXHR.prototype.send = function (body) {
if (this.readyState !== 1 || this._sent) throw new DOMException('send: invalid state', 'InvalidStateError');
var self = this, token = this._token;
var local = localURL(this._url);
if (local === null) return this._sendNative(body, false);
if (NATIVE && isAsset(local)) return this._sendNative(body, true, nativeURL(local));
this._sent = true;
var ctl = new AbortController();
this._ctl = ctl;
var headers = Object.assign({}, this._reqHeaders);
this._fire('loadstart', 0);
(async function () {
var bytes = null;
if (body != null && self._method !== 'GET' && self._method !== 'HEAD') bytes = await toBytes(body, headers);
return request({ method: self._method, url: local, headers: headers, body: bytes, signal: ctl.signal, timeoutMs: self.timeout > 0 ? self.timeout : undefined });
})().then(async function (r) {
if (r.streaming) r.body = new Uint8Array(await new Response(r.body).arrayBuffer());
return r;
}).then(function (r) {
if (token !== self._token) return; // reopened/aborted meanwhile
self._ctl = null;
self.status = r.status; self.statusText = r.statusText; self._respHeaders = r.headers;
self.responseURL = local;
self._state(2);
var type = (self._mime || r.headers['content-type'] || '').split(';')[0].trim();
var text = null;
function asText() { if (text === null) text = new TextDecoder().decode(r.body); return text; }
switch (self.responseType) {
case 'arraybuffer': self.response = r.body.buffer.slice(r.body.byteOffset, r.body.byteOffset + r.body.byteLength); break;
case 'blob': self.response = new Blob([r.body], { type: type }); break;
case 'json': try { self.response = JSON.parse(asText()); } catch (e) { self.response = null; } break;
case 'document': self.response = new DOMParser().parseFromString(asText(), type === 'text/xml' || type === 'application/xml' ? type : 'text/html'); break;
default: self.responseText = self.response = asText();
}
self._state(3);
self._fire('progress', r.body.length, r.body.length);
self._sent = false;
self._state(4);
self._fire('load', r.body.length, r.body.length);
self._fire('loadend', r.body.length, r.body.length);
}, function (e) {
if (token !== self._token) return;
self._ctl = null; self._sent = false;
self.status = 0;
self._state(4);
self._fire(e && e.name === 'TimeoutError' ? 'timeout' : (e && e.name === 'AbortError' ? 'abort' : 'error'));
self._fire('loadend');
});
};
YetanoXHR.prototype._sendNative = function (body, asset, url) {
var self = this;
if (!asset && (cfg.external !== 'passthrough' || !OrigXHR)) {
this._sent = true;
setTimeout(function () {
self._sent = false; self.status = 0; self._state(4);
self._fire('error'); self._fire('loadend');
if (window.console) console.warn(String(externalBlocked(self._url)));
});
return;
}
var x = new OrigXHR();
this._native = x;
this._sent = true;
x.open(this._method, url || this._url, true);
Object.keys(this._reqHeaders).forEach(function (k) { x.setRequestHeader(k, self._reqHeaders[k]); });
x.responseType = this.responseType; x.timeout = this.timeout; x.withCredentials = this.withCredentials;
['readystatechange', 'loadstart', 'progress', 'load', 'error', 'abort', 'timeout', 'loadend'].forEach(function (t) {
x.addEventListener(t, function () {
if (self._native !== x) return;
self.status = x.status; self.statusText = x.statusText; self.response = x.response; self.responseURL = x.responseURL;
if (x.responseType === '' || x.responseType === 'text') self.responseText = x.responseText;
self._respHeaders = {};
(x.getAllResponseHeaders() || '').trim().split(/[\r\n]+/).forEach(function (l) {
var i = l.indexOf(':'); if (i > 0) self._respHeaders[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim();
});
if (t === 'readystatechange') { self._state(x.readyState); } else { self._fire(t); }
});
});
x.send(body);
};
window.XMLHttpRequest = YetanoXHR;
// ---- page console -> host log (diagnostics) ---------------------------
if (cfg.forwardConsole) {
['log', 'warn', 'error'].forEach(function (lvl) {
var orig = console[lvl];
console[lvl] = function () {
try { post({ t: 'log', level: lvl, msg: Array.prototype.map.call(arguments, String).join(' ') }); } catch (e) {}
return orig.apply(console, arguments);
};
});
window.addEventListener('error', function (e) { post({ t: 'log', level: 'error', msg: 'uncaught: ' + e.message + ' @' + e.filename + ':' + e.lineno }); });
window.addEventListener('unhandledrejection', function (e) { post({ t: 'log', level: 'error', msg: 'unhandled rejection: ' + (e.reason && e.reason.stack || e.reason) }); });
}
// ---- public API ------------------------------------------------------
async function call(route, payload, opts) {
opts = opts || {};
var r = await bridgeFetch('/rpc/' + route, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload === undefined ? null : payload),
signal: opts.signal, yetanoTimeout: opts.timeoutMs
});
var text = await r.text();
if (!r.ok) { var err = new Error(route + ': HTTP ' + r.status + ': ' + text); err.status = r.status; throw err; }
return text ? JSON.parse(text) : null;
}
window.yetano = Object.freeze({
__installed: true,
protocol: PROTO,
config: cfg,
transport: NATIVE ? 'native' : 'inline',
bridgeFetch: bridgeFetch,
ready: ready,
fetch: yetanoFetch,
call: call,
pendingCount: function () { return pending.size; },
stats: function () { return { staleDropped: stats.staleDropped, requests: stats.requests, pending: pending.size, generation: gen }; },
_post: cfg.selftest ? post : undefined
});
})();
+72
View File
@@ -0,0 +1,72 @@
package bridge
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
)
// NativeWriter is the response side of a native resource request
// (implemented by window.ResourceWriter).
type NativeWriter interface {
Respond(status int, header http.Header)
Write(p []byte) (int, error)
Close(err error)
}
// ServeNative answers a request the WebView made to the app origin through
// the native resource handler: "/" is the entry document, everything else
// goes through the same router as bridge requests. Stream responses are
// written through as they are produced.
func (r *Router) ServeNative(ctx context.Context, origin, method, rawURL string, header http.Header, body []byte, w NativeWriter) {
if !strings.HasPrefix(rawURL, origin+"/") {
w.Respond(http.StatusForbidden, textHeader())
w.Write([]byte("not the app origin: " + rawURL))
return
}
local := rawURL[len(origin):]
path, q, err := ParseLocalURL(local)
if err != nil {
w.Respond(http.StatusBadRequest, textHeader())
w.Write([]byte(err.Error()))
return
}
if path == "/" {
r.mu.RLock()
entry := r.entry
r.mu.RUnlock()
path = "/assets/" + entry
}
req := &Request{Native: true, Method: strings.ToUpper(method), URL: local, Path: path, Query: q, Header: header, Body: body}
resp, err := r.Serve(ctx, req)
if err != nil {
w.Close(err)
return
}
h := resp.Header
if h == nil {
h = http.Header{}
}
h.Set("Cache-Control", "no-store")
w.Respond(resp.Status, h)
if resp.Stream != nil {
if err := resp.Stream(ctx, w); err != nil && !errors.Is(err, context.Canceled) {
w.Close(fmt.Errorf("%s %s: stream: %w", req.Method, req.Path, err))
return
}
w.Close(nil)
return
}
if len(resp.Body) > 0 {
w.Write(resp.Body)
}
w.Close(nil)
}
func textHeader() http.Header {
h := http.Header{}
h.Set("Content-Type", "text/plain; charset=utf-8")
return h
}
+265
View File
@@ -0,0 +1,265 @@
package bridge
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"runtime/debug"
"sort"
"strings"
"sync"
"yetano.dev/yetano/core/gui/assets"
"yetano.dev/yetano/core/gui/document"
)
// Request is a local request as it arrives from the fetch/XHR adapter or
// the native resource handler.
type Request struct {
Native bool // via the native resource handler (link mode for HTML/CSS)
Method string
URL string // as written by the page ("/rpc/add?x=1", "assets:img/a.png")
Path string // percent-decoded once, without query
Query url.Values
Header http.Header
Body []byte
}
// Response is an HTTP-like local response. 404/500 are responses, not
// transport errors. A handler either sets Body or Stream. Stream writes the
// body incrementally: the native resource handler delivers every Write to
// the page as it happens; the bridge transport buffers it (MaxBody).
type Response struct {
Status int
Header http.Header
Body []byte
Stream func(ctx context.Context, w io.Writer) error
}
// HandlerFunc serves one registered route. Returning an error yields a 500
// response that names the route; a cancelled ctx yields an abort/timeout.
type HandlerFunc func(ctx context.Context, req *Request) (*Response, error)
// Router maps local requests to the asset resolver and to registered Go
// handlers. Routes are fixed before the document starts (Freeze).
type Router struct {
mu sync.RWMutex
routes map[string]HandlerFunc // "METHOD /path"
frozen bool
res *assets.Resolver
entry string // asset served for "/" by the native handler
native bool // document mode: link (native) or inline (bridge)
}
// SetDocument sets the entry asset for "/" and whether Go-generated HTML is
// prepared for the native resource handler (link mode) or inlined.
func (r *Router) SetDocument(entry string, native bool) {
r.mu.Lock()
r.entry, r.native = entry, native
r.mu.Unlock()
}
// NewRouter creates a router that serves GET/HEAD /assets/... and assets:...
// from res.
func NewRouter(res *assets.Resolver) *Router {
return &Router{routes: map[string]HandlerFunc{}, res: res}
}
// Resolver returns the asset resolver behind /assets/.
func (r *Router) Resolver() *assets.Resolver { return r.res }
// Handle registers h for an exact method and path. Duplicate registrations
// and registrations after Freeze are errors.
func (r *Router) Handle(method, path string, h HandlerFunc) error {
method = strings.ToUpper(method)
if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "/assets/") || h == nil {
return fmt.Errorf("bridge: invalid route %s %s", method, path)
}
key := method + " " + path
r.mu.Lock()
defer r.mu.Unlock()
if r.frozen {
return fmt.Errorf("bridge: route %s registered after document start", key)
}
if _, dup := r.routes[key]; dup {
return fmt.Errorf("bridge: duplicate route %s", key)
}
r.routes[key] = h
return nil
}
// Freeze ends registration.
func (r *Router) Freeze() {
r.mu.Lock()
r.frozen = true
r.mu.Unlock()
}
// Routes lists registered routes (diagnostics).
func (r *Router) Routes() []string {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]string, 0, len(r.routes))
for k := range r.routes {
out = append(out, k)
}
sort.Strings(out)
return out
}
// ParseLocalURL splits a page-local URL into path and query. It accepts
// "/x" (not "//x") and "assets:x". The path is percent-decoded exactly once.
func ParseLocalURL(raw string) (path string, q url.Values, err error) {
p, rest := assets.SplitRef(raw)
if strings.HasPrefix(rest, "?") {
qs := rest[1:]
if i := strings.IndexByte(qs, '#'); i >= 0 {
qs = qs[:i]
}
if q, err = url.ParseQuery(qs); err != nil {
return "", nil, fmt.Errorf("bad query: %w", err)
}
}
switch {
case strings.HasPrefix(p, assets.PrefixScheme):
p = assets.PrefixSlash + p[len(assets.PrefixScheme):]
case strings.HasPrefix(p, "/") && !strings.HasPrefix(p, "//"):
default:
return "", nil, fmt.Errorf("not a local URL: %q", raw)
}
dec, err := url.PathUnescape(p)
if err != nil {
return "", nil, fmt.Errorf("bad path escape: %w", err)
}
return dec, q, nil
}
// Serve answers one request. It returns an error only when ctx ended
// (abort, timeout, stale generation, close).
func (r *Router) Serve(ctx context.Context, req *Request) (resp *Response, err error) {
defer func() {
if p := recover(); p != nil {
resp, err = Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: handler panic: %v\n%s", req.Method, req.Path, p, debug.Stack())), nil
}
}()
resp = r.serve(ctx, req)
if cerr := ctx.Err(); cerr != nil {
return nil, context.Cause(ctx)
}
return resp, nil
}
func (r *Router) serve(ctx context.Context, req *Request) *Response {
if strings.HasPrefix(req.Path, assets.PrefixSlash) {
if req.Method != http.MethodGet && req.Method != http.MethodHead {
return Text(http.StatusMethodNotAllowed, "assets are read-only")
}
name := req.Path[len(assets.PrefixSlash):]
res, err := r.res.Resolve(ctx, name)
switch {
case errors.Is(err, assets.ErrInvalidPath):
return Text(http.StatusBadRequest, err.Error())
case errors.Is(err, fs.ErrNotExist):
return Text(http.StatusNotFound, err.Error())
case err != nil:
return Text(http.StatusInternalServerError, err.Error())
}
h := http.Header{}
h.Set("Content-Type", res.MIME)
h.Set("X-Yetano-Asset-Source", res.Source)
body := res.Bytes
if req.Native {
// Natively loaded HTML/CSS: assets: references become /assets/
// URLs the WebView can load; nothing is inlined.
var err error
switch assets.BaseMIME(res.MIME) {
case "text/html":
var doc *document.Result
if doc, err = document.Prepare(ctx, r.res, name, body, document.Options{Link: true}); err == nil {
body = doc.HTML
}
case "text/css":
body, err = document.PrepareCSS(ctx, r.res, name, body, document.Options{Link: true})
}
if err != nil {
return Text(http.StatusInternalServerError, err.Error())
}
}
if req.Method == http.MethodHead {
h.Set("Content-Length", fmt.Sprint(len(body)))
body = nil
}
return &Response{Status: http.StatusOK, Header: h, Body: body}
}
r.mu.RLock()
h, ok := r.routes[req.Method+" "+req.Path]
if !ok && req.Method == http.MethodHead {
h, ok = r.routes["GET "+req.Path]
}
known := false
if !ok {
for k := range r.routes {
if strings.HasSuffix(k, " "+req.Path) {
known = true
}
}
}
r.mu.RUnlock()
if !ok {
if known {
return Text(http.StatusMethodNotAllowed, fmt.Sprintf("%s not allowed for %s", req.Method, req.Path))
}
return Text(http.StatusNotFound, "no route for "+req.Method+" "+req.Path)
}
resp, err := h(ctx, req)
if err != nil {
if ctx.Err() != nil {
return nil
}
return Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: %v", req.Method, req.Path, err))
}
if resp == nil {
resp = &Response{Status: http.StatusNoContent}
}
if resp.Status < 200 || resp.Status > 599 {
return Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: handler returned invalid status %d", req.Method, req.Path, resp.Status))
}
if req.Method == http.MethodHead {
resp.Body = nil
}
return resp
}
// Text builds a text/plain response.
func Text(status int, body string) *Response {
h := http.Header{}
h.Set("Content-Type", "text/plain; charset=utf-8")
return &Response{Status: status, Header: h, Body: []byte(body)}
}
// JSONBytes builds an application/json response from already-encoded JSON.
func JSONBytes(status int, body []byte) *Response {
h := http.Header{}
h.Set("Content-Type", "application/json")
return &Response{Status: status, Header: h, Body: body}
}
// HTML prepares Go-generated HTML through the same asset replace as the entry
// document and returns it as a text/html response.
func (r *Router) HTML(ctx context.Context, name string, src []byte) (*Response, error) {
r.mu.RLock()
link := r.native
r.mu.RUnlock()
doc, err := document.Prepare(ctx, r.res, name, src, document.Options{Link: link})
if err != nil {
return nil, err
}
h := http.Header{}
h.Set("Content-Type", "text/html; charset=utf-8")
return &Response{Status: http.StatusOK, Header: h, Body: doc.HTML}, nil
}
+32
View File
@@ -0,0 +1,32 @@
package bridge
import (
_ "embed"
"encoding/json"
)
//go:embed bridge.js
var bridgeJS string
// PageConfig is exposed to the page as window.__yetano_config (and
// window.yetano.config) before the bridge installs itself.
type PageConfig struct {
External string `json:"external"` // "reject" (default) or "passthrough"
Transport string `json:"transport"` // "native" (scheme handler) or "inline" (data: entry, bridge only)
Origin string `json:"origin,omitempty"`
DefaultTimeoutMs int `json:"defaultTimeoutMs,omitempty"`
HandshakeTimeoutMs int `json:"handshakeTimeoutMs,omitempty"`
ForwardConsole bool `json:"forwardConsole,omitempty"`
Selftest bool `json:"selftest,omitempty"`
Run int `json:"run,omitempty"`
ProtocolOverride int `json:"protocolOverride,omitempty"` // tests only
}
// InitScript returns the document-start script: config + bridge.
func InitScript(cfg PageConfig) string {
if cfg.External == "" {
cfg.External = "reject"
}
b, _ := json.Marshal(cfg)
return "window.__yetano_config=" + string(b) + ";\n" + bridgeJS
}
+477
View File
@@ -0,0 +1,477 @@
// Package bridge connects the page and the Go host without any network
// listener: one native binding (__yetano_post) carries JSON messages from
// JS to Go; replies go back through Dispatch+Eval on the UI thread.
//
// Protocol v1 (all messages are JSON objects with a "t" field):
//
// JS -> Go {t:"hello", v, nonce}
// JS -> Go {t:"req", id, gen, method, url, headers, body(base64|null), timeoutMs}
// JS -> Go {t:"abort", id, gen, reason}
// JS -> Go {t:"log", level, msg}
// Go -> JS {t:"ready", v, gen, nonce, session} or {t:"ready", nonce, error}
// Go -> JS {t:"res", id, gen, status, statusText, headers, body(base64)}
// Go -> JS {t:"err", id, gen, code, message} code: abort|timeout|stale|closed|protocol
//
// Every document load sends a new hello and gets a new generation. Calls of
// an older generation are cancelled and their results are dropped, both in Go
// (before Dispatch and again on the UI thread) and in JS.
package bridge
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
// ProtocolVersion is the bridge wire version.
const ProtocolVersion = 1
// Binding is the name of the single native binding.
const Binding = "__yetano_post"
// Cancellation causes reported to handlers via context.Cause.
var (
ErrAborted = errors.New("request aborted by page")
ErrTimeout = errors.New("request timed out")
ErrStale = errors.New("document generation replaced (reload/navigation)")
ErrClosed = errors.New("session closed")
)
// Dispatcher is the part of the native window the session needs. Dispatch
// must be safe from any goroutine and run f on the UI thread; Eval is only
// called from inside such an f.
type Dispatcher interface {
Dispatch(f func())
Eval(js string)
}
// Options configure a session.
type Options struct {
MaxBody int // max request body (decoded); default 8 MiB
MaxTimeout time.Duration // upper bound for any call; default 60s
CloseWait time.Duration // how long Close waits for handlers; default 5s
Logf func(format string, args ...any)
OnPageLog func(level, msg string)
OnHello func(gen uint64) // called after a new generation started
}
// Stats are counters for diagnostics and tests.
type Stats struct {
Generation uint64 `json:"generation"`
Hellos uint64 `json:"hellos"`
Requests uint64 `json:"requests"`
Completed uint64 `json:"completed"`
Cancelled uint64 `json:"cancelled"`
DroppedStale uint64 `json:"droppedStale"`
DroppedClosed uint64 `json:"droppedClosed"`
ProtocolErrors uint64 `json:"protocolErrors"`
Pending int `json:"pending"`
}
type call struct {
gen uint64
cancel context.CancelCauseFunc
}
// Session owns the bridge state of one window.
type Session struct {
id string
router *Router
opt Options
mu sync.Mutex
d Dispatcher
gen uint64
closed bool
calls map[string]*call
wg sync.WaitGroup
hellos, requests, completed, cancelled atomic.Uint64
droppedStale, droppedClosed, protocolErrors atomic.Uint64
}
// NewSession creates a session for router. The router is frozen.
func NewSession(router *Router, opt Options) *Session {
if opt.MaxBody == 0 {
opt.MaxBody = 8 << 20
}
if opt.MaxTimeout == 0 {
opt.MaxTimeout = 60 * time.Second
}
if opt.CloseWait == 0 {
opt.CloseWait = 5 * time.Second
}
if opt.Logf == nil {
opt.Logf = func(string, ...any) {}
}
router.Freeze()
var b [8]byte
_, _ = rand.Read(b[:])
return &Session{id: hex.EncodeToString(b[:]), router: router, opt: opt, calls: map[string]*call{}}
}
// Attach sets the dispatcher (the native window). Must happen before the
// first message.
func (s *Session) Attach(d Dispatcher) {
s.mu.Lock()
s.d = d
s.mu.Unlock()
}
// ID returns the random session id.
func (s *Session) ID() string { return s.id }
// Stats returns a snapshot of the counters.
func (s *Session) Stats() Stats {
s.mu.Lock()
gen, pending := s.gen, len(s.calls)
s.mu.Unlock()
return Stats{
Generation: gen, Hellos: s.hellos.Load(), Requests: s.requests.Load(),
Completed: s.completed.Load(), Cancelled: s.cancelled.Load(),
DroppedStale: s.droppedStale.Load(), DroppedClosed: s.droppedClosed.Load(),
ProtocolErrors: s.protocolErrors.Load(), Pending: pending,
}
}
type inMsg struct {
T string `json:"t"`
V int `json:"v"`
Nonce string `json:"nonce"`
ID string `json:"id"`
Gen uint64 `json:"gen"`
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Body *string `json:"body"`
TimeoutMs int64 `json:"timeoutMs"`
Reason string `json:"reason"`
Level string `json:"level"`
Msg string `json:"msg"`
}
// Post is the native binding target. It only decodes and enqueues; all work
// happens on other goroutines, so the UI thread is never blocked.
func (s *Session) Post(raw json.RawMessage) {
var m inMsg
if err := json.Unmarshal(raw, &m); err != nil {
s.protocolErrors.Add(1)
s.opt.Logf("bridge: undecodable message: %v", err)
return
}
switch m.T {
case "hello":
s.hello(m)
case "req":
s.request(m)
case "abort":
s.abort(m)
case "log":
if s.opt.OnPageLog != nil {
s.opt.OnPageLog(m.Level, m.Msg)
}
default:
s.protocolErrors.Add(1)
s.opt.Logf("bridge: unknown message type %q", m.T)
if m.ID != "" {
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": "protocol", "message": "unknown message type " + m.T})
}
}
}
func (s *Session) hello(m inMsg) {
s.hellos.Add(1)
if m.V != ProtocolVersion {
s.protocolErrors.Add(1)
s.mu.Lock()
gen := s.gen
s.mu.Unlock()
// Reply on the current generation so the page sees the refusal.
s.sendAny(gen, map[string]any{"t": "ready", "nonce": m.Nonce, "error": fmt.Sprintf("unsupported bridge protocol %d (host speaks %d)", m.V, ProtocolVersion)})
return
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return
}
s.gen++
gen := s.gen
for id, c := range s.calls {
if c.gen < gen {
c.cancel(ErrStale)
delete(s.calls, id)
}
}
s.mu.Unlock()
s.send(gen, map[string]any{"t": "ready", "v": ProtocolVersion, "gen": gen, "nonce": m.Nonce, "session": s.id})
if s.opt.OnHello != nil {
s.opt.OnHello(gen)
}
}
func (s *Session) request(m inMsg) {
s.requests.Add(1)
fail := func(code, msg string) {
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": code, "message": msg})
}
if m.ID == "" {
s.protocolErrors.Add(1)
return
}
method := strings.ToUpper(m.Method)
if method == "" {
method = http.MethodGet
}
path, q, err := ParseLocalURL(m.URL)
if err != nil {
// A bad URL is a response (400), not a transport failure.
s.respond(m.Gen, m.ID, Text(http.StatusBadRequest, err.Error()))
return
}
var body []byte
if m.Body != nil {
if base64.StdEncoding.DecodedLen(len(*m.Body)) > s.opt.MaxBody+3 {
s.respond(m.Gen, m.ID, Text(http.StatusRequestEntityTooLarge, "request body too large"))
return
}
if body, err = base64.StdEncoding.DecodeString(*m.Body); err != nil {
s.protocolErrors.Add(1)
fail("protocol", "request body is not valid base64")
return
}
}
h := http.Header{}
for k, v := range m.Headers {
h.Set(k, v)
}
timeout := s.opt.MaxTimeout
if m.TimeoutMs > 0 && time.Duration(m.TimeoutMs)*time.Millisecond < timeout {
timeout = time.Duration(m.TimeoutMs) * time.Millisecond
}
s.mu.Lock()
switch {
case s.closed:
s.mu.Unlock()
s.droppedClosed.Add(1)
return
case m.Gen != s.gen:
s.mu.Unlock()
s.droppedStale.Add(1)
return
}
if _, dup := s.calls[m.ID]; dup {
s.mu.Unlock()
s.protocolErrors.Add(1)
fail("protocol", "duplicate request id")
return
}
ctx, cancel := context.WithCancelCause(context.Background())
ctx, cancelTimeout := context.WithTimeoutCause(ctx, timeout, ErrTimeout)
s.calls[m.ID] = &call{gen: m.Gen, cancel: cancel}
s.wg.Add(1)
s.mu.Unlock()
req := &Request{Method: method, URL: m.URL, Path: path, Query: q, Header: h, Body: body}
go func() {
defer s.wg.Done()
defer cancelTimeout()
resp, err := s.router.Serve(ctx, req)
if err == nil && resp.Stream != nil {
s.stream(ctx, cancel, m, req, resp)
return
}
s.mu.Lock()
_, live := s.calls[m.ID]
delete(s.calls, m.ID)
s.mu.Unlock()
cancel(nil)
if err != nil {
s.cancelled.Add(1)
code := "abort"
switch {
case errors.Is(err, ErrTimeout):
code = "timeout"
case errors.Is(err, ErrStale):
code = "stale"
case errors.Is(err, ErrClosed):
code = "closed"
}
// A call removed by abort/hello/Close already ended on the
// page side; only a host-side deadline still needs a reply.
if live {
fail(code, err.Error())
}
return
}
if !live {
s.droppedStale.Add(1)
return
}
s.completed.Add(1)
s.respond(m.Gen, m.ID, resp)
}()
}
func (s *Session) abort(m inMsg) {
s.mu.Lock()
c, ok := s.calls[m.ID]
if ok && c.gen == m.Gen {
delete(s.calls, m.ID)
}
s.mu.Unlock()
if ok && c.gen == m.Gen {
if m.Reason == "timeout" {
c.cancel(ErrTimeout)
} else {
c.cancel(ErrAborted)
}
}
}
func (s *Session) respond(gen uint64, id string, r *Response) {
hdr := map[string]string{}
for k, v := range r.Header {
hdr[strings.ToLower(k)] = strings.Join(v, ", ")
}
s.send(gen, map[string]any{
"t": "res", "id": id, "gen": gen, "status": r.Status, "statusText": http.StatusText(r.Status),
"headers": hdr, "body": base64.StdEncoding.EncodeToString(r.Body),
})
}
// send delivers msg to the page if gen is still the current generation and
// the session is open; otherwise the message is dropped and counted.
func (s *Session) send(gen uint64, msg map[string]any) { s.deliver(gen, msg, true) }
// sendAny delivers without a generation check (protocol refusal).
func (s *Session) sendAny(gen uint64, msg map[string]any) { s.deliver(gen, msg, false) }
func (s *Session) deliver(gen uint64, msg map[string]any, checkGen bool) {
b, err := json.Marshal(msg)
if err != nil {
s.opt.Logf("bridge: marshal: %v", err)
return
}
// json.Marshal escapes <, >, &, U+2028 and U+2029, so b is a safe JS
// expression.
js := "window.__yetano_recv&&window.__yetano_recv(" + string(b) + ")"
ok := func() bool {
if s.closed {
s.droppedClosed.Add(1)
return false
}
if checkGen && gen != s.gen {
s.droppedStale.Add(1)
return false
}
return true
}
s.mu.Lock()
d := s.d
if !ok() || d == nil {
s.mu.Unlock()
return
}
s.mu.Unlock()
d.Dispatch(func() {
// Re-check on the UI thread: a reload or Close may have happened
// while this closure was queued.
s.mu.Lock()
live := ok()
s.mu.Unlock()
if live {
d.Eval(js)
}
})
}
// stream delivers a Stream response as res(stream:true), chunk..., end.
// The call stays registered (abortable, generation-bound) until the end.
func (s *Session) stream(ctx context.Context, cancel context.CancelCauseFunc, m inMsg, req *Request, resp *Response) {
hdr := map[string]string{}
for k, v := range resp.Header {
hdr[strings.ToLower(k)] = strings.Join(v, ", ")
}
s.send(m.Gen, map[string]any{"t": "res", "id": m.ID, "gen": m.Gen, "status": resp.Status,
"statusText": http.StatusText(resp.Status), "headers": hdr, "stream": true})
serr := resp.Stream(ctx, &chunkWriter{s: s, ctx: ctx, gen: m.Gen, id: m.ID})
cerr := ctx.Err()
s.mu.Lock()
_, live := s.calls[m.ID]
delete(s.calls, m.ID)
s.mu.Unlock()
cancel(nil)
switch {
case cerr != nil:
s.cancelled.Add(1)
if live { // host-side deadline; page-side ends are already settled
code := "abort"
if errors.Is(context.Cause(ctx), ErrTimeout) {
code = "timeout"
}
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": code, "message": context.Cause(ctx).Error()})
}
case serr != nil:
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": "stream", "message": fmt.Sprintf("%s %s: %v", req.Method, req.Path, serr)})
default:
s.completed.Add(1)
s.send(m.Gen, map[string]any{"t": "end", "id": m.ID, "gen": m.Gen})
}
}
// chunkWriter sends every Write as chunk message(s) of at most 192 KiB.
type chunkWriter struct {
s *Session
ctx context.Context
gen uint64
id string
}
func (w *chunkWriter) Write(p []byte) (int, error) {
const max = 192 << 10
for off := 0; off < len(p); off += max {
if err := w.ctx.Err(); err != nil {
return off, context.Cause(w.ctx)
}
end := min(off+max, len(p))
w.s.send(w.gen, map[string]any{"t": "chunk", "id": w.id, "gen": w.gen, "data": base64.StdEncoding.EncodeToString(p[off:end])})
}
return len(p), nil
}
// Close blocks new calls, invalidates the generation, cancels running
// handlers and waits (bounded) for them. It never needs the UI thread, so it
// can be called after the native loop ended and before the window is
// destroyed. Close is idempotent.
func (s *Session) Close() error {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return nil
}
s.closed = true
for id, c := range s.calls {
c.cancel(ErrClosed)
delete(s.calls, id)
}
s.mu.Unlock()
done := make(chan struct{})
go func() { s.wg.Wait(); close(done) }()
select {
case <-done:
return nil
case <-time.After(s.opt.CloseWait):
return fmt.Errorf("bridge: handlers still running %s after close (they ignore their context)", s.opt.CloseWait)
}
}
+358
View File
@@ -0,0 +1,358 @@
package bridge
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"testing"
"testing/fstest"
"time"
"yetano.dev/yetano/core/gui/assets"
)
// fakeUI runs dispatched functions serially on one goroutine (like a UI
// thread) and decodes every Eval into a message.
type fakeUI struct {
q chan func()
msgs chan map[string]any
once sync.Once
}
func newFakeUI() *fakeUI {
u := &fakeUI{q: make(chan func(), 256), msgs: make(chan map[string]any, 256)}
go func() {
for f := range u.q {
f()
}
}()
return u
}
func (u *fakeUI) Dispatch(f func()) { u.q <- f }
func (u *fakeUI) Eval(js string) {
const p = "window.__yetano_recv&&window.__yetano_recv("
var m map[string]any
if err := json.Unmarshal([]byte(strings.TrimSuffix(strings.TrimPrefix(js, p), ")")), &m); err != nil {
panic(err)
}
u.msgs <- m
}
func (u *fakeUI) next(t *testing.T) map[string]any {
t.Helper()
select {
case m := <-u.msgs:
return m
case <-time.After(3 * time.Second):
t.Fatal("no message")
return nil
}
}
func (u *fakeUI) none(t *testing.T, d time.Duration) {
t.Helper()
select {
case m := <-u.msgs:
t.Fatalf("unexpected message %v", m)
case <-time.After(d):
}
}
type harness struct {
s *Session
ui *fakeUI
started chan string
causes chan error
}
func newHarness(t *testing.T) *harness {
res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{"a.wasm": {Data: []byte("\x00asm\x01\x00\x00\x00")}}))
r := NewRouter(res)
h := &harness{ui: newFakeUI(), started: make(chan string, 16), causes: make(chan error, 16)}
must := func(err error) {
if err != nil {
t.Fatal(err)
}
}
must(r.Handle("POST", "/rpc/add", func(_ context.Context, req *Request) (*Response, error) {
var in struct{ A, B int }
json.Unmarshal(req.Body, &in)
return JSONBytes(200, []byte(fmt.Sprintf(`{"result":%d}`, in.A+in.B))), nil
}))
must(r.Handle("POST", "/rpc/block", func(ctx context.Context, req *Request) (*Response, error) {
h.started <- string(req.Body)
<-ctx.Done()
h.causes <- context.Cause(ctx)
return nil, ctx.Err()
}))
must(r.Handle("GET", "/rpc/panic", func(context.Context, *Request) (*Response, error) { panic("boom") }))
if err := r.Handle("POST", "/rpc/add", nil); err == nil {
t.Fatal("nil/duplicate handler accepted")
}
if err := r.Handle("POST", "/rpc/add", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil {
t.Fatal("duplicate route accepted")
}
h.s = NewSession(r, Options{CloseWait: time.Second})
if err := r.Handle("GET", "/late", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil {
t.Fatal("route after session start accepted")
}
h.s.Attach(h.ui)
t.Cleanup(func() { h.s.Close() })
return h
}
func (h *harness) post(v any) {
b, _ := json.Marshal(v)
h.s.Post(b)
}
func (h *harness) hello(t *testing.T) uint64 {
h.post(map[string]any{"t": "hello", "v": ProtocolVersion, "nonce": "n"})
m := h.ui.next(t)
if m["t"] != "ready" || m["nonce"] != "n" {
t.Fatalf("ready: %v", m)
}
return uint64(m["gen"].(float64))
}
func (h *harness) req(gen uint64, id, method, url, body string) {
var b *string
if body != "" {
e := base64.StdEncoding.EncodeToString([]byte(body))
b = &e
}
h.post(map[string]any{"t": "req", "id": id, "gen": gen, "method": method, "url": url, "body": b})
}
func body(t *testing.T, m map[string]any) string {
b, err := base64.StdEncoding.DecodeString(m["body"].(string))
if err != nil {
t.Fatal(err)
}
return string(b)
}
func TestRoundtripAndResponses(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/add", `{"a":3,"b":4}`)
m := h.ui.next(t)
if m["t"] != "res" || m["id"] != "1" || m["status"].(float64) != 200 || body(t, m) != `{"result":7}` {
t.Fatalf("%v", m)
}
cases := map[string]float64{"/rpc/nope": 404, "/rpc/panic": 500, "/assets/../x": 400, "/assets/a.wasm": 200, "assets:a.wasm": 200, "//evil/x": 400, "/assets/missing": 404}
i := 10
for u, want := range cases {
i++
h.req(g, fmt.Sprint(i), "GET", u, "")
m := h.ui.next(t)
if m["status"].(float64) != want {
t.Errorf("%s: %v", u, m["status"])
}
if u == "/assets/a.wasm" && m["headers"].(map[string]any)["content-type"] != "application/wasm" {
t.Errorf("wasm mime: %v", m["headers"])
}
}
h.req(g, "h", "HEAD", "/assets/a.wasm", "")
if m := h.ui.next(t); body(t, m) != "" || m["headers"].(map[string]any)["content-length"] != "8" {
t.Errorf("HEAD: %v", m)
}
h.req(g, "m", "PUT", "/rpc/add", "")
if m := h.ui.next(t); m["status"].(float64) != 405 {
t.Errorf("405: %v", m)
}
}
func TestProtocolVersionMismatch(t *testing.T) {
h := newHarness(t)
h.post(map[string]any{"t": "hello", "v": 99, "nonce": "x"})
m := h.ui.next(t)
if m["t"] != "ready" || !strings.Contains(fmt.Sprint(m["error"]), "unsupported bridge protocol 99") {
t.Fatalf("%v", m)
}
if h.s.Stats().Generation != 0 {
t.Error("generation advanced on refused hello")
}
}
func TestAbortReachesHandler(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/block", "x")
<-h.started
h.post(map[string]any{"t": "abort", "id": "1", "gen": g})
if c := <-h.causes; !errors.Is(c, ErrAborted) {
t.Fatalf("cause %v", c)
}
h.ui.none(t, 100*time.Millisecond) // the page already settled the call
}
func TestStaleGenerationCancelledAndDropped(t *testing.T) {
h := newHarness(t)
g1 := h.hello(t)
h.req(g1, "1", "POST", "/rpc/block", "old")
<-h.started
g2 := h.hello(t) // reload
if g2 != g1+1 {
t.Fatalf("gen %d -> %d", g1, g2)
}
if c := <-h.causes; !errors.Is(c, ErrStale) {
t.Fatalf("cause %v", c)
}
h.ui.none(t, 100*time.Millisecond)
// A request still tagged with the old generation is dropped.
h.req(g1, "2", "POST", "/rpc/add", `{"a":1,"b":1}`)
h.ui.none(t, 100*time.Millisecond)
if h.s.Stats().DroppedStale == 0 {
t.Error("stale request not counted")
}
}
func TestCloseCancelsAndBlocksDelivery(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/block", "x")
<-h.started
if err := h.s.Close(); err != nil {
t.Fatal(err)
}
if c := <-h.causes; !errors.Is(c, ErrClosed) {
t.Fatalf("cause %v", c)
}
if err := h.s.Close(); err != nil {
t.Fatal("second close", err)
}
h.req(g, "2", "POST", "/rpc/add", `{"a":1,"b":1}`)
h.ui.none(t, 100*time.Millisecond)
if st := h.s.Stats(); st.Pending != 0 || st.DroppedClosed == 0 {
t.Errorf("%+v", st)
}
}
func TestDuplicateIDAndBadMessages(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/block", "x")
<-h.started
h.req(g, "1", "POST", "/rpc/add", `{}`)
if m := h.ui.next(t); m["code"] != "protocol" {
t.Fatalf("%v", m)
}
h.s.Post(json.RawMessage(`"string"`))
h.s.Post(json.RawMessage(`{"t":"bogus","id":"z","gen":1}`))
if m := h.ui.next(t); m["code"] != "protocol" {
t.Fatalf("%v", m)
}
if h.s.Stats().ProtocolErrors < 3 {
t.Errorf("%+v", h.s.Stats())
}
}
func TestHostTimeout(t *testing.T) {
res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{}))
r := NewRouter(res)
r.Handle("GET", "/slow", func(ctx context.Context, _ *Request) (*Response, error) { <-ctx.Done(); return nil, ctx.Err() })
s := NewSession(r, Options{MaxTimeout: 50 * time.Millisecond})
ui := newFakeUI()
s.Attach(ui)
defer s.Close()
s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`))
ui.next(t)
s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/slow"}`))
if m := ui.next(t); m["t"] != "err" || m["code"] != "timeout" {
t.Fatalf("%v", m)
}
}
func TestParseLocalURL(t *testing.T) {
p, q, err := ParseLocalURL("assets:img/a.png?x=1#f")
if err != nil || p != "/assets/img/a.png" || q.Get("x") != "1" {
t.Fatal(p, q, err)
}
if p, _, _ := ParseLocalURL("/assets/%252e"); p != "/assets/%2e" {
t.Errorf("decoded more than once: %q", p)
}
for _, bad := range []string{"https://x/y", "//x/y", "rel/path", "/a%zz"} {
if _, _, err := ParseLocalURL(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
}
func TestInitScript(t *testing.T) {
js := InitScript(PageConfig{Selftest: true})
if !strings.HasPrefix(js, `window.__yetano_config={"external":"reject"`) || !strings.Contains(js, "__yetano_post") {
t.Fatal(js[:120])
}
_ = http.StatusOK
}
func TestStreamChunksAndAbort(t *testing.T) {
res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{}))
r := NewRouter(res)
causes := make(chan error, 1)
r.Handle("GET", "/s", func(context.Context, *Request) (*Response, error) {
return &Response{Status: 200, Stream: func(ctx context.Context, w io.Writer) error {
for i := 0; ; i++ {
if _, err := fmt.Fprintf(w, "c%d", i); err != nil {
causes <- err
return err
}
if i == 2 {
// after three chunks wait for the page to abort
<-ctx.Done()
causes <- context.Cause(ctx)
return ctx.Err()
}
}
}}, nil
})
r.Handle("GET", "/done", func(context.Context, *Request) (*Response, error) {
return &Response{Status: 201, Stream: func(_ context.Context, w io.Writer) error {
w.Write(make([]byte, 400<<10)) // split into 192 KiB chunks
return nil
}}, nil
})
s := NewSession(r, Options{})
ui := newFakeUI()
s.Attach(ui)
defer s.Close()
s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`))
ui.next(t)
s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/s"}`))
if m := ui.next(t); m["t"] != "res" || m["stream"] != true {
t.Fatalf("head: %v", m)
}
for i := 0; i < 3; i++ {
if m := ui.next(t); m["t"] != "chunk" {
t.Fatalf("chunk %d: %v", i, m)
}
}
s.Post(json.RawMessage(`{"t":"abort","id":"1","gen":1}`))
if c := <-causes; !errors.Is(c, ErrAborted) {
t.Fatalf("cause %v", c)
}
ui.none(t, 100*time.Millisecond) // page already ended the stream: no end/err
s.Post(json.RawMessage(`{"t":"req","id":"2","gen":1,"method":"GET","url":"/done"}`))
if m := ui.next(t); m["status"].(float64) != 201 {
t.Fatalf("%v", m)
}
total := 0
for {
m := ui.next(t)
if m["t"] == "end" {
break
}
b, _ := base64.StdEncoding.DecodeString(m["data"].(string))
total += len(b)
}
if total != 400<<10 {
t.Fatalf("streamed %d bytes", total)
}
}
+23
View File
@@ -0,0 +1,23 @@
// Package gui is the native WebView host shared by Yetano desktop
// programs: a native window with a WebView that shows embedded HTML/CSS/JS
// and routes the page's fetch/XHR to Go handlers -- without any local web
// server, port or localhost listener.
//
// The host lives in four subpackages:
//
// - [yetano.dev/yetano/core/gui/assets]: asset resolver over embed.FS,
// a directory (os.Root), a ZIP file or ZIP bytes; path rules, MIME.
// - [yetano.dev/yetano/core/gui/document]: prepares the entry HTML and
// CSS (link mode: /assets/ URLs, validated; inline mode: data: URLs).
// - [yetano.dev/yetano/core/gui/bridge]: the page script (fetch/XHR
// replacement), protocol v1 with chunked streams, Session, Router and
// ServeNative for the native resource handler.
// - [yetano.dev/yetano/core/gui/window]: the native window: macOS
// (Cocoa + WKWebView, cgo, scheme yetano://app) and Windows (Win32 +
// WebView2, pure Go, https://yetano.invalid). Other platforms return
// window.ErrUnsupported.
//
// This is a separate Go module (yetano.dev/yetano/core/gui, tags gui/vX.Y.Z)
// so the main core module stays free of cgo and WebView dependencies. See
// README.md for wiring, invariants and the platform pitfalls.
package gui
+267
View File
@@ -0,0 +1,267 @@
package document
import (
"context"
"fmt"
"strings"
"yetano.dev/yetano/core/gui/assets"
)
// rewriteCSS replaces url(...) and @import references in css. base is the
// virtual path of the stylesheet ("" for CSS embedded in the entry HTML);
// relative references resolve against it. Comments and strings outside of
// url()/@import are copied untouched.
func (p *preparer) rewriteCSS(ctx context.Context, css, base string) (string, error) {
var out strings.Builder
i := 0
n := len(css)
for i < n {
c := css[i]
switch {
case c == '/' && i+1 < n && css[i+1] == '*':
end := strings.Index(css[i+2:], "*/")
if end < 0 {
out.WriteString(css[i:])
return out.String(), nil
}
out.WriteString(css[i : i+2+end+2])
i += 2 + end + 2
case c == '"' || c == '\'':
j := skipString(css, i)
out.WriteString(css[i:j])
i = j
case c == '\\' && i+1 < n:
out.WriteString(css[i : i+2])
i += 2
case hasFoldPrefix(css[i:], "url(") && isIdentBoundary(css, i):
ref, end, ok := parseURLToken(css, i+4)
if !ok {
out.WriteByte(c)
i++
continue
}
repl, err := p.cssRef(ctx, ref, base, false)
if err != nil {
return "", err
}
if repl == strings.TrimSpace(ref) {
out.WriteString(css[i:end]) // not an asset: byte-identical
} else {
out.WriteString("url(" + quoteCSS(repl) + ")")
}
i = end
case c == '@' && hasFoldPrefix(css[i:], "@import") && i+7 < n && !isIdentChar(css[i+7]):
j := i + 7
for j < n && isSpace(css[j]) {
j++
}
var ref string
var end int
switch {
case j < n && (css[j] == '"' || css[j] == '\''):
end = skipString(css, j)
ref = unquoteCSS(css[j:end])
case hasFoldPrefix(css[j:], "url("):
var ok bool
ref, end, ok = parseURLToken(css, j+4)
if !ok {
out.WriteString(css[i:j])
i = j
continue
}
default:
out.WriteString(css[i:j])
i = j
continue
}
repl, err := p.cssRef(ctx, ref, base, true)
if err != nil {
return "", err
}
if repl == strings.TrimSpace(ref) {
out.WriteString(css[i:end])
} else {
out.WriteString("@import url(" + quoteCSS(repl) + ")")
}
i = end
default:
out.WriteByte(c)
i++
}
}
return out.String(), nil
}
// cssRef resolves one reference found in CSS. Data URLs, fragments and
// external URLs are left alone.
func (p *preparer) cssRef(ctx context.Context, ref, base string, isImport bool) (string, error) {
ref = strings.TrimSpace(ref)
var name string
var err error
switch {
case ref == "" || strings.HasPrefix(ref, "#") || strings.HasPrefix(ref, "data:"):
return ref, nil
case assets.IsAssetRef(ref):
name, err = assets.FromRef(ref)
case hasScheme(ref) || strings.HasPrefix(ref, "//") || strings.HasPrefix(ref, "/"):
return ref, nil // external or not an asset: untouched
case base != "":
pth, _ := assets.SplitRef(ref)
name, err = assets.Join(base, pth)
if err == nil && p.link {
// The WebView resolves relative URLs itself; only validate.
if _, err := p.resolve(ctx, name, base); err != nil {
return "", err
}
return ref, nil
}
default:
return ref, nil // relative ref in entry-level CSS: not an asset reference
}
if err != nil {
return "", p.fail(base, ref, err)
}
if p.link {
return p.assetDataURL(ctx, name, base)
}
if isImport {
css, err := p.loadCSS(ctx, name)
if err != nil {
return "", err
}
return dataURL("text/css;charset=utf-8", []byte(css)), nil
}
if assets.BaseMIME(mimeOf(name)) == "text/css" {
css, err := p.loadCSS(ctx, name)
if err != nil {
return "", err
}
return dataURL("text/css;charset=utf-8", []byte(css)), nil
}
return p.assetDataURL(ctx, name, base)
}
// loadCSS loads and rewrites a stylesheet asset, detecting @import cycles.
func (p *preparer) loadCSS(ctx context.Context, name string) (string, error) {
for _, s := range p.cssStack {
if s == name {
return "", fmt.Errorf("css @import cycle: %s -> %s", strings.Join(p.cssStack, " -> "), name)
}
}
res, err := p.resolve(ctx, name, p.current())
if err != nil {
return "", err
}
if assets.BaseMIME(res.MIME) != "text/css" {
return "", fmt.Errorf("%s: expected text/css, got %s", name, res.MIME)
}
p.cssStack = append(p.cssStack, name)
defer func() { p.cssStack = p.cssStack[:len(p.cssStack)-1] }()
return p.rewriteCSS(ctx, string(res.Bytes), name)
}
func (p *preparer) current() string {
if len(p.cssStack) == 0 {
return p.entry
}
return p.cssStack[len(p.cssStack)-1]
}
// parseURLToken parses the inside of url( ... ) starting at i and returns the
// reference and the index after ')'.
func parseURLToken(s string, i int) (string, int, bool) {
n := len(s)
for i < n && isSpace(s[i]) {
i++
}
if i < n && (s[i] == '"' || s[i] == '\'') {
end := skipString(s, i)
ref := unquoteCSS(s[i:end])
j := end
for j < n && isSpace(s[j]) {
j++
}
if j >= n || s[j] != ')' {
return "", 0, false
}
return ref, j + 1, true
}
start := i
for i < n && s[i] != ')' {
if s[i] == '\\' {
i++
}
i++
}
if i >= n {
return "", 0, false
}
return strings.TrimSpace(s[start:i]), i + 1, true
}
func skipString(s string, i int) int {
q := s[i]
j := i + 1
for j < len(s) {
switch s[j] {
case '\\':
j += 2
continue
case q:
return j + 1
case '\n':
return j
}
j++
}
return len(s)
}
func unquoteCSS(s string) string {
if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') && s[len(s)-1] == s[0] {
s = s[1 : len(s)-1]
}
// Minimal unescape: "\x" -> "x" (hex escapes are not used in asset paths).
if strings.IndexByte(s, '\\') < 0 {
return s
}
var b strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '\\' && i+1 < len(s) {
i++
}
b.WriteByte(s[i])
}
return b.String()
}
func quoteCSS(s string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\a `).Replace(s) + `"`
}
func hasFoldPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
}
func isIdentChar(c byte) bool {
return c == '-' || c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80
}
func isIdentBoundary(s string, i int) bool { return i == 0 || !isIdentChar(s[i-1]) }
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' }
func hasScheme(ref string) bool {
for i := 0; i < len(ref); i++ {
c := ref[i]
switch {
case c == ':':
return i > 0
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', i > 0 && (c >= '0' && c <= '9' || c == '+' || c == '-' || c == '.'):
default:
return false
}
}
return false
}
+295
View File
@@ -0,0 +1,295 @@
// Package document prepares HTML for display: every "/assets/..." and
// "assets:..." reference in HTML attributes, <style> blocks, style="" and
// referenced CSS (url(), @import) is resolved through the asset resolver and
// replaced by a typed data: URL.
//
// HTML is processed with the golang.org/x/net/html tokenizer. Tokens that are
// not changed are copied byte for byte (comments, entities, scripts, void
// tags and formatting stay as written); only a changed start tag is
// re-serialized.
package document
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"strings"
"golang.org/x/net/html"
"yetano.dev/yetano/core/gui/assets"
)
// DefaultMaxOutput bounds the prepared document. Data-URL navigation and
// NavigateToString have backend limits (WebView2: 2 MB); large binaries such
// as Go-WASM are meant to be fetched separately, not inlined.
const DefaultMaxOutput = 1536 << 10
// Replacement records one rewritten reference (diagnostics).
type Replacement struct {
Ref string `json:"ref"`
Asset string `json:"asset"`
Source string `json:"source"`
MIME string `json:"mime"`
Size int `json:"size"`
In string `json:"in"`
}
// Result is a prepared HTML document or fragment.
type Result struct {
HTML []byte
Replacements []Replacement
}
// Options for Prepare.
type Options struct {
MaxOutput int // 0 = DefaultMaxOutput (inline mode only)
// Link keeps resources as URLs instead of inlining them: "assets:x"
// becomes "/assets/x", "/assets/x" stays, relative CSS references stay.
// Every reference is still validated against the resolver. This is the
// mode for the native resource handler, where the WebView loads each
// resource itself.
Link bool
}
type preparer struct {
link bool
res *assets.Resolver
entry string // virtual name of the HTML being prepared (diagnostics)
cssStack []string
repl []Replacement
}
// Prepare rewrites an HTML document or fragment. entry names the source for
// error messages (an asset path or e.g. "fragment:/fragment/card").
func Prepare(ctx context.Context, res *assets.Resolver, entry string, src []byte, opt Options) (*Result, error) {
r, err := prepare(ctx, res, entry, src, opt)
if err != nil {
return nil, fmt.Errorf("prepare %s: %w", entry, err)
}
return r, nil
}
func prepare(ctx context.Context, res *assets.Resolver, entry string, src []byte, opt Options) (*Result, error) {
if opt.MaxOutput == 0 {
opt.MaxOutput = DefaultMaxOutput
}
if opt.Link {
opt.MaxOutput = 1 << 30
}
p := &preparer{res: res, entry: entry, link: opt.Link}
var out bytes.Buffer
z := html.NewTokenizer(bytes.NewReader(src))
inStyle := false
for {
tt := z.Next()
if tt == html.ErrorToken {
if z.Err() == io.EOF {
break
}
return nil, fmt.Errorf("html: %w", z.Err())
}
raw := z.Raw()
switch tt {
case html.StartTagToken, html.SelfClosingTagToken:
tok := z.Token()
changed, err := p.rewriteTag(ctx, &tok)
if err != nil {
return nil, err
}
if changed {
out.WriteString(tok.String())
} else {
out.Write(raw)
}
inStyle = tt == html.StartTagToken && tok.Data == "style"
case html.TextToken:
if inStyle {
css, err := p.rewriteCSS(ctx, string(raw), "")
if err != nil {
return nil, err
}
if strings.Contains(strings.ToLower(css), "</style") {
return nil, fmt.Errorf("rewritten <style> would contain </style")
}
out.WriteString(css)
} else {
out.Write(raw)
}
case html.EndTagToken:
inStyle = false
out.Write(raw)
default:
out.Write(raw)
}
if out.Len() > opt.MaxOutput {
return nil, fmt.Errorf("prepared document exceeds %d bytes; load large assets via fetch instead of inlining", opt.MaxOutput)
}
}
return &Result{HTML: out.Bytes(), Replacements: p.repl}, nil
}
func (p *preparer) rewriteTag(ctx context.Context, tok *html.Token) (bool, error) {
changed := false
rel := ""
for _, a := range tok.Attr {
if a.Namespace == "" && a.Key == "rel" {
rel = " " + strings.ToLower(a.Val) + " "
}
}
for i := range tok.Attr {
a := &tok.Attr[i]
if a.Namespace != "" {
continue
}
var nv string
var err error
did := false
switch {
case a.Key == "style":
nv, err = p.rewriteCSS(ctx, a.Val, "")
did = nv != a.Val
case a.Key == "srcset" && (tok.Data == "img" || tok.Data == "source"):
nv, did, err = p.rewriteSrcset(ctx, a.Val)
case assets.IsAssetRef(strings.TrimSpace(a.Val)) && urlAttr(tok.Data, a.Key):
ref := strings.TrimSpace(a.Val)
if tok.Data == "link" && a.Key == "href" && strings.Contains(rel, " stylesheet ") {
nv, err = p.stylesheetURL(ctx, ref)
} else {
nv, err = p.refDataURL(ctx, ref)
}
did = true
}
if err != nil {
return false, err
}
if did {
a.Val = nv
changed = true
}
}
return changed, nil
}
// urlAttr lists the element/attribute pairs whose asset references load a
// resource. Navigation targets (<a href>) are deliberately not inlined.
func urlAttr(tag, key string) bool {
switch key {
case "src":
switch tag {
case "img", "script", "source", "audio", "video", "track", "input", "iframe", "embed":
return true
}
case "href":
return tag == "link" || tag == "image" || tag == "use"
case "poster":
return tag == "video"
case "data":
return tag == "object"
case "xlink:href":
return tag == "image" || tag == "use"
}
return false
}
func (p *preparer) rewriteSrcset(ctx context.Context, v string) (string, bool, error) {
parts := strings.Split(v, ",")
changed := false
for i, part := range parts {
f := strings.Fields(part)
if len(f) == 0 || !assets.IsAssetRef(f[0]) {
continue
}
d, err := p.refDataURL(ctx, f[0])
if err != nil {
return "", false, err
}
f[0] = d
parts[i] = strings.Join(f, " ")
changed = true
}
return strings.Join(parts, ", "), changed, nil
}
func (p *preparer) stylesheetURL(ctx context.Context, ref string) (string, error) {
name, err := assets.FromRef(ref)
if err != nil {
return "", p.fail(p.entry, ref, err)
}
if p.link {
return p.assetDataURL(ctx, name, p.entry)
}
css, err := p.loadCSS(ctx, name)
if err != nil {
return "", err
}
p.repl = append(p.repl, Replacement{Ref: ref, Asset: name, MIME: "text/css", Size: len(css), In: p.entry})
return dataURL("text/css;charset=utf-8", []byte(css)), nil
}
func (p *preparer) refDataURL(ctx context.Context, ref string) (string, error) {
name, err := assets.FromRef(ref)
if err != nil {
return "", p.fail(p.entry, ref, err)
}
if assets.BaseMIME(mimeOf(name)) == "text/css" {
return p.stylesheetURL(ctx, ref)
}
return p.assetDataURL(ctx, name, p.entry)
}
func (p *preparer) assetDataURL(ctx context.Context, name, in string) (string, error) {
if in == "" {
in = p.entry
}
r, err := p.resolve(ctx, name, in)
if err != nil {
return "", err
}
p.repl = append(p.repl, Replacement{Ref: name, Asset: name, Source: r.Source, MIME: r.MIME, Size: len(r.Bytes), In: in})
if p.link {
return assets.PrefixSlash + name, nil
}
m := strings.ReplaceAll(r.MIME, " ", "")
return dataURL(m, r.Bytes), nil
}
func (p *preparer) resolve(ctx context.Context, name, in string) (*assets.Resource, error) {
r, err := p.res.Resolve(ctx, name)
if err != nil {
if in != p.entry {
return nil, fmt.Errorf("%s: %w", in, err)
}
return nil, err
}
return r, nil
}
func (p *preparer) fail(in, ref string, err error) error {
if in == "" || in == p.entry {
return fmt.Errorf("reference %q: %w", ref, err)
}
return fmt.Errorf("%s: reference %q: %w", in, ref, err)
}
// PrepareCSS rewrites a stylesheet asset served on its own (link mode for
// the native resource handler, inline mode otherwise).
func PrepareCSS(ctx context.Context, res *assets.Resolver, name string, css []byte, opt Options) ([]byte, error) {
p := &preparer{res: res, entry: name, link: opt.Link}
out, err := p.rewriteCSS(ctx, string(css), name)
if err != nil {
return nil, fmt.Errorf("prepare %s: %w", name, err)
}
return []byte(out), nil
}
func dataURL(mime string, data []byte) string {
return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(data)
}
func mimeOf(name string) string {
m, _ := assets.DetectMIME(name, nil)
return m
}
+143
View File
@@ -0,0 +1,143 @@
package document
import (
"context"
"encoding/base64"
"regexp"
"strings"
"testing"
"testing/fstest"
"yetano.dev/yetano/core/gui/assets"
)
func resolver(files map[string]string) *assets.Resolver {
m := fstest.MapFS{}
for k, v := range files {
m[k] = &fstest.MapFile{Data: []byte(v)}
}
r, _ := assets.NewResolver(assets.NewFSSource("test", m))
return r
}
var testFiles = map[string]string{
"images/a.svg": `<svg xmlns="http://www.w3.org/2000/svg"/>`,
"images/b.png": "\x89PNG\r\n\x1a\nxx",
"fonts/f.ttf": "ttf",
"js/app.js": "console.log(1)",
"css/app.css": `@import "base.css"; body{background:url('../images/b.png')} /* url(/assets/missing) */ .x{content:"url(x)"} .e{background:url(https://example.com/x.png)} .d{background:url(data:image/png;base64,AAAA)}`,
"css/base.css": `@font-face{font-family:F;src:url("../fonts/f.ttf") format("truetype")}`,
"css/cycle1.css": `@import url(cycle2.css);`,
"css/cycle2.css": `@import "cycle1.css";`,
"css/escape.css": `x{background:url(../../outside.png)}`,
}
func prep(t *testing.T, html string) string {
t.Helper()
res, err := Prepare(context.Background(), resolver(testFiles), "index.html", []byte(html), Options{})
if err != nil {
t.Fatal(err)
}
return string(res.HTML)
}
func decodeDataURL(t *testing.T, u string) string {
t.Helper()
i := strings.Index(u, ";base64,")
b, err := base64.StdEncoding.DecodeString(u[i+8:])
if err != nil {
t.Fatal(err)
}
return string(b)
}
func TestReplaceBothForms(t *testing.T) {
out := prep(t, `<img src="/assets/images/a.svg"><img src='assets:images/b.png'>`)
if !strings.Contains(out, `src="data:image/svg+xml;base64,`) || !strings.Contains(out, `src="data:image/png;base64,`) {
t.Fatal(out)
}
}
func TestUntouchedParts(t *testing.T) {
in := "<!doctype html>\n<!-- /assets/images/a.svg stays --><p title=\"a &amp; b\">x &lt; y &hellip;</p><br/><a href=\"/assets/images/a.svg\">nav</a>" +
"<script>var s = \"<img src='/assets/images/a.svg'>\";</script><img src=\"https://example.com/x.png\"><img src=\"data:image/png;base64,AA\">"
out := prep(t, in)
if out != in {
t.Fatalf("unchanged document was modified:\n%s", out)
}
}
func TestStylesheetCSSDependencies(t *testing.T) {
out := prep(t, `<link rel="stylesheet" href="/assets/css/app.css">`)
href := regexp.MustCompile(`href="([^"]+)"`).FindStringSubmatch(out)[1]
if !strings.HasPrefix(href, "data:text/css;charset=utf-8;base64,") {
t.Fatal(href)
}
css := decodeDataURL(t, href)
for _, want := range []string{`url("data:image/png;base64,`, `@import url("data:text/css`, `/* url(/assets/missing) */`, `content:"url(x)"`, `url(https://example.com/x.png)`, `url(data:image/png;base64,AAAA)`} {
if !strings.Contains(css, want) {
t.Errorf("css lacks %q:\n%s", want, css)
}
}
imp := regexp.MustCompile(`@import url\("([^"]+)"\)`).FindStringSubmatch(css)[1]
if base := decodeDataURL(t, imp); !strings.Contains(base, `url("data:font/ttf;base64,`) {
t.Errorf("font in imported css (relative to css/): %s", base)
}
}
func TestStyleBlockSrcsetAndStyleAttr(t *testing.T) {
out := prep(t, `<style>.h{background:url("assets:images/b.png")}</style><img srcset="/assets/images/b.png 1x, assets:images/a.svg 2x"><div style="background:url(/assets/images/b.png)"></div>`)
if strings.Count(out, "data:image/png;base64,") != 3 || strings.Count(out, "data:image/svg+xml;base64,") != 1 {
t.Fatal(out)
}
}
func TestErrors(t *testing.T) {
r := resolver(testFiles)
for name, in := range map[string]string{
"missing": `<img src="/assets/nope.png">`,
"traversal": `<img src="/assets/../go.mod">`,
"cycle": `<link rel="stylesheet" href="/assets/css/cycle1.css">`,
"escape": `<link rel="stylesheet" href="/assets/css/escape.css">`,
} {
if _, err := Prepare(context.Background(), r, "index.html", []byte(in), Options{}); err == nil {
t.Errorf("%s: no error", name)
} else if !strings.Contains(err.Error(), "index.html") {
t.Errorf("%s: error does not name the document: %v", name, err)
}
}
big := `<img src="/assets/images/b.png">`
if _, err := Prepare(context.Background(), r, "index.html", []byte(strings.Repeat(big, 100)), Options{MaxOutput: 1000}); err == nil {
t.Error("size limit not enforced")
}
}
func TestFragmentKeepsSemantics(t *testing.T) {
in := `<tr><td><img src="assets:images/a.svg"></td></tr>`
out := prep(t, in)
if !strings.HasPrefix(out, "<tr><td><img src=\"data:") || !strings.HasSuffix(out, "></td></tr>") {
t.Fatal(out)
}
}
func TestLinkMode(t *testing.T) {
r := resolver(testFiles)
res, err := Prepare(context.Background(), r, "index.html", []byte(`<img src="assets:images/a.svg"><link rel="stylesheet" href="/assets/css/app.css"><div style="background:url(assets:images/b.png)">`), Options{Link: true})
if err != nil {
t.Fatal(err)
}
want := `<img src="/assets/images/a.svg"><link rel="stylesheet" href="/assets/css/app.css"><div style="background:url(&#34;/assets/images/b.png&#34;)">`
if string(res.HTML) != want {
t.Fatalf("got %s\nwant %s", res.HTML, want)
}
css, err := PrepareCSS(context.Background(), r, "css/app.css", []byte(testFiles["css/app.css"]), Options{Link: true})
if err != nil || string(css) != testFiles["css/app.css"] {
t.Fatalf("relative CSS must stay byte-identical: %s %v", css, err)
}
if _, err := Prepare(context.Background(), r, "index.html", []byte(`<img src="assets:images/missing.png">`), Options{Link: true}); err == nil {
t.Error("missing asset not reported in link mode")
}
if _, err := PrepareCSS(context.Background(), r, "css/escape.css", []byte(testFiles["css/escape.css"]), Options{Link: true}); err == nil {
t.Error("root escape not reported in link mode")
}
}
+11
View File
@@ -0,0 +1,11 @@
module yetano.dev/yetano/core/gui
go 1.26.0
require (
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808
golang.org/x/net v0.59.0
golang.org/x/sys v0.48.0
)
require github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
+10
View File
@@ -0,0 +1,10 @@
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 h1:ftnsTqIUH57XQEF+PnXX9++nlHCzdkuB5zbWyMMruZo=
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+21
View File
@@ -0,0 +1,21 @@
#ifndef YETANO_WINDOW_DARWIN_H
#define YETANO_WINDOW_DARWIN_H
#include <stdint.h>
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme);
void yt_add_script(void *h, const char *js);
void yt_navigate(void *h, const char *url);
void yt_eval(void *h, const char *js);
void yt_dispatch(uintptr_t fn);
void yt_run(void);
void yt_stop(void);
void yt_destroy(void *h);
void yt_task_respond(void *h, long tid, int status, const char *headersJSON, const char *url);
void yt_task_data(void *h, long tid, const void *data, int n);
void yt_task_finish(void *h, long tid, const char *err);
void yt_snapshot(void *h, const char *path);
void yt_set_appearance(void *h, int mode);
void yt_accent_color(char *buf, int n);
void yt_set_app_icon(const void *png, int n);
#endif
+282
View File
@@ -0,0 +1,282 @@
//go:build darwin
// Native macOS host: NSWindow + WKWebView with
// - a WKScriptMessageHandler "yetano" (page -> Go messages),
// - document-start WKUserScripts,
// - a WKURLSchemeHandler for the "yetano" scheme (native resources, streaming),
// - main-queue dispatch for Go closures.
// Everything here runs on the main thread; calls from Go goroutines are
// marshalled with dispatch_async onto the main queue.
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
#include "darwin.h"
// Implemented in Go (window_darwin.go).
extern void ytGoMessage(uintptr_t h, const char *msg);
extern void ytGoSchemeStart(uintptr_t h, long id, const char *method, const char *url, const char *headers, const void *body, int n);
extern void ytGoSchemeStop(uintptr_t h, long id);
extern void ytGoDispatch(uintptr_t fn);
extern void ytGoClosed(uintptr_t h);
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
@property (assign) uintptr_t goHandle;
@property (strong) NSWindow *window;
@property (strong) WKWebView *webview;
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
@property (assign) long nextTask;
@property (assign) BOOL closed;
@end
@implementation YTHost
- (void)userContentController:(WKUserContentController *)ucc didReceiveScriptMessage:(WKScriptMessage *)message {
if (self.closed || ![message.body isKindOfClass:[NSString class]]) return;
ytGoMessage(self.goHandle, [(NSString *)message.body UTF8String]);
}
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)task {
long tid = ++self.nextTask;
self.tasks[@(tid)] = task;
NSURLRequest *req = task.request;
NSData *body = req.HTTPBody;
if (!body && req.HTTPBodyStream) {
NSMutableData *buf = [NSMutableData data];
NSInputStream *s = req.HTTPBodyStream;
[s open];
uint8_t chunk[65536];
NSInteger n;
while ((n = [s read:chunk maxLength:sizeof chunk]) > 0) [buf appendBytes:chunk length:(NSUInteger)n];
[s close];
body = buf;
}
NSDictionary *hdr = req.allHTTPHeaderFields ?: @{};
NSData *hj = [NSJSONSerialization dataWithJSONObject:hdr options:0 error:nil];
NSString *hs = [[NSString alloc] initWithData:hj encoding:NSUTF8StringEncoding];
ytGoSchemeStart(self.goHandle, tid, [(req.HTTPMethod ?: @"GET") UTF8String], [req.URL.absoluteString UTF8String],
[hs UTF8String], body.bytes, (int)body.length);
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id<WKURLSchemeTask>)task {
NSNumber *key = nil;
for (NSNumber *k in self.tasks) {
if (self.tasks[k] == task) { key = k; break; }
}
if (!key) return;
[self.tasks removeObjectForKey:key];
ytGoSchemeStop(self.goHandle, key.longValue);
}
- (void)windowWillClose:(NSNotification *)n {
if (self.closed) return;
ytGoClosed(self.goHandle);
yt_stop();
}
@end
static NSString *str(const char *s) { return [NSString stringWithUTF8String:s ?: ""]; }
static void ensureApp(void) {
static BOOL done = NO;
if (done) return;
done = YES;
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Minimal menu: Quit and the Edit actions (copy/paste need them).
NSMenu *bar = [NSMenu new];
NSMenuItem *appItem = [NSMenuItem new];
[bar addItem:appItem];
NSMenu *appMenu = [NSMenu new];
[appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"];
appItem.submenu = appMenu;
NSMenuItem *editItem = [NSMenuItem new];
[bar addItem:editItem];
NSMenu *edit = [[NSMenu alloc] initWithTitle:@"Edit"];
[edit addItemWithTitle:@"Cut" action:@selector(cut:) keyEquivalent:@"x"];
[edit addItemWithTitle:@"Copy" action:@selector(copy:) keyEquivalent:@"c"];
[edit addItemWithTitle:@"Paste" action:@selector(paste:) keyEquivalent:@"v"];
[edit addItemWithTitle:@"Select All" action:@selector(selectAll:) keyEquivalent:@"a"];
editItem.submenu = edit;
NSApp.mainMenu = bar;
[NSApp finishLaunching];
}
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) {
@autoreleasepool {
ensureApp();
YTHost *host = [YTHost new];
host.goHandle = goHandle;
host.tasks = [NSMutableDictionary dictionary];
WKWebViewConfiguration *cfg = [WKWebViewConfiguration new];
[cfg.userContentController addScriptMessageHandler:host name:@"yetano"];
if (scheme && scheme[0]) [cfg setURLSchemeHandler:host forURLScheme:str(scheme)];
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
NSRect frame = NSMakeRect(0, 0, width, height);
host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg];
if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; }
host.window = [[NSWindow alloc] initWithContentRect:frame
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
backing:NSBackingStoreBuffered
defer:NO];
host.window.releasedWhenClosed = NO;
host.window.title = str(title);
host.window.contentView = host.webview;
host.window.delegate = host;
[host.window center];
[host.window makeKeyAndOrderFront:nil];
[NSApp activateIgnoringOtherApps:YES];
return (__bridge_retained void *)host;
}
}
void yt_add_script(void *h, const char *js) {
YTHost *host = (__bridge YTHost *)h;
WKUserScript *s = [[WKUserScript alloc] initWithSource:str(js)
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:YES];
[host.webview.configuration.userContentController addUserScript:s];
}
void yt_navigate(void *h, const char *url) {
YTHost *host = (__bridge YTHost *)h;
[host.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str(url)]]];
}
void yt_eval(void *h, const char *js) {
YTHost *host = (__bridge YTHost *)h;
if (host.closed) return;
[host.webview evaluateJavaScript:str(js) completionHandler:nil];
}
static void runGo(void *fn) { ytGoDispatch((uintptr_t)fn); }
void yt_dispatch(uintptr_t fn) { dispatch_async_f(dispatch_get_main_queue(), (void *)fn, runGo); }
void yt_run(void) {
@autoreleasepool { [NSApp run]; }
}
void yt_stop(void) {
[NSApp stop:nil];
// stop: takes effect after the next event; post one.
NSEvent *e = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0
timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0];
[NSApp postEvent:e atStart:YES];
}
void yt_destroy(void *h) {
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
host.closed = YES;
for (NSNumber *k in host.tasks.allKeys) {
// Remaining tasks are failed so WebKit does not wait forever.
id<WKURLSchemeTask> t = host.tasks[k];
@try { [t didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil]]; } @catch (id e) {}
}
[host.tasks removeAllObjects];
[host.webview stopLoading];
[host.webview.configuration.userContentController removeScriptMessageHandlerForName:@"yetano"];
[host.webview.configuration.userContentController removeAllUserScripts];
host.window.delegate = nil;
[host.window orderOut:nil];
host.window.contentView = nil;
[host.window close];
host.webview = nil;
host.window = nil;
}
// --- scheme task responses (called from Go, any thread) --------------------
static void onTask(void *h, long tid, void (^block)(id<WKURLSchemeTask>)) {
YTHost *host = (__bridge YTHost *)h;
dispatch_async(dispatch_get_main_queue(), ^{
id<WKURLSchemeTask> t = host.tasks[@(tid)];
if (!t || host.closed) return; // stopped meanwhile: must not be touched
block(t);
});
}
void yt_task_respond(void *h, long tid, int status, const char *headersJSON, const char *url) {
NSData *hj = [str(headersJSON) dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *hdr = [NSJSONSerialization JSONObjectWithData:hj options:0 error:nil];
NSURL *u = [NSURL URLWithString:str(url)];
onTask(h, tid, ^(id<WKURLSchemeTask> t) {
NSHTTPURLResponse *r = [[NSHTTPURLResponse alloc] initWithURL:u statusCode:status HTTPVersion:@"HTTP/1.1" headerFields:hdr];
[t didReceiveResponse:r];
});
}
void yt_task_data(void *h, long tid, const void *data, int n) {
NSData *d = [NSData dataWithBytes:data length:(NSUInteger)n]; // copied before returning to Go
onTask(h, tid, ^(id<WKURLSchemeTask> t) { [t didReceiveData:d]; });
}
void yt_task_finish(void *h, long tid, const char *err) {
NSString *e = err ? str(err) : nil;
YTHost *host = (__bridge YTHost *)h;
onTask(h, tid, ^(id<WKURLSchemeTask> t) {
if (e) {
[t didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorUnknown
userInfo:@{NSLocalizedDescriptionKey : e}]];
} else {
[t didFinish];
}
[host.tasks removeObjectForKey:@(tid)];
});
}
// --- snapshot: render the web view into a PNG file (main thread) ---------
void yt_snapshot(void *h, const char *path) {
YTHost *host = (__bridge YTHost *)h;
NSString *p = str(path);
uintptr_t gh = host.goHandle;
[host.webview takeSnapshotWithConfiguration:nil completionHandler:^(NSImage *img, NSError *error) {
if (!img) { ytGoSnapshotDone(gh, [(error.localizedDescription ?: @"snapshot failed") UTF8String]); return; }
CGImageRef cg = [img CGImageForProposedRect:NULL context:nil hints:nil];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:cg];
NSData *png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
NSError *werr = nil;
if (![png writeToFile:p options:NSDataWritingAtomic error:&werr]) {
ytGoSnapshotDone(gh, [werr.localizedDescription UTF8String]);
return;
}
ytGoSnapshotDone(gh, NULL);
}];
}
// --- appearance ------------------------------------------------------------
// yt_set_appearance: 0 = follow the system, 1 = light, 2 = dark. Changes the
// title bar and what the page sees as prefers-color-scheme.
void yt_set_appearance(void *h, int mode) {
YTHost *host = (__bridge YTHost *)h;
NSAppearance *a = nil;
if (mode == 1) a = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
if (mode == 2) a = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
host.window.appearance = a;
}
// yt_accent_color writes the user's accent color as "#RRGGBB" into buf.
void yt_accent_color(char *buf, int n) {
@autoreleasepool {
NSColor *c = [[NSColor controlAccentColor] colorUsingColorSpace:[NSColorSpace sRGBColorSpace]];
if (!c) { buf[0] = 0; return; }
snprintf(buf, (size_t)n, "#%02X%02X%02X", (int)lround(c.redComponent * 255), (int)lround(c.greenComponent * 255), (int)lround(c.blueComponent * 255));
}
}
// yt_set_app_icon sets the Dock icon from PNG bytes, unless the process runs
// from an app bundle (which brings its own icon).
void yt_set_app_icon(const void *png, int n) {
@autoreleasepool {
ensureApp();
if ([[NSBundle mainBundle] bundleIdentifier] != nil) return;
NSImage *img = [[NSImage alloc] initWithData:[NSData dataWithBytes:png length:(NSUInteger)n]];
if (img) NSApp.applicationIconImage = img;
}
}
+241
View File
@@ -0,0 +1,241 @@
// Package window is a narrow native WebView host:
//
// - macOS: own Cocoa host (darwin.m): NSWindow + WKWebView, cgo
// - Windows: own Win32 host on github.com/jchv/go-webview2/pkg/edge
// (WebView2 COM, pure Go)
//
// It offers exactly what the program needs: one message channel page -> Go
// (window.__yetano_post), document-start scripts, Eval, UI-thread Dispatch
// and a native resource handler for the app origin (BaseURL), which serves
// the entry document, assets and local routes without any network listener,
// with streaming response bodies.
//
// Thread rules: New, Init, Navigate, Run and Destroy run on the thread that
// locked itself in this package's init (the main goroutine). Dispatch is safe
// from any goroutine; Eval only inside a dispatched function. After Destroy,
// Dispatch and queued closures are no-ops.
package window
import (
"context"
"errors"
"net/http"
"sync"
)
// ResourceRequest is a request from the WebView for the app origin.
type ResourceRequest struct {
Method string
URL string // absolute, e.g. "yetano://app/assets/x.css" or "https://yetano.invalid/rpc/add"
Header http.Header
Body []byte
}
// ResourceWriter answers one ResourceRequest. Respond is called once, then
// any number of Write calls (each is delivered to the page as it comes:
// streaming), then Close. All methods are safe from any goroutine.
type ResourceWriter interface {
Respond(status int, header http.Header)
Write(p []byte) (int, error)
Close(err error)
}
// ResourceHandler serves app-origin requests. ctx ends when the page drops
// the request (where the backend reports that) or the window is destroyed.
type ResourceHandler func(ctx context.Context, req *ResourceRequest, w ResourceWriter)
// Options for a new window.
type Options struct {
Title string
Width int
Height int
Debug bool // developer tools
DataPath string // WebView2 user data folder (Windows)
OnMessage func(msg string)
Resource ResourceHandler // nil: no native resource handler
}
type backend interface {
Init(js string)
Navigate(url string)
Run()
Terminate()
Dispatch(f func())
Eval(js string)
Destroy()
}
// Window is a guarded native WebView window.
type Window struct {
mu sync.Mutex
b backend
alive bool
name string
base string
dropped int
}
// Debugf, if set, receives backend diagnostics.
var Debugf func(format string, args ...any)
// ErrUnsupported is returned on platforms without a backend.
var ErrUnsupported = errors.New("window: no native WebView backend for this platform")
// postShim defines window.__yetano_post on top of the backend's native
// message channel. It is installed before any other init script.
const postShimDarwin = `window.__yetano_post=function(m){window.webkit.messageHandlers.yetano.postMessage(JSON.stringify(m));return Promise.resolve();};`
const postShimWindows = `window.__yetano_post=function(m){window.chrome.webview.postMessage(JSON.stringify(m));return Promise.resolve();};`
// New creates the native window. On failure it returns an error and nothing
// has to be cleaned up.
func New(opt Options) (*Window, error) {
if opt.Width == 0 {
opt.Width, opt.Height = 1100, 820
}
b, name, base, err := newBackend(opt)
if err != nil {
return nil, err
}
return &Window{b: b, alive: true, name: name, base: base}, nil
}
// Backend names the native backend.
func (w *Window) Backend() string { return w.name }
// BaseURL is the app origin served by the resource handler, without
// trailing slash ("yetano://app", "https://yetano.invalid").
func (w *Window) BaseURL() string { return w.base }
// Init adds a document-start script (every navigation, before page scripts).
func (w *Window) Init(js string) { w.b.Init(js) }
// Navigate loads url.
func (w *Window) Navigate(url string) { w.b.Navigate(url) }
// Run runs the UI loop until Terminate or the user closes the window.
func (w *Window) Run() { w.b.Run() }
// Dispatch queues f on the UI thread. After Destroy it is dropped.
func (w *Window) Dispatch(f func()) {
w.mu.Lock()
defer w.mu.Unlock()
if !w.alive {
w.dropped++
return
}
w.b.Dispatch(func() {
w.mu.Lock()
alive := w.alive
w.mu.Unlock()
if alive {
f()
}
})
}
// Eval runs js in the page; only on the UI thread.
func (w *Window) Eval(js string) {
w.mu.Lock()
alive := w.alive
w.mu.Unlock()
if alive {
w.b.Eval(js)
}
}
// Terminate ends Run from any goroutine.
func (w *Window) Terminate() { w.Dispatch(func() { w.b.Terminate() }) }
// Destroy releases the native window. Idempotent; on the UI thread after Run.
func (w *Window) Destroy() {
w.mu.Lock()
if !w.alive {
w.mu.Unlock()
return
}
w.alive = false
w.mu.Unlock()
w.b.Destroy()
}
// snapshotter is implemented by backends that can render the page to PNG.
type snapshotter interface {
Snapshot(path string, done func(error))
}
// Snapshot renders the current page into a PNG file (UI thread). done runs
// on the UI thread. Backends without support report an error.
func (w *Window) Snapshot(path string, done func(error)) {
s, ok := w.b.(snapshotter)
if !ok {
done(errors.New("window: snapshot not supported by " + w.name))
return
}
s.Snapshot(path, done)
}
// appearancer is implemented by backends whose window chrome (title bar)
// can follow the page's light/dark choice.
type appearancer interface {
SetAppearance(mode string)
}
// SetAppearance makes the native window chrome light ("light"), dark
// ("dark") or follow the system (anything else). UI thread. A no-op where
// unsupported.
func (w *Window) SetAppearance(mode string) {
if a, ok := w.b.(appearancer); ok {
a.SetAppearance(mode)
}
}
// SetAppIcon sets the application icon shown by the OS (macOS Dock) from
// PNG bytes when the program does not run from an app bundle. Windows takes
// the icon from the executable's resources instead. Call before New.
func SetAppIcon(png []byte) { setAppIcon(png) }
// AccentColor is the user's system accent color as "#RRGGBB", or "" if
// unknown. Safe to call before a window exists.
func AccentColor() string { return accentColor() }
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
func (w *Window) DroppedDispatches() int {
w.mu.Lock()
defer w.mu.Unlock()
return w.dropped
}
// taskTable tracks running resource requests so Destroy can cancel them.
type taskTable struct {
mu sync.Mutex
tasks map[int64]context.CancelFunc
}
func (t *taskTable) add(id int64, c context.CancelFunc) {
t.mu.Lock()
if t.tasks == nil {
t.tasks = map[int64]context.CancelFunc{}
}
t.tasks[id] = c
t.mu.Unlock()
}
func (t *taskTable) cancel(id int64) {
t.mu.Lock()
c := t.tasks[id]
delete(t.tasks, id)
t.mu.Unlock()
if c != nil {
c()
}
}
func (t *taskTable) cancelAll() {
t.mu.Lock()
cs := t.tasks
t.tasks = nil
t.mu.Unlock()
for _, c := range cs {
c()
}
}
+283
View File
@@ -0,0 +1,283 @@
//go:build darwin && cgo
package window
/*
#cgo CFLAGS: -x objective-c -fobjc-arc
#cgo LDFLAGS: -framework Cocoa -framework WebKit
#include <stdlib.h>
#include "darwin.h"
*/
import "C"
import (
"context"
"encoding/json"
"net/http"
"runtime"
"runtime/cgo"
"sync"
"unsafe"
)
// Cocoa requires the UI on the main thread: keep the main goroutine there.
func init() { runtime.LockOSThread() }
// Scheme and host of the app origin on macOS. WKURLSchemeHandler cannot
// take over http/https, so the app gets its own scheme.
const darwinScheme = "yetano"
type darwinBackend struct {
h unsafe.Pointer // retained YTHost
handle cgo.Handle // -> *darwinBackend, given to ObjC
opt Options
tasks taskTable
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
snapDone func(error)
}
// with runs f with the live host pointer, or not at all after Destroy.
func (b *darwinBackend) with(f func(h unsafe.Pointer)) bool {
b.mu.RLock()
defer b.mu.RUnlock()
if b.h == nil {
return false
}
f(b.h)
return true
}
func newBackend(opt Options) (backend, string, string, error) {
b := &darwinBackend{opt: opt}
b.handle = cgo.NewHandle(b)
title := C.CString(opt.Title)
defer C.free(unsafe.Pointer(title))
scheme := C.CString("")
if opt.Resource != nil {
C.free(unsafe.Pointer(scheme))
scheme = C.CString(darwinScheme)
}
defer C.free(unsafe.Pointer(scheme))
debug := 0
if opt.Debug {
debug = 1
}
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme)
if b.h == nil {
b.handle.Delete()
return nil, "", "", errUnavailable("WKWebView could not be created")
}
b.Init(postShimDarwin)
return b, "cocoa/WKWebView", darwinScheme + "://app", nil
}
type errUnavailable string
func (e errUnavailable) Error() string { return "window: " + string(e) }
func cstr(s string) *C.char { return C.CString(s) }
func (b *darwinBackend) Init(js string) {
c := cstr(js)
defer C.free(unsafe.Pointer(c))
C.yt_add_script(b.h, c)
}
func (b *darwinBackend) Navigate(url string) {
c := cstr(url)
defer C.free(unsafe.Pointer(c))
C.yt_navigate(b.h, c)
}
func (b *darwinBackend) Eval(js string) {
c := cstr(js)
defer C.free(unsafe.Pointer(c))
C.yt_eval(b.h, c)
}
func (b *darwinBackend) Run() { C.yt_run() }
func (b *darwinBackend) Terminate() { C.yt_stop() }
func (b *darwinBackend) Dispatch(f func()) {
C.yt_dispatch(C.uintptr_t(cgo.NewHandle(f)))
}
func (b *darwinBackend) Destroy() {
b.tasks.cancelAll()
b.mu.Lock()
h := b.h
b.h = nil
b.mu.Unlock()
C.yt_destroy(h)
// The handle stays valid: ObjC may still deliver an already queued
// message; the callbacks check b.h.
}
//export ytGoDispatch
func ytGoDispatch(fn C.uintptr_t) {
h := cgo.Handle(fn)
f := h.Value().(func())
h.Delete()
f()
}
//export ytGoMessage
func ytGoMessage(h C.uintptr_t, msg *C.char) {
b := cgo.Handle(h).Value().(*darwinBackend)
if b.opt.OnMessage != nil && b.with(func(unsafe.Pointer) {}) {
b.opt.OnMessage(C.GoString(msg))
}
}
// Snapshot renders the page into a PNG file; done runs on the UI thread.
func (b *darwinBackend) Snapshot(path string, done func(error)) {
b.mu.Lock()
b.snapDone = done
b.mu.Unlock()
c := cstr(path)
defer C.free(unsafe.Pointer(c))
b.with(func(h unsafe.Pointer) { C.yt_snapshot(h, c) })
}
// SetAppearance: "light", "dark", or anything else to follow the system.
func (b *darwinBackend) SetAppearance(mode string) {
m := 0
switch mode {
case "light":
m = 1
case "dark":
m = 2
}
b.with(func(h unsafe.Pointer) { C.yt_set_appearance(h, C.int(m)) })
}
func setAppIcon(png []byte) {
if len(png) > 0 {
C.yt_set_app_icon(unsafe.Pointer(&png[0]), C.int(len(png)))
}
}
func accentColor() string {
var buf [16]C.char
C.yt_accent_color(&buf[0], C.int(len(buf)))
return C.GoString(&buf[0])
}
//export ytGoSnapshotDone
func ytGoSnapshotDone(h C.uintptr_t, err *C.char) {
b := cgo.Handle(h).Value().(*darwinBackend)
b.mu.Lock()
done := b.snapDone
b.snapDone = nil
b.mu.Unlock()
if done == nil {
return
}
if err != nil {
done(errUnavailable("snapshot: " + C.GoString(err)))
return
}
done(nil)
}
//export ytGoClosed
func ytGoClosed(h C.uintptr_t) {}
//export ytGoSchemeStart
func ytGoSchemeStart(h C.uintptr_t, id C.long, method, url, headers *C.char, body unsafe.Pointer, n C.int) {
b := cgo.Handle(h).Value().(*darwinBackend)
req := &ResourceRequest{Method: C.GoString(method), URL: C.GoString(url), Header: http.Header{}}
var hm map[string]string
_ = json.Unmarshal([]byte(C.GoString(headers)), &hm)
for k, v := range hm {
req.Header.Set(k, v)
}
if n > 0 {
req.Body = C.GoBytes(body, n)
}
ctx, cancel := context.WithCancel(context.Background())
tid := int64(id)
b.tasks.add(tid, cancel)
w := &darwinTask{b: b, id: tid, url: req.URL}
go func() {
defer b.tasks.cancel(tid)
b.opt.Resource(ctx, req, w)
w.Close(nil)
}()
}
//export ytGoSchemeStop
func ytGoSchemeStop(h C.uintptr_t, id C.long) {
cgo.Handle(h).Value().(*darwinBackend).tasks.cancel(int64(id))
}
// darwinTask forwards a response to the WKURLSchemeTask. The ObjC side drops
// calls for tasks that WebKit already stopped.
type darwinTask struct {
b *darwinBackend
id int64
url string
mu sync.Mutex
responded bool
done bool
}
func (t *darwinTask) Respond(status int, header http.Header) {
t.mu.Lock()
defer t.mu.Unlock()
if t.responded || t.done {
return
}
t.responded = true
hm := map[string]string{}
for k, v := range header {
if len(v) > 0 {
hm[k] = v[0]
}
}
hj, _ := json.Marshal(hm)
ch, cu := cstr(string(hj)), cstr(t.url)
defer C.free(unsafe.Pointer(ch))
defer C.free(unsafe.Pointer(cu))
t.b.with(func(h unsafe.Pointer) { C.yt_task_respond(h, C.long(t.id), C.int(status), ch, cu) })
}
func (t *darwinTask) Write(p []byte) (int, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.done {
return 0, context.Canceled
}
if !t.responded {
t.mu.Unlock()
t.Respond(http.StatusOK, nil)
t.mu.Lock()
}
if len(p) > 0 && !t.b.with(func(h unsafe.Pointer) { C.yt_task_data(h, C.long(t.id), unsafe.Pointer(&p[0]), C.int(len(p))) }) {
return 0, context.Canceled
}
return len(p), nil
}
func (t *darwinTask) Close(err error) {
t.mu.Lock()
if t.done {
t.mu.Unlock()
return
}
responded := t.responded
t.mu.Unlock()
if !responded && err == nil {
t.Respond(http.StatusNoContent, nil)
}
t.mu.Lock()
defer t.mu.Unlock()
t.done = true
var ce *C.char
if err != nil {
ce = cstr(err.Error())
defer C.free(unsafe.Pointer(ce))
}
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !(darwin && cgo) && !windows
package window
func newBackend(Options) (backend, string, string, error) { return nil, "", "", ErrUnsupported }
func accentColor() string { return "" }
func setAppIcon([]byte) {}
+75
View File
@@ -0,0 +1,75 @@
package window
import (
"context"
"testing"
)
// fakeBackend queues dispatched functions like a real UI loop (run them
// with drain) and records calls.
type fakeBackend struct {
queue []func()
evals []string
destroyed int
}
func (f *fakeBackend) drain() {
for len(f.queue) > 0 {
g := f.queue[0]
f.queue = f.queue[1:]
g()
}
}
func (f *fakeBackend) Init(string) {}
func (f *fakeBackend) Navigate(string) {}
func (f *fakeBackend) Run() {}
func (f *fakeBackend) Terminate() {}
func (f *fakeBackend) Dispatch(g func()) { f.queue = append(f.queue, g) }
func (f *fakeBackend) Eval(js string) { f.evals = append(f.evals, js) }
func (f *fakeBackend) Destroy() { f.destroyed++ }
func TestDispatchAfterDestroyIsDropped(t *testing.T) {
fb := &fakeBackend{}
w := &Window{b: fb, alive: true, name: "fake"}
ran := 0
w.Dispatch(func() { ran++; w.Eval("a") })
w.Dispatch(func() { ran++ })
fb.drain()
w.Dispatch(func() { ran++ }) // queued, Destroy comes first
w.Destroy()
fb.drain()
w.Destroy() // idempotent
w.Dispatch(func() { ran++ })
w.Eval("b")
if ran != 2 || len(fb.evals) != 1 || fb.destroyed != 1 || w.DroppedDispatches() != 1 || len(fb.queue) != 0 {
t.Fatalf("ran=%d evals=%v destroyed=%d dropped=%d", ran, fb.evals, fb.destroyed, w.DroppedDispatches())
}
}
func TestSnapshotUnsupported(t *testing.T) {
w := &Window{b: &fakeBackend{}, alive: true, name: "fake"}
var got error
w.Snapshot("x.png", func(err error) { got = err })
if got == nil {
t.Fatal("expected an error from a backend without snapshot support")
}
w.SetAppearance("dark") // no-op without support, must not panic
}
func TestTaskTableCancel(t *testing.T) {
var tt taskTable
ctx1, c1 := context.WithCancel(context.Background())
ctx2, c2 := context.WithCancel(context.Background())
tt.add(1, c1)
tt.add(2, c2)
tt.cancel(1)
if ctx1.Err() == nil || ctx2.Err() != nil {
t.Fatal("cancel(1) must cancel only task 1")
}
tt.cancel(1) // unknown id: no-op
tt.cancelAll()
if ctx2.Err() == nil {
t.Fatal("cancelAll must cancel the remaining tasks")
}
}
+705
View File
@@ -0,0 +1,705 @@
//go:build windows
package window
import (
"context"
"errors"
"fmt"
"net/http"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/jchv/go-webview2/pkg/edge"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
// WebView2 needs every call on the thread that created it (STA, message
// loop). Lock the main goroutine to the main thread before main runs.
func init() { runtime.LockOSThread() }
// App origin on Windows. WebView2's WebResourceRequested intercepts this
// https URL before any network access; ".invalid" can never resolve, so a
// missed interception cannot reach a real host. Custom schemes would need
// ICoreWebView2EnvironmentOptions4, which pkg/edge does not pass.
const windowsOrigin = "https://yetano.invalid"
var (
user32 = windows.NewLazySystemDLL("user32.dll")
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
pRegisterClassEx = user32.NewProc("RegisterClassExW")
pCreateWindowEx = user32.NewProc("CreateWindowExW")
pDefWindowProc = user32.NewProc("DefWindowProcW")
pShowWindow = user32.NewProc("ShowWindow")
pUpdateWindow = user32.NewProc("UpdateWindow")
pSetFocus = user32.NewProc("SetFocus")
pGetMessage = user32.NewProc("GetMessageW")
pPeekMessage = user32.NewProc("PeekMessageW")
pTranslate = user32.NewProc("TranslateMessage")
pDispatch = user32.NewProc("DispatchMessageW")
pPostMessage = user32.NewProc("PostMessageW")
pPostQuit = user32.NewProc("PostQuitMessage")
pDestroyWindow = user32.NewProc("DestroyWindow")
pIsWindow = user32.NewProc("IsWindow")
pLoadCursor = user32.NewProc("LoadCursorW")
pLoadIcon = user32.NewProc("LoadIconW")
pGetSysMetrics = user32.NewProc("GetSystemMetrics")
pGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
dwmapi = windows.NewLazySystemDLL("dwmapi.dll")
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
pSetWindowPos = user32.NewProc("SetWindowPos")
pGetDpiForSystem = user32.NewProc("GetDpiForSystem")
)
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
const (
wmDestroy = 0x0002
wmMove = 0x0003
wmSize = 0x0005
wmClose = 0x0010
wmQuit = 0x0012
wmMoving = 0x0216
wmApp = 0x8000
pmRemove = 0x0001
swShow = 5
wsOverlapp = 0x00CF0000
)
type wndClassEx struct {
cbSize uint32
style uint32
lpfnWndProc uintptr
cbClsExtra int32
cbWndExtra int32
hInstance uintptr
hIcon uintptr
hCursor uintptr
hbrBackground uintptr
lpszMenuName *uint16
lpszClassName *uint16
hIconSm uintptr
}
type msgT struct {
hwnd uintptr
message uint32
wParam uintptr
lParam uintptr
time uint32
ptX int32
ptY int32
private uint32
}
var (
classOnce sync.Once
className *uint16
windowsMu sync.Mutex
byHWND = map[uintptr]*winBackend{}
)
func registerClass() {
classOnce.Do(func() {
className, _ = windows.UTF16PtrFromString("YetanoWebView")
hinst, _, _ := pGetModuleHandle.Call(0)
cursor, _, _ := pLoadCursor.Call(0, 32512) // IDC_ARROW
// The executable's own icon (gui/winres: RT_GROUP_ICON "APP"), else
// the stock application icon.
appName, _ := windows.UTF16PtrFromString("APP")
icon, _, _ := pLoadIcon.Call(hinst, uintptr(unsafe.Pointer(appName)))
if icon == 0 {
icon, _, _ = pLoadIcon.Call(0, 32512) // IDI_APPLICATION
}
wc := wndClassEx{
lpfnWndProc: windows.NewCallback(wndproc), hInstance: hinst, hCursor: cursor,
hIcon: icon, hIconSm: icon, lpszClassName: className, hbrBackground: 6, // COLOR_WINDOW+1
}
wc.cbSize = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
})
}
type winBackend struct {
hwnd uintptr
chromium *edge.Chromium
opt Options
mu sync.Mutex
queue []func()
destroying bool
tasks taskTable
nextID atomic.Int64
}
func newBackend(opt Options) (backend, string, string, error) {
// A previous window in this process may still have teardown messages
// (including WM_QUIT) queued. pkg/edge's Embed waits for the controller
// with a GetMessage loop that gives up on WM_QUIT, so drain first.
if n := settle(200 * time.Millisecond); n > 0 && Debugf != nil {
Debugf("window: discarded %d WM_QUIT before creating a window", n)
}
registerClass()
b := &winBackend{opt: opt}
// The manifest declares per-monitor DPI awareness: sizes are physical
// pixels, so scale the requested (96-dpi) size.
if pGetDpiForSystem.Find() == nil {
if dpi, _, _ := pGetDpiForSystem.Call(); dpi > 96 {
opt.Width, opt.Height = opt.Width*int(dpi)/96, opt.Height*int(dpi)/96
}
}
title, _ := windows.UTF16PtrFromString(opt.Title)
sw, _, _ := pGetSysMetrics.Call(0) // SM_CXSCREEN
sh, _, _ := pGetSysMetrics.Call(1) // SM_CYSCREEN
x, y := (int(sw)-opt.Width)/2, (int(sh)-opt.Height)/2
hinst, _, _ := pGetModuleHandle.Call(0)
hwnd, _, err := pCreateWindowEx.Call(0, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(title)),
wsOverlapp, uintptr(x), uintptr(y), uintptr(opt.Width), uintptr(opt.Height), 0, 0, hinst, 0)
if hwnd == 0 {
return nil, "", "", fmt.Errorf("window: CreateWindowEx: %v", err)
}
b.hwnd = hwnd
windowsMu.Lock()
byHWND[hwnd] = b
windowsMu.Unlock()
pShowWindow.Call(hwnd, swShow)
pUpdateWindow.Call(hwnd)
pSetFocus.Call(hwnd)
c := edge.NewChromium()
c.DataPath = opt.DataPath
c.MessageCallback = func(msg string) {
if opt.OnMessage != nil {
opt.OnMessage(msg)
}
}
if opt.Resource != nil {
c.WebResourceRequestedCallback = b.onResource
}
b.chromium = c
if !c.Embed(hwnd) {
b.Destroy()
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
}
c.Resize()
if s, err := c.GetSettings(); err == nil {
_ = s.PutAreDevToolsEnabled(opt.Debug)
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
}
if opt.Resource != nil {
c.AddWebResourceRequestedFilter(windowsOrigin+"/*", edge.COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL)
}
b.Init(postShimWindows)
return b, "win32/WebView2", windowsOrigin, nil
}
func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
windowsMu.Lock()
b := byHWND[hwnd]
windowsMu.Unlock()
if b != nil {
switch msg {
case wmSize:
if b.chromium != nil {
b.chromium.Resize()
}
case wmMove, wmMoving:
if b.chromium != nil {
_ = b.chromium.NotifyParentWindowPositionChanged()
}
case wmApp:
b.runQueue()
return 0
case wmClose:
pDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
b.mu.Lock()
programmatic := b.destroying
b.mu.Unlock()
if !programmatic {
pPostQuit.Call(0) // user closed the window: end Run
}
return 0
}
}
r, _, _ := pDefWindowProc.Call(hwnd, msg, wp, lp)
return r
}
func (b *winBackend) runQueue() {
b.mu.Lock()
q := b.queue
b.queue = nil
b.mu.Unlock()
for _, f := range q {
f()
}
}
func (b *winBackend) Init(js string) { b.chromium.Init(js) }
func (b *winBackend) Navigate(url string) { b.chromium.Navigate(url) }
func (b *winBackend) Eval(js string) { b.chromium.Eval(js) }
func (b *winBackend) Terminate() { pPostQuit.Call(0) }
// Dispatch posts to the window (not the thread), so closures also run while
// a modal loop (move/resize) is active.
func (b *winBackend) Dispatch(f func()) {
b.mu.Lock()
b.queue = append(b.queue, f)
b.mu.Unlock()
pPostMessage.Call(b.hwnd, wmApp, 0, 0)
}
func (b *winBackend) Run() {
var m msgT
for {
r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
if int32(r) <= 0 {
return
}
pTranslate.Call(uintptr(unsafe.Pointer(&m)))
pDispatch.Call(uintptr(unsafe.Pointer(&m)))
}
}
// Destroy destroys the window synchronously (WebView2 is torn down with
// its parent) and pumps the remaining messages.
func (b *winBackend) Destroy() {
b.tasks.cancelAll()
b.mu.Lock()
b.destroying = true
b.mu.Unlock()
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
pDestroyWindow.Call(b.hwnd)
}
windowsMu.Lock()
delete(byHWND, b.hwnd)
windowsMu.Unlock()
if n := settle(200 * time.Millisecond); n > 0 && Debugf != nil {
Debugf("window: discarded %d WM_QUIT after destroy", n)
}
}
// settle pumps this thread's queue for d, dispatching normal messages and
// discarding WM_QUIT. It returns the number of WM_QUIT seen.
func settle(d time.Duration) int {
quits := 0
end := time.Now().Add(d)
var m msgT
for time.Now().Before(end) {
r, _, _ := pPeekMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0, pmRemove)
if r == 0 {
time.Sleep(5 * time.Millisecond)
continue
}
if m.message == wmQuit {
quits++
continue
}
pTranslate.Call(uintptr(unsafe.Pointer(&m)))
pDispatch.Call(uintptr(unsafe.Pointer(&m)))
}
return quits
}
// ---- appearance ---------------------------------------------------------
// SetAppearance switches the title bar between light and dark
// (DWMWA_USE_IMMERSIVE_DARK_MODE). "system" follows the "app mode" setting.
func (b *winBackend) SetAppearance(mode string) {
dark := mode == "dark"
if mode != "light" && mode != "dark" {
dark = systemDark()
}
var v int32
if dark {
v = 1
}
const dwmwaUseImmersiveDarkMode = 20
pDwmSetAttribute.Call(b.hwnd, dwmwaUseImmersiveDarkMode, uintptr(unsafe.Pointer(&v)), 4)
// Redraw the non-client area so the change shows immediately.
const swpFlags = 0x0001 | 0x0002 | 0x0004 | 0x0010 | 0x0020 // NOSIZE|NOMOVE|NOZORDER|NOACTIVATE|FRAMECHANGED
pSetWindowPos.Call(b.hwnd, 0, 0, 0, 0, 0, swpFlags)
}
func systemDark() bool {
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE)
if err != nil {
return false
}
defer k.Close()
v, _, err := k.GetIntegerValue("AppsUseLightTheme")
return err == nil && v == 0
}
// accentColor reads the accent color Windows uses for window chrome
// (HKCU\Software\Microsoft\Windows\DWM\AccentColor, 0xAABBGGRR).
func accentColor() string {
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\DWM`, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer k.Close()
v, _, err := k.GetIntegerValue("AccentColor")
if err != nil {
return ""
}
return fmt.Sprintf("#%02X%02X%02X", v&0xff, v>>8&0xff, v>>16&0xff)
}
// ---- raw COM helpers ----------------------------------------------------
func comCall(obj unsafe.Pointer, slot int, args ...uintptr) uintptr {
vtbl := *(*unsafe.Pointer)(obj)
fn := *(*uintptr)(unsafe.Add(vtbl, slot*int(unsafe.Sizeof(uintptr(0)))))
r, _, _ := syscall.SyscallN(fn, append([]uintptr{uintptr(obj)}, args...)...)
return r
}
func comRelease(obj unsafe.Pointer) {
if obj != nil {
comCall(obj, 2)
}
}
func coString(p *uint16) string {
if p == nil {
return ""
}
s := windows.UTF16PtrToString(p)
windows.CoTaskMemFree(unsafe.Pointer(p))
return s
}
// vtable slots, from WebView2.h
const (
argsPutResponse = 5
argsGetDeferral = 6
deferralComplete = 3
reqGetMethod = 5
reqGetContent = 7
reqGetHeaders = 9
hdrGetIterator = 8
iterGetCurrent = 3
iterHasCurrent = 4
iterMoveNext = 5
envCreateResponse = 4
streamRead = 3
)
// onResource runs on the UI thread for every request to windowsOrigin.
func (b *winBackend) onResource(req *edge.ICoreWebView2WebResourceRequest, args *edge.ICoreWebView2WebResourceRequestedEventArgs) {
rp, ap := unsafe.Pointer(req), unsafe.Pointer(args)
uri, _ := req.GetUri()
var method *uint16
comCall(rp, reqGetMethod, uintptr(unsafe.Pointer(&method)))
rr := &ResourceRequest{Method: coString(method), URL: uri, Header: http.Header{}}
var headers unsafe.Pointer
if comCall(rp, reqGetHeaders, uintptr(unsafe.Pointer(&headers))) == 0 && headers != nil {
var it unsafe.Pointer
if comCall(headers, hdrGetIterator, uintptr(unsafe.Pointer(&it))) == 0 && it != nil {
for {
var has int32
comCall(it, iterHasCurrent, uintptr(unsafe.Pointer(&has)))
if has == 0 {
break
}
var n, v *uint16
comCall(it, iterGetCurrent, uintptr(unsafe.Pointer(&n)), uintptr(unsafe.Pointer(&v)))
rr.Header.Add(coString(n), coString(v))
var more int32
comCall(it, iterMoveNext, uintptr(unsafe.Pointer(&more)))
}
comRelease(it)
}
comRelease(headers)
}
var content unsafe.Pointer
if comCall(rp, reqGetContent, uintptr(unsafe.Pointer(&content))) == 0 && content != nil {
buf := make([]byte, 64<<10)
for {
var n uint32
hr := comCall(content, streamRead, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&n)))
rr.Body = append(rr.Body, buf[:n]...)
if hr != 0 || n == 0 {
break
}
}
comRelease(content)
}
var deferral unsafe.Pointer
comCall(ap, argsGetDeferral, uintptr(unsafe.Pointer(&deferral)))
comCall(ap, 1) // AddRef: args outlive this callback until the response is set
ctx, cancel := context.WithCancel(context.Background())
id := b.nextID.Add(1)
b.tasks.add(id, cancel)
t := &winTask{b: b, args: ap, deferral: deferral, stream: newGoStream()}
// WebView2 has no cancel notification for intercepted requests; the
// closest signal is the page dropping the response stream.
t.stream.onDrop = func() { b.tasks.cancel(id) }
go func() {
defer b.tasks.cancel(id)
b.opt.Resource(ctx, rr, t)
t.Close(nil)
}()
}
// winTask answers one intercepted request. Respond completes the deferral
// with a response whose body is a goStream; Write feeds that stream, so the
// page receives data as it is written.
type winTask struct {
b *winBackend
args unsafe.Pointer
deferral unsafe.Pointer
stream *goStream
mu sync.Mutex
responded bool
closed bool
}
func (t *winTask) Respond(status int, header http.Header) {
t.mu.Lock()
if t.responded {
t.mu.Unlock()
return
}
t.responded = true
t.mu.Unlock()
var hs []string
for k, v := range header {
for _, x := range v {
hs = append(hs, k+": "+x)
}
}
sort.Strings(hs)
reason := http.StatusText(status)
t.b.Dispatch(func() {
env := unsafe.Pointer(t.b.chromium.Environment())
r16, _ := windows.UTF16PtrFromString(reason)
h16, _ := windows.UTF16PtrFromString(strings.Join(hs, "\r\n"))
var resp unsafe.Pointer
hr := comCall(env, envCreateResponse, uintptr(t.stream.ptr()), uintptr(status),
uintptr(unsafe.Pointer(r16)), uintptr(unsafe.Pointer(h16)), uintptr(unsafe.Pointer(&resp)))
if hr == 0 && resp != nil {
comCall(t.args, argsPutResponse, uintptr(resp))
comRelease(resp)
} else if Debugf != nil {
Debugf("window: CreateWebResourceResponse failed: 0x%08x", hr)
}
comCall(t.deferral, deferralComplete)
comRelease(t.deferral)
comRelease(t.args)
t.stream.release() // our own reference; WebView2 holds its own
})
}
func (t *winTask) Write(p []byte) (int, error) {
t.mu.Lock()
responded := t.responded
t.mu.Unlock()
if !responded {
t.Respond(http.StatusOK, nil)
}
return t.stream.write(p)
}
func (t *winTask) Close(err error) {
t.mu.Lock()
if t.closed {
t.mu.Unlock()
return
}
t.closed = true
responded := t.responded
t.mu.Unlock()
if !responded {
if err != nil {
t.Respond(http.StatusBadGateway, nil)
} else {
t.Respond(http.StatusNoContent, nil)
}
}
t.stream.finish()
}
// ---- goStream: a COM IStream whose Read blocks on Go-written chunks -------
type istreamVtbl struct {
QueryInterface, AddRef, Release uintptr
Read, Write, Seek, SetSize, CopyTo, Commit, Revert, Lock, Unlock uintptr
Stat, Clone uintptr
}
type goStream struct {
vtbl *istreamVtbl // must be first: COM object layout
refs atomic.Int32
mu sync.Mutex
cond *sync.Cond
buf []byte
eof bool
pos uint64
pin runtime.Pinner
// onDrop runs when WebView2 released the last reference: the page no
// longer reads the body (finished or aborted).
onDrop func()
}
var (
streamVtbl *istreamVtbl
streamsMu sync.Mutex
liveStreams = map[uintptr]*goStream{}
iidIUnknown = windows.GUID{Data1: 0x00000000, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0, 0, 0, 0, 0, 0, 0x46}}
iidSeqStrm = windows.GUID{Data1: 0x0c733a30, Data2: 0x2a1c, Data3: 0x11ce, Data4: [8]byte{0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}
iidIStream = windows.GUID{Data1: 0x0000000c, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0, 0, 0, 0, 0, 0, 0x46}}
)
const (
sOK = 0
sFalse = 1
eNotImpl = 0x80004001
eNoIface = 0x80004002
stgInvFunc = 0x80030001
)
func initStreamVtbl() {
if streamVtbl != nil {
return
}
notImpl := windows.NewCallback(func(this uintptr) uintptr { return eNotImpl })
notImpl2 := windows.NewCallback(func(this, a uintptr) uintptr { return eNotImpl })
notImpl3 := windows.NewCallback(func(this, a, b uintptr) uintptr { return eNotImpl })
notImpl4 := windows.NewCallback(func(this, a, b, c uintptr) uintptr { return eNotImpl })
streamVtbl = &istreamVtbl{
QueryInterface: windows.NewCallback(func(this uintptr, riid *windows.GUID, out *uintptr) uintptr {
if *riid == iidIUnknown || *riid == iidSeqStrm || *riid == iidIStream {
*out = this
lookupStream(this).refs.Add(1)
return sOK
}
*out = 0
return eNoIface
}),
AddRef: windows.NewCallback(func(this uintptr) uintptr { return uintptr(lookupStream(this).refs.Add(1)) }),
Release: windows.NewCallback(func(this uintptr) uintptr {
s := lookupStream(this)
n := s.refs.Add(-1)
if n == 0 {
s.drop()
}
return uintptr(n)
}),
// WebView2 calls Read on a background thread and reads to EOF before
// the page sees any byte (measured: no incremental delivery, and
// E_PENDING fails the request). Blocking here is therefore fine,
// but it is not a streaming path.
Read: windows.NewCallback(func(this uintptr, pv *byte, cb uint32, pcbRead *uint32) uintptr {
n := lookupStream(this).read(unsafe.Slice(pv, cb))
if pcbRead != nil {
*pcbRead = uint32(n)
}
if n == 0 {
return sFalse
}
return sOK
}),
Write: notImpl4,
Seek: windows.NewCallback(func(this uintptr, move int64, origin uint32, newPos *uint64) uintptr {
s := lookupStream(this)
if origin == 1 && move == 0 { // STREAM_SEEK_CUR, 0: tell
if newPos != nil {
s.mu.Lock()
*newPos = s.pos
s.mu.Unlock()
}
return sOK
}
return stgInvFunc
}),
SetSize: notImpl2,
CopyTo: notImpl4,
Commit: notImpl2,
Revert: notImpl,
Lock: notImpl4,
Unlock: notImpl4,
Stat: notImpl3,
Clone: notImpl2,
}
}
func newGoStream() *goStream {
streamsMu.Lock()
initStreamVtbl()
s := &goStream{vtbl: streamVtbl}
s.cond = sync.NewCond(&s.mu)
s.refs.Store(1) // ours, released after the response was handed over
s.pin.Pin(s)
liveStreams[uintptr(unsafe.Pointer(s))] = s
streamsMu.Unlock()
return s
}
func lookupStream(p uintptr) *goStream {
streamsMu.Lock()
defer streamsMu.Unlock()
return liveStreams[p]
}
func (s *goStream) ptr() unsafe.Pointer { return unsafe.Pointer(s) }
func (s *goStream) release() {
if s.refs.Add(-1) == 0 {
s.drop()
}
}
func (s *goStream) drop() {
s.finish()
if s.onDrop != nil {
go s.onDrop()
}
streamsMu.Lock()
delete(liveStreams, uintptr(unsafe.Pointer(s)))
streamsMu.Unlock()
s.pin.Unpin()
}
func (s *goStream) write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.eof {
return 0, context.Canceled
}
s.buf = append(s.buf, p...)
s.cond.Broadcast()
return len(p), nil
}
func (s *goStream) finish() {
s.mu.Lock()
s.eof = true
s.cond.Broadcast()
s.mu.Unlock()
}
// read blocks until data or EOF; it returns what is available (at most len
// p), so chunks reach the page as soon as they are written.
func (s *goStream) read(p []byte) int {
s.mu.Lock()
defer s.mu.Unlock()
for len(s.buf) == 0 && !s.eof {
s.cond.Wait()
}
n := copy(p, s.buf)
s.buf = s.buf[n:]
s.pos += uint64(n)
return n
}
+183
View File
@@ -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)
}
+87
View File
@@ -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
View File
@@ -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
View File
@@ -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,
+33 -4
View File
@@ -13,6 +13,15 @@ import "yetano.dev/yetano/core"
// preferences-adjacent files and its bulk data side by side); State gets
// 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 {
if scope == core.SystemScope {
return "/Library/Application Support"
@@ -80,7 +89,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 +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
}
// 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 +169,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,
+16
View File
@@ -93,3 +93,19 @@ func TestDarwinServiceUsesXDGLikeLayout(t *testing.T) {
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
View File
@@ -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
View File
@@ -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
View File
@@ -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())
}
+72
View File
@@ -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])
}
}
}
+36
View File
@@ -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
}
+27 -12
View File
@@ -23,13 +23,16 @@ type unixFlavor struct {
}
// flavor selects the unixFlavor for r.platform. darwin (in CLI/Service
// kind) and any GOOS not otherwise recognized fall back to the Linux
// flavor as a documented, sane default -- see AGENTS.md TODO for tuning
// individual BSDs later without a redesign.
// kind) uses the Linux flavor with macOS's runtime base; any GOOS not
// otherwise recognized falls back to the Linux flavor as a documented,
// sane default -- see AGENTS.md TODO for tuning individual BSDs later
// without a redesign.
func (r *Resolver) flavor() unixFlavor {
switch r.platform {
case "freebsd":
return freebsdFlavor
case "darwin":
return darwinFlavor
default:
return linuxFlavor
}
@@ -146,9 +149,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 +189,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 +218,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 +248,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
View File
@@ -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
+23
View File
@@ -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()
+257
View File
@@ -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
}
+127
View File
@@ -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)
}
}
+79
View File
@@ -0,0 +1,79 @@
# yetano.dev/yetano/core/tui
The shared kernel of the Yetano terminal UIs, on Charm v2
(`charm.land/lipgloss/v2`). It is the code that yet's TUI
(`yet/internal/tui`), yavebu's TUI (`yavebu/internal/tui`) and yalsh's
menuconfig (`yalsh/cli/internal/menuconfig`) each carried as a hand-kept
copy -- and that had already started to drift (yavebu's slate theme kept
two blue-tinted greys that render dark blue without truecolor; yet and
yavebu kept an older, truecolor-only `paint`).
```text
module yetano.dev/yetano/core/tui tags: tui/v0.1.0, ... go 1.25
```
A nested module of the core repository, like `core/gui`, so the main core
module stays free of Charm. Depends only on lipgloss v2 (and
`colorprofile` in tests); no bubbletea, no bubbles.
```sh
GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/tui@tui/v0.1.0
```
## API
| | |
|---|---|
| `Theme`, `ThemeByName(name)`, `ThemeNames`, `ValidTheme`, `NormalizeThemeName`, `NextThemeName` | the three themes `slate` (default), `dialog`, `midnight`; F2 cycles them |
| `Theme.Styles() Styles` | the 21 lipgloss styles (Root, Header, Info, Panel, PanelAlt, ListItem, ListSelected, Search, Footer, Key, Value, ...) |
| `Paint(block, fg, bg, width)` | re-grounds a pre-styled block on its area's colors after every SGR reset and pads each line (menuconfig's profile-aware version) |
| `Outer(style, w, h)` | sizes a style so the rendered block, border and padding included, is exactly w x h |
| `ListState{Filtered, Cursor, Scroll}` with `Rebuild`, `Move`, `ClampScroll`, `Index` | filtered list with cursor and scroll window |
| `Truncate`, `TruncateBlock`, `WrapStyled`, `KeyValue`, `FirstNonEmpty` | text helpers; `Truncate` counts runes, not cells (unchanged behavior) |
The values are byte-identical to yet's `theme.go` (= menuconfig's). The
exported names are the former unexported ones capitalized; `listState`
fields are exported (`filtered` -> `Filtered`, ...).
## Not in the kernel (yet)
- The app frame (`render()`: header, info bar, list + detail, search,
footer): yet, yavebu and menuconfig share the structure, not the code
(minimum sizes, width ratios, stacking differ). A `Frame` helper is the
natural next step once a third v2 program needs it.
- Menus/dialogs, task logs, terminal hand-over (`tea.Exec`), yet's
Markdown renderer and manual view: each exists in one program only.
- Standard screens for `manual`/`doctor`/`version`: only yet has a manual
view; it belongs here once a second program wants it (it would build on
the JSON form of `core/manual`).
- yamc (Charm v1, its own Midnight-Commander palette and layout) and yaki
(no TUI yet) are not consumers.
## Migration (per program, when it is next touched)
**yet** (`internal/tui`):
1. `go get yetano.dev/yetano/core/tui@tui/v0.1.0`.
2. Delete `theme.go` (keep the package comment elsewhere), `list.go`,
`paint`/`outer`/`truncate`/`truncateBlock`/`wrapStyled`/`keyValue`/
`firstNonEmpty` in `view.go`, `ThemeNames`/`ValidTheme` in `app.go`
(re-export `ThemeNames = coretui.ThemeNames` if the CLI uses it).
3. Rename call sites: `themeByName` -> `coretui.ThemeByName`,
`theme.styles()` -> `theme.Styles()`, `paint` -> `coretui.Paint`,
`listState` -> `coretui.ListState` (`.filtered/.cursor/.scroll` ->
`.Filtered/.Cursor/.Scroll`, methods capitalized), and so on.
4. Move `theme_test.go` away (it lives here now). `go test ./...`, then
look at `yet tui` in Apple Terminal (no truecolor) and a truecolor
terminal. `Paint` now emits lipgloss's own sequence, which Bubble Tea
downsamples -- the visible change is that slate stays grey on
256-color terminals.
**yavebu** (`internal/tui`): same steps for `theme.go`, `util.go`
(`listState`, `paint`, `outer`, `truncate*`, `wrapStyled`, `keyValue`,
`firstNonEmpty`) and `ThemeNames`/`ValidTheme` in `tui.go`. Intended
visible change: slate `Panel` `#2A2D33` -> `#2A2A2E` and `SelectedText`
`#202734` -> `#20242B` (the grey fix yet already has).
**yalsh menuconfig**: identical code; whether a `yalsh.dev` program
imports a `yetano.dev` module is an owner decision -- until then it stays
a copy.
+25
View File
@@ -0,0 +1,25 @@
module yetano.dev/yetano/core/tui
go 1.25.0
require (
charm.land/lipgloss/v2 v2.0.6
github.com/charmbracelet/colorprofile v0.4.3
)
require (
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
github.com/charmbracelet/x/ansi v0.11.8 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/mattn/go-runewidth v0.0.24 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
)
+34
View File
@@ -0,0 +1,34 @@
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA=
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro=
github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ=
github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=
github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+54
View File
@@ -0,0 +1,54 @@
package tui
// ListState is the filtered/cursor/scroll state of a list view: Filtered
// holds indexes into the view's own item slice.
type ListState struct {
Filtered []int
Cursor int
Scroll int
}
// Rebuild filters the n items with match and keeps the cursor in range.
func (l *ListState) Rebuild(n int, match func(i int) bool) {
l.Filtered = l.Filtered[:0]
for i := 0; i < n; i++ {
if match(i) {
l.Filtered = append(l.Filtered, i)
}
}
if l.Cursor >= len(l.Filtered) {
l.Cursor = max(0, len(l.Filtered)-1)
}
}
// Move moves the cursor by delta, clamped to the filtered items.
func (l *ListState) Move(delta int) {
l.Cursor += delta
if l.Cursor >= len(l.Filtered) {
l.Cursor = len(l.Filtered) - 1
}
if l.Cursor < 0 {
l.Cursor = 0
}
}
// ClampScroll scrolls so the cursor is visible in a window of rows lines.
func (l *ListState) ClampScroll(rows int) {
if l.Cursor < l.Scroll {
l.Scroll = l.Cursor
}
if l.Cursor >= l.Scroll+rows {
l.Scroll = l.Cursor - rows + 1
}
if l.Scroll < 0 {
l.Scroll = 0
}
}
// Index is the item index under the cursor, or -1.
func (l ListState) Index() int {
if l.Cursor < 0 || l.Cursor >= len(l.Filtered) {
return -1
}
return l.Filtered[l.Cursor]
}
+49
View File
@@ -0,0 +1,49 @@
package tui
import (
"image/color"
"strings"
"charm.land/lipgloss/v2"
)
// Paint grounds a pre-styled block on its area's colors: lipgloss ends
// every styled segment with a full SGR reset, which also drops the
// enclosing area's background and foreground, so the rest of that line
// (JoinVertical/Width padding, the gap between panels, unstyled borders,
// plain text after a styled label) would fall back to the terminal's own
// colors -- black background, and white or bold-yellow text that is
// unreadable on a light header. Paint re-applies fg/bg after every reset
// and pads each line to width with them. The sequence comes from lipgloss
// itself; Bubble Tea downsamples it to the terminal's color profile.
//
// This is menuconfig's version; yet's and yavebu's copies hard-coded a
// truecolor sequence instead.
func Paint(block string, fg, bg color.Color, width int) string {
set, _, _ := strings.Cut(lipgloss.NewStyle().Foreground(fg).Background(bg).Render("x"), "x")
lines := strings.Split(block, "\n")
for i, line := range lines {
if set != "" {
line = strings.ReplaceAll(line, "\x1b[0m", "\x1b[m")
line = strings.ReplaceAll(line, "\x1b[m", "\x1b[m"+set)
}
if pad := width - lipgloss.Width(line); pad > 0 {
line += strings.Repeat(" ", pad)
}
if set != "" {
line = set + line + "\x1b[m"
}
lines[i] = line
}
return strings.Join(lines, "\n")
}
// Outer sizes style so its rendered block, border and padding included,
// is exactly width x height cells (height 0: natural height).
func Outer(style lipgloss.Style, width, height int) lipgloss.Style {
style = style.Width(width).MaxWidth(width)
if height > 0 {
style = style.Height(height).MaxHeight(height)
}
return style
}
+66
View File
@@ -0,0 +1,66 @@
package tui
import (
"strings"
"charm.land/lipgloss/v2"
)
// Truncate cuts text to width with a trailing "..." (width > 3).
// It counts runes, not terminal cells: wide (CJK, emoji) characters can
// still overflow -- the behavior the programs had; a cell-aware version
// would be a deliberate, tested change.
func Truncate(text string, width int) string {
if width <= 0 {
return ""
}
runes := []rune(text)
if len(runes) <= width {
return text
}
if width <= 3 {
return string(runes[:width])
}
return string(runes[:width-3]) + "..."
}
// TruncateBlock truncates every line of text to width.
func TruncateBlock(text string, width int) string {
lines := strings.Split(text, "\n")
for i, line := range lines {
lines[i] = Truncate(line, width)
}
return strings.Join(lines, "\n")
}
// WrapStyled wraps text to width and renders each line with style.
func WrapStyled(text string, width int, style lipgloss.Style) []string {
if strings.TrimSpace(text) == "" {
return []string{style.Render("")}
}
wrapped := lipgloss.NewStyle().Width(width).Render(text)
lines := strings.Split(wrapped, "\n")
for i, line := range lines {
lines[i] = style.Render(line)
}
return lines
}
// KeyValue returns a renderer for "key: value" lines of at most width
// cells, the value truncated.
func KeyValue(width int, styles Styles) func(k, v string) string {
return func(k, v string) string {
label := k + ": "
return styles.Key.Render(label) + styles.Value.Render(Truncate(v, width-lipgloss.Width(label)))
}
}
// FirstNonEmpty returns the first non-empty value, or "".
func FirstNonEmpty(values ...string) string {
for _, v := range values {
if v != "" {
return v
}
}
return ""
}
+237
View File
@@ -0,0 +1,237 @@
// Package tui is the shared kernel of the Yetano terminal UIs (Charm v2):
// the three color themes and their lipgloss styles, the paint/outer layout
// helpers, the filtered list state and the text helpers that yet's TUI,
// yavebu's TUI and yalsh's menuconfig each carried as a hand-kept copy.
// It deliberately holds no app shell, menus or screens -- those still
// differ per program (see README.md).
package tui
import (
"image/color"
"charm.land/lipgloss/v2"
)
// Theme is one color scheme; every surface of a Yetano TUI takes its colors
// from these roles.
type Theme struct {
Name string
Background color.Color
Panel color.Color
PanelAlt color.Color
PanelBorder color.Color
Text color.Color
Muted color.Color
Accent color.Color
AccentText color.Color
Selected color.Color
SelectedText color.Color
Success color.Color
Warning color.Color
}
// Styles are the lipgloss styles derived from a Theme.
type Styles struct {
Root lipgloss.Style
Header lipgloss.Style
HeaderTitle lipgloss.Style
HeaderMeta lipgloss.Style
Info lipgloss.Style
Panel lipgloss.Style
PanelAlt lipgloss.Style
PanelTitle lipgloss.Style
ListItem lipgloss.Style
ListEnabled lipgloss.Style
ListSelected lipgloss.Style
Search lipgloss.Style
SearchLabel lipgloss.Style
SearchInput lipgloss.Style
Footer lipgloss.Style
Key lipgloss.Style
Value lipgloss.Style
Text lipgloss.Style
Subtle lipgloss.Style
Warning lipgloss.Style
Empty lipgloss.Style
}
// NormalizeThemeName maps "" and "default" (and anything unknown) to
// "slate"; known names stay.
func NormalizeThemeName(name string) string {
switch name {
case "", "default":
return "slate"
case "slate", "dialog", "midnight":
return name
default:
return "slate"
}
}
// NextThemeName is the theme after current in the cycle slate -> dialog ->
// midnight -> slate (the F2 key).
func NextThemeName(current string) string {
switch NormalizeThemeName(current) {
case "slate":
return "dialog"
case "dialog":
return "midnight"
default:
return "slate"
}
}
// ThemeByName returns the named theme (see NormalizeThemeName).
func ThemeByName(name string) Theme {
switch NormalizeThemeName(name) {
case "dialog":
return Theme{
Name: "dialog",
Background: lipgloss.Color("#1B2D70"),
Panel: lipgloss.Color("#3552A5"),
PanelAlt: lipgloss.Color("#2E4A95"),
PanelBorder: lipgloss.Color("#AFC6FF"),
Text: lipgloss.Color("#F6F8FF"),
Muted: lipgloss.Color("#D9E2FF"),
Accent: lipgloss.Color("#EDF3FF"),
AccentText: lipgloss.Color("#12307A"),
Selected: lipgloss.Color("#FFF2A8"),
SelectedText: lipgloss.Color("#1B2450"),
Success: lipgloss.Color("#C2FFD1"),
Warning: lipgloss.Color("#FFE08A"),
}
case "midnight":
return Theme{
Name: "midnight",
Background: lipgloss.Color("#0B1020"),
Panel: lipgloss.Color("#102341"),
PanelAlt: lipgloss.Color("#17315A"),
PanelBorder: lipgloss.Color("#4C89C8"),
Text: lipgloss.Color("#EAF6FF"),
Muted: lipgloss.Color("#B6CEE4"),
Accent: lipgloss.Color("#FFD166"),
AccentText: lipgloss.Color("#12233C"),
Selected: lipgloss.Color("#64C7FF"),
SelectedText: lipgloss.Color("#0C1D33"),
Success: lipgloss.Color("#95E6B0"),
Warning: lipgloss.Color("#FFC857"),
}
default:
return Theme{
Name: "slate",
Background: lipgloss.Color("#1D1F24"),
Panel: lipgloss.Color("#2A2A2E"),
PanelAlt: lipgloss.Color("#343840"),
PanelBorder: lipgloss.Color("#6F7683"),
Text: lipgloss.Color("#F2F3F5"),
Muted: lipgloss.Color("#C5CAD3"),
Accent: lipgloss.Color("#BDC7D8"),
AccentText: lipgloss.Color("#1D232F"),
Selected: lipgloss.Color("#E7EDF7"),
SelectedText: lipgloss.Color("#20242B"),
Success: lipgloss.Color("#B5E48C"),
Warning: lipgloss.Color("#FFD27D"),
}
}
}
// Styles derives the lipgloss styles of t.
func (t Theme) Styles() Styles {
return Styles{
Root: lipgloss.NewStyle().
Background(t.Background).
Foreground(t.Text).
Padding(1, 2),
Header: lipgloss.NewStyle().
Background(t.Accent).
Foreground(t.AccentText).
Bold(true).
Padding(0, 1),
HeaderTitle: lipgloss.NewStyle().
Background(t.Accent).
Foreground(t.AccentText).
Bold(true).
MarginRight(2),
HeaderMeta: lipgloss.NewStyle().
Background(t.Accent).
Foreground(t.AccentText),
Info: lipgloss.NewStyle().
Background(t.PanelAlt).
Foreground(t.Muted).
Padding(0, 1),
Panel: lipgloss.NewStyle().
Background(t.Panel).
Foreground(t.Text).
Border(lipgloss.RoundedBorder()).
BorderForeground(t.PanelBorder).
Padding(1, 1),
PanelAlt: lipgloss.NewStyle().
Background(t.PanelAlt).
Foreground(t.Text).
Border(lipgloss.RoundedBorder()).
BorderForeground(t.PanelBorder).
Padding(1, 1),
PanelTitle: lipgloss.NewStyle().
Foreground(t.Accent).
Bold(true).
MarginBottom(1),
ListItem: lipgloss.NewStyle().
Foreground(t.Text).
Padding(0, 1),
ListEnabled: lipgloss.NewStyle().
Foreground(t.Success).
Padding(0, 1),
ListSelected: lipgloss.NewStyle().
Background(t.Selected).
Foreground(t.SelectedText).
Bold(true).
Padding(0, 1),
Search: lipgloss.NewStyle().
Background(t.Panel).
Foreground(t.Text).
Border(lipgloss.NormalBorder()).
BorderForeground(t.PanelBorder).
Padding(0, 1),
SearchLabel: lipgloss.NewStyle().
Foreground(t.Accent).
Bold(true),
SearchInput: lipgloss.NewStyle().
Foreground(t.Text),
Footer: lipgloss.NewStyle().
Background(t.PanelAlt).
Foreground(t.Muted).
Padding(0, 1),
Key: lipgloss.NewStyle().
Foreground(t.Accent).
Bold(true),
Value: lipgloss.NewStyle().
Foreground(t.Text),
Text: lipgloss.NewStyle().
Foreground(t.Text),
Subtle: lipgloss.NewStyle().
Foreground(t.Muted).
Bold(true),
Warning: lipgloss.NewStyle().
Foreground(t.Warning).
Bold(true),
Empty: lipgloss.NewStyle().
Foreground(t.Muted).
Italic(true),
}
}
// ThemeNames lists the accepted --theme values.
var ThemeNames = []string{"slate", "dialog", "midnight"}
// ValidTheme reports whether name is one of ThemeNames (or empty).
func ValidTheme(name string) bool {
if name == "" {
return true
}
for _, n := range ThemeNames {
if n == name {
return true
}
}
return false
}
+152
View File
@@ -0,0 +1,152 @@
package tui
import (
"image/color"
"strings"
"testing"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/colorprofile"
)
// TestSlateDarkColorsStayGreyWithoutTruecolor guards the slate theme's
// dark surfaces against a terminal without truecolor (no COLORTERM, e.g.
// Apple Terminal, ssh, tmux without Tc): bubbletea then downsamples every
// color to the 256-color palette, and a dark grey with a slight blue tint
// (#2A2D33 for Panel did) lands on index 17, #00005F -- painting the list
// panel and search bar dark blue. Each of these must map to a grey.
func TestSlateDarkColorsStayGreyWithoutTruecolor(t *testing.T) {
th := ThemeByName("slate")
for name, c := range map[string]color.Color{
"Background": th.Background,
"Panel": th.Panel,
"PanelAlt": th.PanelAlt,
"AccentText": th.AccentText,
"SelectedText": th.SelectedText,
} {
got := colorprofile.ANSI256.Convert(c)
r, g, b, _ := got.RGBA()
if r != g || g != b {
t.Errorf("slate %s converts to non-grey 256-color %v (#%02x%02x%02x)", name, got, r>>8, g>>8, b>>8)
}
}
}
func TestThemeNames(t *testing.T) {
for in, want := range map[string]string{"": "slate", "default": "slate", "bogus": "slate", "dialog": "dialog", "midnight": "midnight"} {
if got := NormalizeThemeName(in); got != want {
t.Errorf("NormalizeThemeName(%q) = %q, want %q", in, got, want)
}
if got := ThemeByName(in).Name; got != want {
t.Errorf("ThemeByName(%q).Name = %q, want %q", in, got, want)
}
}
name := "slate"
for i, want := range []string{"dialog", "midnight", "slate"} {
name = NextThemeName(name)
if name != want {
t.Fatalf("cycle step %d = %q, want %q", i, name, want)
}
}
for _, n := range append([]string{""}, ThemeNames...) {
if !ValidTheme(n) {
t.Errorf("ValidTheme(%q) = false", n)
}
}
if ValidTheme("default") || ValidTheme("x") {
t.Error("ValidTheme accepts a name outside ThemeNames")
}
_ = ThemeByName("dialog").Styles() // must not panic
}
func TestListState(t *testing.T) {
var l ListState
if l.Index() != -1 {
t.Fatal("empty list must have Index -1")
}
l.Rebuild(10, func(i int) bool { return i%2 == 0 }) // 0 2 4 6 8
l.Move(3)
if l.Index() != 6 {
t.Fatalf("Index = %d, want 6", l.Index())
}
l.Move(100)
if l.Cursor != 4 || l.Index() != 8 {
t.Fatalf("Move past end: cursor %d index %d", l.Cursor, l.Index())
}
l.ClampScroll(2)
if l.Scroll != 3 {
t.Fatalf("Scroll = %d, want 3", l.Scroll)
}
l.Rebuild(10, func(i int) bool { return i < 4 }) // 0 1 2 3: cursor clamps
if l.Cursor != 3 {
t.Fatalf("Rebuild must clamp cursor, got %d", l.Cursor)
}
l.Move(-100)
l.ClampScroll(2)
if l.Cursor != 0 || l.Scroll != 0 {
t.Fatalf("cursor %d scroll %d", l.Cursor, l.Scroll)
}
l.Rebuild(3, func(int) bool { return false })
if l.Cursor != 0 || l.Index() != -1 {
t.Fatal("empty filter")
}
}
func TestTextHelpers(t *testing.T) {
cases := []struct {
in string
w int
want string
}{{"hello", 10, "hello"}, {"hello world", 8, "hello..."}, {"hello", 2, "he"}, {"hello", 0, ""}, {"äöüäöü", 5, "äö..."}}
for _, c := range cases {
if got := Truncate(c.in, c.w); got != c.want {
t.Errorf("Truncate(%q,%d) = %q, want %q", c.in, c.w, got, c.want)
}
}
if got := TruncateBlock("abcdef\nxy", 5); got != "ab...\nxy" {
t.Errorf("TruncateBlock = %q", got)
}
if got := FirstNonEmpty("", "", "b", "c"); got != "b" {
t.Errorf("FirstNonEmpty = %q", got)
}
if got := WrapStyled("one two three", 7, lipgloss.NewStyle()); len(got) != 2 {
t.Errorf("WrapStyled = %q", got)
}
if got := WrapStyled(" ", 7, lipgloss.NewStyle()); len(got) != 1 {
t.Errorf("WrapStyled blank = %q", got)
}
kv := KeyValue(12, ThemeByName("slate").Styles())("name", "a-very-long-value")
if w := lipgloss.Width(kv); w > 12 {
t.Errorf("KeyValue width %d > 12: %q", w, kv)
}
}
func TestPaintReappliesColorsAndPads(t *testing.T) {
th := ThemeByName("slate")
set, _, _ := strings.Cut(lipgloss.NewStyle().Foreground(th.Text).Background(th.Background).Render("x"), "x")
if set == "" {
t.Skip("lipgloss rendered no color sequence")
}
got := Paint("a\x1b[0mb\nc", th.Text, th.Background, 4)
lines := strings.Split(got, "\n")
if len(lines) != 2 {
t.Fatalf("lines = %q", lines)
}
if want := set + "a\x1b[m" + set + "b \x1b[m"; lines[0] != want {
t.Errorf("line 0 = %q, want %q", lines[0], want)
}
if lipgloss.Width(lines[1]) != 4 {
t.Errorf("line 1 not padded to 4: %q", lines[1])
}
}
func TestOuter(t *testing.T) {
s := Outer(lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 1), 20, 5)
out := s.Render("x")
if w, h := lipgloss.Width(out), lipgloss.Height(out); w != 20 || h != 5 {
t.Errorf("Outer block %dx%d, want 20x5", w, h)
}
if h := lipgloss.Height(Outer(lipgloss.NewStyle(), 10, 0).Render("a\nb\nc")); h != 3 {
t.Errorf("height 0 must keep natural height, got %d", h)
}
}
+152
View File
@@ -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
}
+98
View File
@@ -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)
}
}