Compare commits
27
Commits
No files matched your search
@@ -250,3 +250,39 @@ exists to do so (`config create`, `config upgrade --write`).
|
||||
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.
|
||||
@@ -1,9 +1,15 @@
|
||||
MIT License
|
||||
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||
|
||||
Copyright (c) 2026 yetano
|
||||
This software and its documentation are proprietary
|
||||
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
|
||||
publish, distribute, sublicense or sell copies of this software, in whole
|
||||
or in part, is granted without the prior written permission of the
|
||||
copyright holder.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -13,6 +13,14 @@ every Yetano program offers (`core/manual`, `core/completion`,
|
||||
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)), and
|
||||
the publisher-signature check `yetano.dev/yetano/core/trust` (tags
|
||||
`trust/vX.Y.Z`, minisign, see [trust/README.md](trust/README.md)).
|
||||
|
||||
```text
|
||||
yetano.dev/yetano/core
|
||||
yetano.dev/yetano/core/paths
|
||||
@@ -21,8 +29,19 @@ 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/backup
|
||||
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)
|
||||
yetano.dev/yetano/core/trust (own module, tags trust/vX.Y.Z)
|
||||
```
|
||||
|
||||
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||
@@ -237,6 +256,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,
|
||||
@@ -285,11 +325,18 @@ 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.
|
||||
of the program's commands. A level that also takes a path (a program
|
||||
without subcommands, started as `<program> [path]`) adds the key
|
||||
`completion.Files`; the script then completes files and directories
|
||||
there besides the command names.
|
||||
- `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).
|
||||
exit code (0 all good, 1 a check failed, 2 usage). A check may carry
|
||||
an `area` (a group such as "config" or "services") and a `hint` (what
|
||||
to do about it), recorded with `Add(doctor.Check{...})`; both are
|
||||
omitted from the JSON when empty, and the table only gets an AREA or
|
||||
HINT column when some check uses it (since v0.10.0).
|
||||
|
||||
## core/configcmd: "<program> config"
|
||||
|
||||
@@ -317,10 +364,80 @@ 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.
|
||||
A struct whose fields are alternatives (a secret from `env`, `file` or
|
||||
`value`) implements the marker `configcmd.OneOf` (`func (SecretRef)
|
||||
ConfigOneOf() {}`): one alternative in the template documents it, and
|
||||
`upgrade` offers none of the others to a file that already chose one.
|
||||
`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`, plus the program's own
|
||||
`Spec.SecretKeys` such as `database.url` (a key covers everything below
|
||||
it) -- are redacted unless `--show-secrets`, references like `env:X`
|
||||
stay visible; inside a list the same rule applies to every entry's
|
||||
fields, a Spec key naming them without the index: `admins.password`), 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
|
||||
@@ -349,7 +466,10 @@ one-line form for log lines and web UI footers.
|
||||
|
||||
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`, `tui` and `trust`
|
||||
modules have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`,
|
||||
`trust/v0.1.0`, ...); a change
|
||||
there needs no main-module tag and vice versa.
|
||||
|
||||
## core/secretref
|
||||
|
||||
@@ -373,3 +493,53 @@ log.Print(r.Redact(err.Error())) // resolved values become "***"
|
||||
plain values it accepted before checks `IsReference` and treats anything
|
||||
else as a literal. Used by yavebu,
|
||||
yacry and yadenes.
|
||||
|
||||
## core/backup: "<program> backup"
|
||||
|
||||
The archive behind `<program> backup create|list|verify|restore` (see
|
||||
docs/program-conventions.md in the meta-repository). The program
|
||||
chooses the content; `core/backup` writes, lists, rotates, verifies and
|
||||
unpacks:
|
||||
|
||||
```go
|
||||
w, err := backup.Create(dir, "yanks-registry", version.Version)
|
||||
w.AddFile("registry.db", snapshot) // a consistent copy, not the live file
|
||||
w.AddDir("state", dataDir, skipBlobs) // regular files below a directory
|
||||
w.AddFile("config/yanks-registry.yaml", cfgPath)
|
||||
a, err := w.Close() // atomic: complete or nothing
|
||||
removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, nil)
|
||||
|
||||
m, err := backup.Verify(path) // every file against MANIFEST.json
|
||||
m, err := backup.Extract(path, newDir) // verified first; only below newDir
|
||||
```
|
||||
|
||||
`<program>-<UTC time>.tar.gz`, a gzip tar with `MANIFEST.json` last
|
||||
(schema, program, version, time, each file's name, size, mode and
|
||||
SHA-256). Archives and their directory are owner-only (0600/0700).
|
||||
`Extract` never writes over anything and never outside its destination
|
||||
(`..`, absolute names and links are rejected before a byte is written).
|
||||
`Prune` keeps `Keep{Last, Daily, Weekly, Monthly}` (default 3/7/4/6); an
|
||||
empty `Keep` removes nothing.
|
||||
|
||||
## 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.
|
||||
|
||||
## License
|
||||
|
||||
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE).
|
||||
@@ -23,18 +23,66 @@ speculatively.
|
||||
`docs/install-store-and-profiles.md`).
|
||||
- [x] `yaseva` was built on `core/paths`/`core/config` from the start.
|
||||
- [x] The remaining applications across the `yetano`, `yak`, and
|
||||
`yamase` meta-repos were migrated on 2026-09-22; the record (and the
|
||||
few open follow-ups) is the meta-repo's `TODO-pathchange.md`.
|
||||
`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] `configcmd.OneOf`: `UndocumentedKeys` and `upgrade` know structs
|
||||
whose fields are alternatives (SecretRef `env`/`file`/`value`);
|
||||
`completion.Files` completes paths for programs without subcommands
|
||||
(yamc) -- 2026-10-31.
|
||||
- [x] `backup` (v0.11.0): archive format, rotation, verify, safe
|
||||
extract for the optional `<program> backup` command -- 2026-11-05.
|
||||
- [x] `doctor.Check` with optional `area` and `hint` (JSON and table,
|
||||
omitted when empty), `Report.Add` -- 2026-11-01, for v0.10.0.
|
||||
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
|
||||
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
||||
- [ ] `core/gui`: the native WebView host from
|
||||
`prototypes/yetano-webview` (yet-gui has a copy in `yet/gui/internal`).
|
||||
- [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)).
|
||||
- [x] `core/gui` (macOS): the web view accepts the first mouse click in
|
||||
an inactive window (`YTWebView`, `acceptsFirstMouse:` YES;
|
||||
`gui/v0.2.0`, 2026-11-15) -- before, the first click only activated
|
||||
the window, so a dialog shown at start looked dead (yanks).
|
||||
- [x] `core/gui`: `window.Options.FrameFile` keeps the window's position,
|
||||
size and maximized state across starts (macOS and Windows;
|
||||
`gui/v0.2.0`, 2026-11-15).
|
||||
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
||||
- [ ] `core/gui`: resident app with a prewarmed WebView, for a start
|
||||
under 300 ms (proposal from yamc, 2026-11-29, for its H-STARTUP;
|
||||
see yamc `docs/spec/gui-comparison.md`). Measured on macOS (Apple
|
||||
Silicon, warm): NSApp setup ~65 ms, WKWebView init ~45 ms, window
|
||||
~25 ms, then ~190 ms until the web content process asks for the
|
||||
first resource and ~150 ms for WebKit's first paint -- ~550 ms to
|
||||
the first frame, ~340 ms of it WebKit's own, which only advances
|
||||
while the main run loop runs. Tried without effect (yamc,
|
||||
2026-11-29): `loadRequest` right after the WKWebView exists
|
||||
(before the window is built, also before `finishLaunching`),
|
||||
spinning the run loop after it, building the app's state in
|
||||
parallel -- the first request still comes ~200 ms after the main
|
||||
thread is free. So a fresh process stays at ~500 ms or more.
|
||||
Proposal: keep the process alive after its last window (macOS: a
|
||||
normal Dock app; Windows: a background process), hold one hidden
|
||||
WebView with the page loaded in reserve, and let a new start hand
|
||||
its arguments to the running instance (single instance, e.g. a
|
||||
socket in the runtime dir), which shows the reserve window and
|
||||
prepares the next. Needs several windows per process, a
|
||||
reserve-window API, and the same on WebView2. The first start
|
||||
stays at ~550 ms. Only worth it once a program needs it (yamc's
|
||||
Gio-vs-WebView choice is still open).
|
||||
- [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
|
||||
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
// Package backup is the archive format and handling behind the optional
|
||||
// "<program> backup create|list|verify|restore" commands of the Yetano
|
||||
// program standard (docs/program-conventions.md in the yetano
|
||||
// meta-repository). The program decides what goes in (a consistent
|
||||
// database copy, its config, state files -- never what can be fetched
|
||||
// again); this package writes, lists, rotates, checks and unpacks.
|
||||
//
|
||||
// w, err := backup.Create(dir, "yanks-registry", version.Version)
|
||||
// w.AddFile("registry.db", snapshotPath)
|
||||
// w.AddFile("config/yanks-registry.yaml", cfgPath)
|
||||
// a, err := w.Close() // atomic: complete or nothing
|
||||
// removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, time.Now())
|
||||
//
|
||||
// An archive is a gzip-compressed tar named
|
||||
// "<program>-<UTC time>.tar.gz": the files, then MANIFEST.json (program,
|
||||
// version, time, and every file's name, size, mode and SHA-256).
|
||||
// Archives and their directory are only readable by the owner -- they
|
||||
// hold password hashes and keys as often as not. Extract verifies an
|
||||
// archive completely before it writes anything, and only ever writes
|
||||
// below its destination.
|
||||
package backup
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Schema is the manifest version this package writes and reads.
|
||||
const Schema = 1
|
||||
|
||||
// ManifestName is the archive's last entry.
|
||||
const ManifestName = "MANIFEST.json"
|
||||
|
||||
// timeLayout is the UTC time in archive names; it sorts as text.
|
||||
const timeLayout = "20060102T150405Z"
|
||||
|
||||
// Manifest describes an archive.
|
||||
type Manifest struct {
|
||||
Schema int `json:"schema"`
|
||||
Program string `json:"program"`
|
||||
Version string `json:"version,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Files []File `json:"files"`
|
||||
}
|
||||
|
||||
// File is one archived file. Name is slash-separated and relative.
|
||||
type File struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Mode uint32 `json:"mode"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
// Archive is a backup file in a directory.
|
||||
type Archive struct {
|
||||
Path string `json:"path"`
|
||||
Program string `json:"program"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
// ErrInvalid: the archive is damaged, incomplete or not a backup.
|
||||
var ErrInvalid = errors.New("backup: invalid archive")
|
||||
|
||||
func invalid(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
var (
|
||||
programRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
|
||||
suffixRE = regexp.MustCompile(`^-[0-9]+$`)
|
||||
)
|
||||
|
||||
// Writer builds an archive in a temporary file next to its final name.
|
||||
type Writer struct {
|
||||
dir, program string
|
||||
m Manifest
|
||||
f *os.File
|
||||
gz *gzip.Writer
|
||||
tw *tar.Writer
|
||||
names map[string]bool
|
||||
err error
|
||||
}
|
||||
|
||||
// Create starts an archive of program in dir (created owner-only when
|
||||
// missing).
|
||||
func Create(dir, program, version string) (*Writer, error) {
|
||||
if !programRE.MatchString(program) {
|
||||
return nil, fmt.Errorf("backup: invalid program name %q", program)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
f, err := os.CreateTemp(dir, "."+program+"-*.partial")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
if err := f.Chmod(0o600); err != nil {
|
||||
f.Close()
|
||||
os.Remove(f.Name())
|
||||
return nil, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
gz := gzip.NewWriter(f)
|
||||
return &Writer{dir: dir, program: program, f: f, gz: gz, tw: tar.NewWriter(gz), names: map[string]bool{},
|
||||
m: Manifest{Schema: Schema, Program: program, Version: version, CreatedAt: time.Now().UTC().Truncate(time.Second), Files: []File{}}}, nil
|
||||
}
|
||||
|
||||
// validName: relative, slash-separated, clean, inside the archive.
|
||||
func validName(name string) bool {
|
||||
return name != "" && name != "." && name != ManifestName && !strings.HasPrefix(name, "/") &&
|
||||
!strings.Contains(name, `\`) && path.Clean(name) == name && name != ".." && !strings.HasPrefix(name, "../")
|
||||
}
|
||||
|
||||
func (w *Writer) add(name string, mode fs.FileMode, size int64, mtime time.Time, r io.Reader) error {
|
||||
if w.err != nil {
|
||||
return w.err
|
||||
}
|
||||
if !validName(name) {
|
||||
return fmt.Errorf("backup: invalid name %q", name)
|
||||
}
|
||||
if w.names[name] {
|
||||
return fmt.Errorf("backup: %s added twice", name)
|
||||
}
|
||||
w.names[name] = true
|
||||
perm := uint32(mode.Perm())
|
||||
h := &tar.Header{Name: name, Mode: int64(perm), Size: size, ModTime: mtime, Typeflag: tar.TypeReg, Format: tar.FormatPAX}
|
||||
if err := w.tw.WriteHeader(h); err != nil {
|
||||
w.err = fmt.Errorf("backup: %s: %w", name, err)
|
||||
return w.err
|
||||
}
|
||||
sum := sha256.New()
|
||||
n, err := io.Copy(w.tw, io.TeeReader(r, sum))
|
||||
if err == nil && n != size {
|
||||
err = fmt.Errorf("changed while it was read (%d of %d bytes)", n, size)
|
||||
}
|
||||
if err != nil {
|
||||
w.err = fmt.Errorf("backup: %s: %w", name, err)
|
||||
return w.err
|
||||
}
|
||||
w.m.Files = append(w.m.Files, File{Name: name, Size: size, Mode: perm, SHA256: hex.EncodeToString(sum.Sum(nil))})
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddFile archives the regular file src as name.
|
||||
func (w *Writer) AddFile(name, src string) error {
|
||||
f, err := os.Open(src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return fmt.Errorf("backup: %s is not a regular file", src)
|
||||
}
|
||||
return w.add(name, fi.Mode(), fi.Size(), fi.ModTime(), f)
|
||||
}
|
||||
|
||||
// AddBytes archives data as name.
|
||||
func (w *Writer) AddBytes(name string, data []byte, mode fs.FileMode) error {
|
||||
return w.add(name, mode, int64(len(data)), w.m.CreatedAt, strings.NewReader(string(data)))
|
||||
}
|
||||
|
||||
// AddDir archives the regular files below src as prefix/<relative
|
||||
// path>, in a stable order. skip (may be nil) leaves out a file or, for
|
||||
// a directory, everything below it; rel is slash-separated. Symbolic
|
||||
// links and other special files are left out.
|
||||
func (w *Writer) AddDir(prefix, src string, skip func(rel string, d fs.DirEntry) bool) error {
|
||||
return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
rel, err := filepath.Rel(src, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rel == "." {
|
||||
return nil
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
if skip != nil && skip(rel, d) {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !d.Type().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
return w.AddFile(path.Join(prefix, rel), p)
|
||||
})
|
||||
}
|
||||
|
||||
// Close finishes the archive: the manifest, then an atomic rename to
|
||||
// "<program>-<time>.tar.gz". After an error the archive is removed.
|
||||
func (w *Writer) Close() (Archive, error) {
|
||||
if w.err != nil {
|
||||
w.Abort()
|
||||
return Archive{}, w.err
|
||||
}
|
||||
b, err := json.MarshalIndent(w.m, "", " ")
|
||||
if err == nil {
|
||||
err = w.tw.WriteHeader(&tar.Header{Name: ManifestName, Mode: 0o600, Size: int64(len(b)), ModTime: w.m.CreatedAt,
|
||||
Typeflag: tar.TypeReg, Format: tar.FormatPAX})
|
||||
}
|
||||
if err == nil {
|
||||
_, err = w.tw.Write(b)
|
||||
}
|
||||
if err == nil {
|
||||
err = w.tw.Close()
|
||||
}
|
||||
if err == nil {
|
||||
err = w.gz.Close()
|
||||
}
|
||||
if err == nil {
|
||||
err = w.f.Sync()
|
||||
}
|
||||
if cerr := w.f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(w.f.Name())
|
||||
return Archive{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
final, err := freeName(w.dir, w.program, w.m.CreatedAt)
|
||||
if err == nil {
|
||||
err = os.Rename(w.f.Name(), final)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(w.f.Name())
|
||||
return Archive{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
fi, err := os.Stat(final)
|
||||
if err != nil {
|
||||
return Archive{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
return Archive{Path: final, Program: w.program, CreatedAt: w.m.CreatedAt, Size: fi.Size()}, nil
|
||||
}
|
||||
|
||||
// Abort drops an unfinished archive.
|
||||
func (w *Writer) Abort() {
|
||||
w.f.Close()
|
||||
os.Remove(w.f.Name())
|
||||
}
|
||||
|
||||
func freeName(dir, program string, t time.Time) (string, error) {
|
||||
base := program + "-" + t.UTC().Format(timeLayout)
|
||||
for i := 1; i < 100; i++ {
|
||||
name := base + ".tar.gz"
|
||||
if i > 1 {
|
||||
name = fmt.Sprintf("%s-%d.tar.gz", base, i)
|
||||
}
|
||||
p := filepath.Join(dir, name)
|
||||
if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no free archive name for %s", base)
|
||||
}
|
||||
|
||||
// parseName reads the time and the sequence number (1, or n of "-n")
|
||||
// from an archive's file name.
|
||||
func parseName(name, program string) (time.Time, int, bool) {
|
||||
rest, ok := strings.CutPrefix(name, program+"-")
|
||||
if !ok {
|
||||
return time.Time{}, 0, false
|
||||
}
|
||||
rest, ok = strings.CutSuffix(rest, ".tar.gz")
|
||||
if !ok || len(rest) < len(timeLayout) {
|
||||
return time.Time{}, 0, false
|
||||
}
|
||||
stamp, suffix := rest[:len(timeLayout)], rest[len(timeLayout):]
|
||||
seq := 1
|
||||
if suffix != "" {
|
||||
if !suffixRE.MatchString(suffix) {
|
||||
return time.Time{}, 0, false
|
||||
}
|
||||
fmt.Sscanf(suffix[1:], "%d", &seq)
|
||||
}
|
||||
t, err := time.Parse(timeLayout, stamp)
|
||||
return t, seq, err == nil
|
||||
}
|
||||
|
||||
// List returns program's archives in dir, newest first. A missing dir
|
||||
// is no archive.
|
||||
func List(dir, program string) ([]Archive, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return []Archive{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
out := []Archive{}
|
||||
seq := map[string]int{}
|
||||
for _, e := range entries {
|
||||
t, n, ok := parseName(e.Name(), program)
|
||||
if !ok || !e.Type().IsRegular() {
|
||||
continue
|
||||
}
|
||||
fi, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(dir, e.Name())
|
||||
seq[p] = n
|
||||
out = append(out, Archive{Path: p, Program: program, CreatedAt: t, Size: fi.Size()})
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if !out[i].CreatedAt.Equal(out[j].CreatedAt) {
|
||||
return out[i].CreatedAt.After(out[j].CreatedAt)
|
||||
}
|
||||
return seq[out[i].Path] > seq[out[j].Path]
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Keep says which archives Prune keeps: the Last newest, and the newest
|
||||
// of each of the last Daily days, Weekly ISO weeks and Monthly months
|
||||
// that have one (local time).
|
||||
type Keep struct {
|
||||
Last int `json:"last" yaml:"last"`
|
||||
Daily int `json:"daily" yaml:"daily"`
|
||||
Weekly int `json:"weekly" yaml:"weekly"`
|
||||
Monthly int `json:"monthly" yaml:"monthly"`
|
||||
}
|
||||
|
||||
// DefaultKeep: the 3 newest, a week of days, a month of weeks, half a
|
||||
// year of months.
|
||||
var DefaultKeep = Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}
|
||||
|
||||
// Prune removes program's archives in dir that keep does not hold and
|
||||
// returns them. A Keep of all zeros removes nothing (a misconfiguration
|
||||
// must not delete every backup).
|
||||
func Prune(dir, program string, keep Keep, loc *time.Location) ([]Archive, error) {
|
||||
if keep == (Keep{}) {
|
||||
return []Archive{}, nil
|
||||
}
|
||||
if loc == nil {
|
||||
loc = time.Local
|
||||
}
|
||||
all, err := List(dir, program)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kept := map[string]bool{}
|
||||
for i := 0; i < keep.Last && i < len(all); i++ {
|
||||
kept[all[i].Path] = true
|
||||
}
|
||||
bucket := func(n int, key func(time.Time) string) {
|
||||
seen := map[string]bool{}
|
||||
for _, a := range all { // newest first: the first of a bucket is its newest
|
||||
k := key(a.CreatedAt.In(loc))
|
||||
if seen[k] {
|
||||
continue
|
||||
}
|
||||
if len(seen) == n {
|
||||
return
|
||||
}
|
||||
seen[k] = true
|
||||
kept[a.Path] = true
|
||||
}
|
||||
}
|
||||
bucket(keep.Daily, func(t time.Time) string { return t.Format("2006-01-02") })
|
||||
bucket(keep.Weekly, func(t time.Time) string { y, w := t.ISOWeek(); return fmt.Sprintf("%d-%02d", y, w) })
|
||||
bucket(keep.Monthly, func(t time.Time) string { return t.Format("2006-01") })
|
||||
removed := []Archive{}
|
||||
for _, a := range all {
|
||||
if kept[a.Path] {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(a.Path); err != nil {
|
||||
return removed, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
removed = append(removed, a)
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
// walk reads an archive, calling fn for every file entry with its
|
||||
// content; it returns the manifest after checking that it lists exactly
|
||||
// the files read, with their sizes and checksums.
|
||||
func walk(archive string, fn func(h *tar.Header, r io.Reader) error) (Manifest, error) {
|
||||
var m Manifest
|
||||
f, err := os.Open(archive)
|
||||
if err != nil {
|
||||
return m, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
return m, invalid("%s: %v", filepath.Base(archive), err)
|
||||
}
|
||||
tr := tar.NewReader(gz)
|
||||
got := map[string]File{}
|
||||
haveManifest := false
|
||||
for {
|
||||
h, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return m, invalid("%s: %v", filepath.Base(archive), err)
|
||||
}
|
||||
if haveManifest {
|
||||
return m, invalid("an entry after the manifest: %q", h.Name)
|
||||
}
|
||||
if h.Name == ManifestName {
|
||||
b, err := io.ReadAll(io.LimitReader(tr, 64<<20))
|
||||
if err != nil {
|
||||
return m, invalid("manifest: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return m, invalid("manifest: %v", err)
|
||||
}
|
||||
haveManifest = true
|
||||
continue
|
||||
}
|
||||
if h.Typeflag != tar.TypeReg || !validName(h.Name) {
|
||||
return m, invalid("unexpected entry %q", h.Name)
|
||||
}
|
||||
if _, dup := got[h.Name]; dup {
|
||||
return m, invalid("%q twice", h.Name)
|
||||
}
|
||||
sum := sha256.New()
|
||||
r := io.TeeReader(tr, sum)
|
||||
if fn != nil {
|
||||
if err := fn(h, r); err != nil {
|
||||
return m, err
|
||||
}
|
||||
}
|
||||
if _, err := io.Copy(io.Discard, r); err != nil { // what fn did not read
|
||||
return m, invalid("%s: %v", h.Name, err)
|
||||
}
|
||||
got[h.Name] = File{Name: h.Name, Size: h.Size, SHA256: hex.EncodeToString(sum.Sum(nil))}
|
||||
}
|
||||
if !haveManifest {
|
||||
return m, invalid("no manifest: the archive is incomplete")
|
||||
}
|
||||
if m.Schema != Schema {
|
||||
return m, invalid("manifest schema %d, this program reads %d", m.Schema, Schema)
|
||||
}
|
||||
if len(m.Files) != len(got) {
|
||||
return m, invalid("the manifest lists %d files, the archive holds %d", len(m.Files), len(got))
|
||||
}
|
||||
for _, mf := range m.Files {
|
||||
g, ok := got[mf.Name]
|
||||
if !ok {
|
||||
return m, invalid("%s is missing", mf.Name)
|
||||
}
|
||||
if g.Size != mf.Size || g.SHA256 != mf.SHA256 {
|
||||
return m, invalid("%s does not match its checksum", mf.Name)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Verify reads an archive completely and checks every file against the
|
||||
// manifest.
|
||||
func Verify(archive string) (Manifest, error) {
|
||||
return walk(archive, nil)
|
||||
}
|
||||
|
||||
// Extract verifies the archive, then unpacks it into dest, which must
|
||||
// not exist yet (its parent must): nothing is ever written over, and
|
||||
// nothing outside dest. On an error dest is removed again.
|
||||
func Extract(archive, dest string) (Manifest, error) {
|
||||
if _, err := Verify(archive); err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
if _, err := os.Lstat(dest); err == nil {
|
||||
return Manifest{}, fmt.Errorf("backup: %s exists; extract into a new directory", dest)
|
||||
}
|
||||
if err := os.Mkdir(dest, 0o700); err != nil {
|
||||
return Manifest{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
m, err := walk(archive, func(h *tar.Header, r io.Reader) error {
|
||||
target := filepath.Join(dest, filepath.FromSlash(h.Name))
|
||||
if rel, err := filepath.Rel(dest, target); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return invalid("%q leaves the destination", h.Name)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
f, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fs.FileMode(h.Mode).Perm()|0o200)
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
_, err = io.Copy(f, r)
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Chmod(target, fs.FileMode(h.Mode).Perm())
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Chtimes(target, h.ModTime, h.ModTime)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %s: %w", h.Name, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
os.RemoveAll(dest)
|
||||
return Manifest{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func write(t *testing.T, p, content string, mode fs.FileMode) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(content), mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func makeArchive(t *testing.T, dir string) Archive {
|
||||
t.Helper()
|
||||
src := t.TempDir()
|
||||
write(t, filepath.Join(src, "db"), "database", 0o600)
|
||||
write(t, filepath.Join(src, "state", "users.json"), `{"u":1}`, 0o600)
|
||||
write(t, filepath.Join(src, "state", "repos", "a", "tags", "latest"), "sha256:x", 0o644)
|
||||
write(t, filepath.Join(src, "state", "blobs", "big"), "blob", 0o644)
|
||||
w, err := Create(dir, "prog", "1.2.3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.AddDir("state", filepath.Join(src, "state"), func(rel string, d fs.DirEntry) bool { return rel == "blobs" }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.AddBytes("config/prog.yaml", []byte("listen: x\n"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err == nil {
|
||||
t.Error("the same name added twice")
|
||||
}
|
||||
w.err = nil // the duplicate is the test's own doing
|
||||
a, err := w.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "backups")
|
||||
a := makeArchive(t, dir)
|
||||
if !strings.HasPrefix(filepath.Base(a.Path), "prog-") || !strings.HasSuffix(a.Path, ".tar.gz") {
|
||||
t.Errorf("archive name %s", a.Path)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
for p, want := range map[string]fs.FileMode{dir: 0o700, a.Path: 0o600} {
|
||||
if fi, _ := os.Stat(p); fi.Mode().Perm() != want {
|
||||
t.Errorf("%s mode %v, want %v", p, fi.Mode().Perm(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if left, _ := filepath.Glob(filepath.Join(dir, ".*partial")); len(left) != 0 {
|
||||
t.Errorf("temporary files left: %v", left)
|
||||
}
|
||||
|
||||
m, err := Verify(a.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var names []string
|
||||
for _, f := range m.Files {
|
||||
names = append(names, f.Name)
|
||||
}
|
||||
if m.Program != "prog" || m.Version != "1.2.3" ||
|
||||
strings.Join(names, ",") != "db/registry.db,state/repos/a/tags/latest,state/users.json,config/prog.yaml" {
|
||||
t.Errorf("manifest = %+v", m)
|
||||
}
|
||||
|
||||
dest := filepath.Join(t.TempDir(), "restore")
|
||||
if _, err := Extract(a.Path, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := os.ReadFile(filepath.Join(dest, "state", "users.json"))
|
||||
if string(b) != `{"u":1}` {
|
||||
t.Errorf("users.json = %q", b)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "state", "blobs")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Error("a skipped directory was archived")
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
if fi, _ := os.Stat(filepath.Join(dest, "config", "prog.yaml")); fi.Mode().Perm() != 0o640 {
|
||||
t.Errorf("restored mode %v", fi.Mode().Perm())
|
||||
}
|
||||
}
|
||||
if _, err := Extract(a.Path, dest); err == nil {
|
||||
t.Error("extracted over an existing directory")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDamagedArchives(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := makeArchive(t, dir)
|
||||
raw, _ := os.ReadFile(a.Path)
|
||||
|
||||
// Cut off: no manifest, or not even a complete gzip stream.
|
||||
cut := filepath.Join(dir, "cut.tar.gz")
|
||||
write(t, cut, string(raw[:len(raw)/2]), 0o600)
|
||||
if _, err := Verify(cut); !errors.Is(err, ErrInvalid) {
|
||||
t.Errorf("truncated archive: %v", err)
|
||||
}
|
||||
|
||||
// A file whose content does not match the manifest.
|
||||
tampered := filepath.Join(dir, "tampered.tar.gz")
|
||||
writeTar(t, tampered, []entry{{"db/registry.db", "other!!!"}, {ManifestName, manifestFor(t, a.Path)}})
|
||||
if _, err := Verify(tampered); !errors.Is(err, ErrInvalid) {
|
||||
t.Errorf("tampered archive: %v", err)
|
||||
}
|
||||
|
||||
// Names that leave the destination are refused before anything is
|
||||
// written.
|
||||
for _, name := range []string{"../evil", "/etc/evil", "a/../../evil", `a\..\evil`} {
|
||||
evil := filepath.Join(dir, "evil.tar.gz")
|
||||
writeTar(t, evil, []entry{{name, "x"}, {ManifestName, `{"schema":1,"program":"prog","files":[]}`}})
|
||||
dest := filepath.Join(t.TempDir(), "d")
|
||||
if _, err := Extract(evil, dest); !errors.Is(err, ErrInvalid) {
|
||||
t.Errorf("%q: %v", name, err)
|
||||
}
|
||||
if _, err := os.Stat(dest); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("%q: destination created", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type entry struct{ name, content string }
|
||||
|
||||
func writeTar(t *testing.T, p string, entries []entry) {
|
||||
t.Helper()
|
||||
f, err := os.Create(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gz := gzip.NewWriter(f)
|
||||
tw := tar.NewWriter(gz)
|
||||
for _, e := range entries {
|
||||
tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o600, Size: int64(len(e.content)), Typeflag: tar.TypeReg})
|
||||
tw.Write([]byte(e.content))
|
||||
}
|
||||
tw.Close()
|
||||
gz.Close()
|
||||
f.Close()
|
||||
}
|
||||
|
||||
// manifestFor is a manifest that lists only db/registry.db as in a.
|
||||
func manifestFor(t *testing.T, archive string) string {
|
||||
m, err := Verify(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return `{"schema":1,"program":"prog","files":[{"name":"db/registry.db","size":8,"mode":384,"sha256":"` + m.Files[0].SHA256 + `"}]}`
|
||||
}
|
||||
|
||||
func TestListAndPrune(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
loc := time.UTC
|
||||
start := time.Date(2026, 1, 1, 3, 0, 0, 0, loc)
|
||||
// One archive a day for 200 days, two on the last day.
|
||||
for d := 0; d < 200; d++ {
|
||||
ts := start.AddDate(0, 0, d)
|
||||
write(t, filepath.Join(dir, "prog-"+ts.Format(timeLayout)+".tar.gz"), "x", 0o600)
|
||||
}
|
||||
last := start.AddDate(0, 0, 199)
|
||||
write(t, filepath.Join(dir, "prog-"+last.Format(timeLayout)+"-2.tar.gz"), "x", 0o600)
|
||||
write(t, filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz"), "x", 0o600)
|
||||
write(t, filepath.Join(dir, "prog-notatime.tar.gz"), "x", 0o600)
|
||||
|
||||
all, err := List(dir, "prog")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(all) != 201 || !strings.HasSuffix(all[0].Path, "-2.tar.gz") {
|
||||
t.Fatalf("list = %d, first %s", len(all), all[0].Path)
|
||||
}
|
||||
if none, _ := List(filepath.Join(dir, "missing"), "prog"); len(none) != 0 {
|
||||
t.Error("a missing directory lists archives")
|
||||
}
|
||||
|
||||
if removed, _ := Prune(dir, "prog", Keep{}, loc); len(removed) != 0 {
|
||||
t.Error("an empty Keep removed archives")
|
||||
}
|
||||
removed, err := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept, _ := List(dir, "prog")
|
||||
if len(kept)+len(removed) != 201 {
|
||||
t.Fatalf("kept %d + removed %d", len(kept), len(removed))
|
||||
}
|
||||
// 3 newest (2 of them on the last day) + 6 more days; weekly and
|
||||
// monthly add the older ones: at most 3+7+4+6, at least 7+6.
|
||||
if len(kept) < 13 || len(kept) > 20 {
|
||||
t.Errorf("kept %d archives", len(kept))
|
||||
}
|
||||
months := map[string]bool{}
|
||||
for _, a := range kept {
|
||||
months[a.CreatedAt.Format("2006-01")] = true
|
||||
}
|
||||
if len(months) != 6 {
|
||||
t.Errorf("months kept: %v", months)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz")); err != nil {
|
||||
t.Error("another program's archive was removed")
|
||||
}
|
||||
// Pruning again changes nothing.
|
||||
if again, _ := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc); len(again) != 0 {
|
||||
t.Errorf("second prune removed %d", len(again))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRejectsBadInput(t *testing.T) {
|
||||
if _, err := Create(t.TempDir(), "../x", ""); err == nil {
|
||||
t.Error("program name with a path")
|
||||
}
|
||||
w, err := Create(t.TempDir(), "prog", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer w.Abort()
|
||||
for _, n := range []string{"", "/abs", "../up", "a/./b", ManifestName} {
|
||||
if err := w.AddBytes(n, nil, 0o600); err == nil {
|
||||
t.Errorf("name %q accepted", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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=
|
||||
@@ -5,7 +5,12 @@
|
||||
//
|
||||
// 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.
|
||||
// into a prefix and look up what may follow it. A level that also takes a
|
||||
// file or directory path (a program without subcommands that is started
|
||||
// as "<program> [path]") adds the Files key; the shell then completes
|
||||
// paths there too:
|
||||
//
|
||||
// var tree = completion.Tree{completion.Files: nil, "manual": nil, ...}
|
||||
//
|
||||
// var tree = completion.Tree{
|
||||
// "serve": nil,
|
||||
@@ -41,6 +46,10 @@ func Leaf(names ...string) Tree {
|
||||
return t
|
||||
}
|
||||
|
||||
// Files is a Tree key, not a command: the level it is in also completes
|
||||
// file and directory paths. Its value is ignored.
|
||||
const Files = "<files>"
|
||||
|
||||
// Shells are the supported shells, in the order help texts list them.
|
||||
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
||||
|
||||
@@ -53,6 +62,7 @@ var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`)
|
||||
type entry struct {
|
||||
prefix string
|
||||
words []string
|
||||
files bool // paths complete here too (Files)
|
||||
}
|
||||
|
||||
func flatten(tree Tree) ([]entry, error) {
|
||||
@@ -60,14 +70,19 @@ func flatten(tree Tree) ([]entry, error) {
|
||||
var walk func(prefix string, t Tree) error
|
||||
walk = func(prefix string, t Tree) error {
|
||||
names := make([]string, 0, len(t))
|
||||
files := false
|
||||
for n := range t {
|
||||
if n == Files {
|
||||
files = true
|
||||
continue
|
||||
}
|
||||
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})
|
||||
out = append(out, entry{prefix, names, files})
|
||||
for _, n := range names {
|
||||
if sub := t[n]; len(sub) > 0 {
|
||||
p := n
|
||||
@@ -84,6 +99,15 @@ func flatten(tree Tree) ([]entry, error) {
|
||||
return out, walk("", tree)
|
||||
}
|
||||
|
||||
func anyFiles(entries []entry) bool {
|
||||
for _, e := range entries {
|
||||
if e.files {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Script returns the completion script for shell.
|
||||
func Script(program, shell string, tree Tree) (string, error) {
|
||||
if !safeWord.MatchString(program) {
|
||||
@@ -97,19 +121,33 @@ func Script(program, shell string, tree Tree) (string, error) {
|
||||
var b strings.Builder
|
||||
switch shell {
|
||||
case "bash":
|
||||
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program)
|
||||
fmt.Fprintf(&b, "# %s 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, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\"))", e.prefix, strings.Join(e.words, " "))
|
||||
if e.files {
|
||||
// One path per line, so names with spaces stay whole;
|
||||
// compopt (bash 4+) adds the trailing "/" and quoting.
|
||||
b.WriteString("\n local IFS=$'\\n'; COMPREPLY+=($(compgen -f -- \"$cur\")); compopt -o filenames 2>/dev/null")
|
||||
}
|
||||
b.WriteString("; return ;;\n")
|
||||
}
|
||||
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)
|
||||
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\" files=0\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, " "))
|
||||
f := ""
|
||||
if e.files {
|
||||
f = "; files=1"
|
||||
}
|
||||
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n")
|
||||
fmt.Fprintf(&b, " %q) completions=(%s)%s ;;\n", e.prefix, strings.Join(e.words, " "), f)
|
||||
}
|
||||
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n")
|
||||
if anyFiles(entries) {
|
||||
b.WriteString(" (( files )) && _files\n")
|
||||
}
|
||||
b.WriteString("}\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)
|
||||
@@ -125,6 +163,9 @@ func Script(program, shell string, tree Tree) (string, error) {
|
||||
quoted[i] = fmt.Sprintf("%q", w)
|
||||
}
|
||||
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
|
||||
if e.files {
|
||||
b.WriteString(" __fish_complete_path (commandline -ct)\n")
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
|
||||
case "powershell":
|
||||
@@ -143,7 +184,18 @@ func Script(program, shell string, tree Tree) (string, error) {
|
||||
}
|
||||
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")
|
||||
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n")
|
||||
var filePrefixes []string
|
||||
for _, e := range entries {
|
||||
if e.files {
|
||||
filePrefixes = append(filePrefixes, "'"+e.prefix+"'")
|
||||
}
|
||||
}
|
||||
if len(filePrefixes) > 0 {
|
||||
fmt.Fprintf(&b, " if (@(%s) -contains $prefix) {\n", strings.Join(filePrefixes, ", "))
|
||||
b.WriteString(" [System.Management.Automation.CompletionCompleters]::CompleteFilename($wordToComplete)\n }\n")
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
default:
|
||||
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ package completion
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -48,3 +51,66 @@ func TestBashCompletes(t *testing.T) {
|
||||
t.Fatalf("bash completion: %v %q", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// A program without subcommands takes a path as its first argument.
|
||||
var pathTree = Tree{
|
||||
Files: nil,
|
||||
"manual": nil,
|
||||
"config": Leaf("path"),
|
||||
"completion": Leaf(Shells...),
|
||||
}
|
||||
|
||||
func TestScriptsWithFiles(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"bash": "compgen -f",
|
||||
"zsh": "_files",
|
||||
"fish": "__fish_complete_path",
|
||||
"powershell": "CompleteFilename",
|
||||
}
|
||||
for _, shell := range Shells {
|
||||
s, err := Script("tool", shell, pathTree)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(s, want[shell]) {
|
||||
t.Errorf("%s script lacks path completion %q", shell, want[shell])
|
||||
}
|
||||
if strings.Contains(s, Files) {
|
||||
t.Errorf("%s script offers the marker %q as a word", shell, Files)
|
||||
}
|
||||
// Without the marker no level completes paths.
|
||||
s, _ = Script("tool", shell, tree)
|
||||
if strings.Contains(s, want[shell]) {
|
||||
t.Errorf("%s script completes paths without Files", shell)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBashCompletesPaths runs the generated bash function in a directory
|
||||
// with a file whose name has a space, when bash is there.
|
||||
func TestBashCompletesPaths(t *testing.T) {
|
||||
if _, err := exec.LookPath("bash"); err != nil {
|
||||
t.Skip("no bash")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
for _, name := range []string{"my notes.txt", "manuscript"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s, _ := Script("tool", "bash", pathTree)
|
||||
for cword, want := range map[string]string{
|
||||
"m": "manual|manuscript|my notes.txt", // command names and paths
|
||||
"config p": "path", // a level without Files: no paths
|
||||
} {
|
||||
words := strings.Fields("tool " + cword)
|
||||
script := s + "\nCOMP_WORDS=(" + strings.Join(words, " ") + "); COMP_CWORD=" +
|
||||
strconv.Itoa(len(words)-1) + "; _tool_complete; printf '%s\\n' \"${COMPREPLY[@]}\" | sort | paste -sd '|' -"
|
||||
cmd := exec.Command("bash", "-c", script)
|
||||
cmd.Dir = dir
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil || strings.TrimSpace(string(out)) != want {
|
||||
t.Errorf("bash completion of %q: %v %q, want %q", cword, err, out, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,3 +179,9 @@ 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 }
|
||||
+1
-13
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+54
-9
@@ -2,10 +2,11 @@
|
||||
// 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 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
|
||||
@@ -33,6 +34,11 @@
|
||||
// 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.
|
||||
@@ -79,8 +85,8 @@ type Spec struct {
|
||||
Filename string
|
||||
|
||||
// Optional says the program also runs without a configuration file
|
||||
// (on built-in defaults): "validate" and "upgrade" then report that
|
||||
// no file exists instead of failing.
|
||||
// (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
|
||||
@@ -110,9 +116,23 @@ type Spec struct {
|
||||
// options (see Missing). Optional.
|
||||
Schema any
|
||||
|
||||
// SecretKeys are the program's own secret options, as dotted keys
|
||||
// ("database.url", "oidc.client_secret"): "config show" redacts them
|
||||
// like the keys it always treats as secret (a last segment secrets,
|
||||
// secret, token or password). A key also covers everything below it.
|
||||
// Fields of list entries are named without the index
|
||||
// ("admins.password" for every entry of the list admins).
|
||||
SecretKeys []string
|
||||
|
||||
// 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 {
|
||||
@@ -131,7 +151,7 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "create", "validate", "upgrade", "path":
|
||||
case "create", "validate", "upgrade", "path", "show":
|
||||
if s.None {
|
||||
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
||||
return ExitOK
|
||||
@@ -141,11 +161,25 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
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
|
||||
@@ -158,19 +192,26 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
|
||||
// Subcommands are the config subcommands, for a program's completion
|
||||
// tree and help text.
|
||||
var Subcommands = []string{"create", "validate", "upgrade", "path"}
|
||||
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>]
|
||||
create [--minimal|--full] [--force] [--output <file>|-]
|
||||
write a commented starter configuration (minimal by default)
|
||||
validate check the configuration file the program would use
|
||||
upgrade [--write]
|
||||
show the options of "create --full" the file does not mention
|
||||
yet, as commented blocks; --write adds them to the file
|
||||
path list the locations searched for %[2]s, highest priority first
|
||||
`, s.Name, s.filename())
|
||||
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
|
||||
@@ -301,7 +342,7 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
|
||||
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)")
|
||||
output := fs.String("output", "", "file to write, - for stdout (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
|
||||
}
|
||||
@@ -315,6 +356,10 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
|
||||
}
|
||||
|
||||
path := *output
|
||||
if path == "-" { // the template on stdout, nothing written
|
||||
io.WriteString(stdout, content)
|
||||
return ExitOK
|
||||
}
|
||||
if path == "" {
|
||||
var err error
|
||||
if path, err = s.defaultCreatePath(explicit); err != nil {
|
||||
|
||||
@@ -190,6 +190,27 @@ func TestCreateExplicitAndOutput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// --output - prints the template and writes no file (not one named "-").
|
||||
func TestCreateOutputStdout(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
work := filepath.Join(root, "work")
|
||||
if err := os.MkdirAll(work, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(work)
|
||||
code, out, errOut := run(t, s, "", "create", "--full", "--output", "-")
|
||||
if code != ExitOK || out != fullTemplate || errOut != "" {
|
||||
t.Fatalf("create --output -: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(work, "-")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("create --output - wrote a file named \"-\": %v", err)
|
||||
}
|
||||
if code, out, _ := run(t, s, "", "create", "--output=-"); code != ExitOK || out != minimalTemplate {
|
||||
t.Errorf("create --output=-: exit %d, stdout %q", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
@@ -427,3 +448,74 @@ func TestFilenameAndFind(t *testing.T) {
|
||||
t.Fatalf("Find: %v, %v", l.Path, err)
|
||||
}
|
||||
}
|
||||
|
||||
type secretRef struct {
|
||||
Env string `yaml:"env,omitempty"`
|
||||
File string `yaml:"file,omitempty"`
|
||||
Value string `yaml:"value,omitempty"`
|
||||
}
|
||||
|
||||
func (secretRef) ConfigOneOf() {}
|
||||
|
||||
type oneOfSchema struct {
|
||||
Auth struct {
|
||||
Type string `yaml:"type"`
|
||||
Token secretRef `yaml:"token"`
|
||||
Email *secretRef `yaml:"email"`
|
||||
} `yaml:"auth"`
|
||||
}
|
||||
|
||||
const oneOfTemplate = `auth:
|
||||
type: bearer
|
||||
# exactly one of env, file or value
|
||||
token:
|
||||
env: TOKEN
|
||||
email:
|
||||
file: /run/secrets/email
|
||||
`
|
||||
|
||||
func TestUndocumentedKeysOneOf(t *testing.T) {
|
||||
got, err := UndocumentedKeys(oneOfTemplate, oneOfSchema{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Errorf("UndocumentedKeys(one alternative set) = %v, want none", got)
|
||||
}
|
||||
// No alternative in the template: every one is undocumented.
|
||||
got, _ = UndocumentedKeys("auth:\n type: bearer\n token: {}\n email:\n env: E\n", oneOfSchema{})
|
||||
if want := "auth.token.env auth.token.file auth.token.value"; strings.Join(got, " ") != want {
|
||||
t.Errorf("UndocumentedKeys(empty token) = %v, want %s", got, want)
|
||||
}
|
||||
// A struct without the marker still needs every field.
|
||||
type plain struct {
|
||||
Token struct {
|
||||
Env string `yaml:"env"`
|
||||
File string `yaml:"file"`
|
||||
} `yaml:"token"`
|
||||
}
|
||||
got, _ = UndocumentedKeys("token:\n env: X\n", plain{})
|
||||
if want := "token.file"; strings.Join(got, " ") != want {
|
||||
t.Errorf("UndocumentedKeys(plain) = %v, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingOneOfOffersNoOtherAlternative(t *testing.T) {
|
||||
file := "auth:\n type: bearer\n token:\n file: /run/secrets/token\n email:\n value: me@example.org\n"
|
||||
got, err := Missing([]byte(file), []byte(oneOfTemplate), oneOfSchema{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Errorf("Missing() = %v, want nothing (each secret has its alternative)", got)
|
||||
}
|
||||
// Without the schema the template's alternative is offered as before.
|
||||
got, _ = Missing([]byte(file), []byte(oneOfTemplate), nil)
|
||||
var keys []string
|
||||
for _, a := range got {
|
||||
keys = append(keys, a.Key)
|
||||
}
|
||||
if want := "auth.token.env auth.email.file"; strings.Join(keys, " ") != want {
|
||||
t.Errorf("Missing(no schema) = %v, want %s", keys, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
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
|
||||
// SecretKeys are redacted by Values and Show in addition to the
|
||||
// default secret names (Spec.SecretKeys).
|
||||
SecretKeys []string
|
||||
}
|
||||
|
||||
// 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()
|
||||
e.SecretKeys = s.SecretKeys
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValuesProgramSecrets: Spec.SecretKeys (on Effective) redacts a
|
||||
// program's own secret options and everything below one; other keys and
|
||||
// a key that only shares a prefix stay.
|
||||
func TestValuesProgramSecrets(t *testing.T) {
|
||||
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
|
||||
"database": map[string]any{"url": "postgres://app:pw@db/x", "owner_url": "file:/run/o", "urls": "kept"},
|
||||
"smtp": map[string]any{"url": "smtps://u:pw@mail", "from": "a@b"},
|
||||
"vault": map[string]any{"inner": map[string]any{"key": "deep"}},
|
||||
}})
|
||||
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"database.url", "database.owner_url", "smtp.url", "vault"}}
|
||||
got := map[string]any{}
|
||||
for _, v := range e.Values(nil, false) {
|
||||
got[v.Key] = v.Value
|
||||
}
|
||||
want := map[string]any{
|
||||
"database.url": "<redacted>", "database.owner_url": "file:/run/o", "database.urls": "kept",
|
||||
"smtp.url": "<redacted>", "smtp.from": "a@b", "vault.inner.key": "<redacted>",
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Values = %v, want %v", got, want)
|
||||
}
|
||||
for _, v := range e.Values(nil, true) {
|
||||
if v.Key == "smtp.url" && v.Value != "smtps://u:pw@mail" {
|
||||
t.Errorf("show-secrets: %v", v.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Through "config show": the Spec's keys reach the output.
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
s.SecretKeys = []string{"log-level"}
|
||||
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-level: debug\n")
|
||||
if code, out, errOut := run(t, s, "", "show"); code != ExitOK || strings.Contains(out, `"debug"`) || !strings.Contains(out, `log-level: "<redacted>"`) {
|
||||
t.Errorf("show: exit %d\n%s%s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// TestValuesRedactionInLists: a list leaf is printed as one value, so
|
||||
// the secret fields of its entries are redacted inside it -- by default
|
||||
// name and by a Spec key without the index -- and the rest stays.
|
||||
func TestValuesRedactionInLists(t *testing.T) {
|
||||
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
|
||||
"admins": []any{
|
||||
map[string]any{"username": "admin", "password": "changeme"},
|
||||
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
|
||||
},
|
||||
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "t0k"}, "url": "pg://u:pw@h"}},
|
||||
"plain": []any{"x", "y"},
|
||||
}})
|
||||
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"ids.url"}}
|
||||
got := map[string]any{}
|
||||
for _, v := range e.Values(nil, false) {
|
||||
got[v.Key] = v.Value
|
||||
}
|
||||
want := map[string]any{
|
||||
"admins": []any{
|
||||
map[string]any{"username": "admin", "password": "<redacted>"},
|
||||
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
|
||||
},
|
||||
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "<redacted>"}, "url": "<redacted>"}},
|
||||
"plain": []any{"x", "y"},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Values = %v\nwant %v", got, want)
|
||||
}
|
||||
if merged["admins"].([]any)[0].(map[string]any)["password"] != "changeme" {
|
||||
t.Error("the merged configuration was changed")
|
||||
}
|
||||
for _, v := range e.Values(nil, true) {
|
||||
if v.Key == "admins" && !strings.Contains(renderValue(v.Value), "changeme") {
|
||||
t.Errorf("show-secrets: %v", v.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Through "config show" from a file, YAML and JSON.
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"),
|
||||
minimalTemplate+"users:\n - name: a\n password: hunter2\n")
|
||||
for _, args := range [][]string{{"show"}, {"show", "--json"}} {
|
||||
code, out, errOut := run(t, s, "", args...)
|
||||
if code != ExitOK || strings.Contains(out, "hunter2") || !strings.Contains(out, "<redacted>") || !strings.Contains(out, `"name"`) {
|
||||
t.Errorf("%v: exit %d\n%s%s", args, code, out, errOut)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
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, and e.SecretKeys) are replaced by "<redacted>" unless
|
||||
// showSecrets; a reference that only says where a secret is (env:,
|
||||
// file:, secret://) is shown. A leaf that is a list is printed as one
|
||||
// value, so the same rule is applied inside it: a field of a list entry
|
||||
// is secret by its name or by its key without the index ("admins.password"
|
||||
// for the field password of every entry of the list admins).
|
||||
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 {
|
||||
if e.isSecret(key) {
|
||||
v = redact(v)
|
||||
} else {
|
||||
v = e.redactWithin(key, 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:]] }
|
||||
|
||||
// isSecret: a default secret name, or one of e.SecretKeys or a key below
|
||||
// one.
|
||||
func (e *Effective) isSecret(key string) bool {
|
||||
if isSecretKey(key) {
|
||||
return true
|
||||
}
|
||||
for _, k := range e.SecretKeys {
|
||||
if key == k || strings.HasPrefix(key, k+".") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// redactWithin redacts the secret fields of the maps inside a list (or
|
||||
// a map) leaf at key, by the same rule as isSecret. A list entry adds no
|
||||
// segment to the key. v is copied, never changed.
|
||||
func (e *Effective) redactWithin(key string, v any) any {
|
||||
switch x := v.(type) {
|
||||
case []any:
|
||||
out := make([]any, len(x))
|
||||
for i, el := range x {
|
||||
out[i] = e.redactWithin(key, el)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
out := make(map[string]any, len(x))
|
||||
for k, el := range x {
|
||||
if sub := key + "." + k; e.isSecret(sub) {
|
||||
out[k] = redact(el)
|
||||
} else {
|
||||
out[k] = e.redactWithin(sub, el)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
+21
-1
@@ -19,9 +19,17 @@ type UnknownKey struct {
|
||||
// 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 { return fmt.Sprintf("%s (line %d)", k.Key, k.Line) }
|
||||
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
|
||||
@@ -43,6 +51,18 @@ func UnknownKeys(raw []byte, schema any) ([]UnknownKey, error) {
|
||||
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)
|
||||
|
||||
@@ -74,12 +74,12 @@ Ignored: x
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []UnknownKey{
|
||||
{"log-levle", 2},
|
||||
{"listen[0].tsl", 5},
|
||||
{"storage.mailstore.rot", 9},
|
||||
{"backends.inbound.extra", 11},
|
||||
{"throttle.enabeld", 15},
|
||||
{"Ignored", 18},
|
||||
{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)
|
||||
@@ -109,3 +109,18 @@ func TestWarnUnknownAndCheck(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
+35
-4
@@ -82,6 +82,9 @@ func docMapping(doc *yaml.Node) *yaml.Node {
|
||||
// of file).
|
||||
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
||||
var out []Addition
|
||||
// A file that chose one alternative of a OneOf struct gets none of
|
||||
// the template's others offered.
|
||||
chosen := isOneOf(t) && len(fmap.Content) > 0
|
||||
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)
|
||||
@@ -105,7 +108,7 @@ func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent,
|
||||
}
|
||||
continue
|
||||
}
|
||||
if mentioned(lines, from, to, childIndent, tkey.Value) {
|
||||
if chosen || mentioned(lines, from, to, childIndent, tkey.Value) {
|
||||
continue
|
||||
}
|
||||
out = append(out, Addition{
|
||||
@@ -226,12 +229,36 @@ func Apply(raw []byte, adds []Addition) []byte {
|
||||
return []byte(out)
|
||||
}
|
||||
|
||||
// OneOf marks a configuration struct whose fields are alternatives, of
|
||||
// which a file sets exactly one -- a secret taken from env, file or
|
||||
// value, say. The method itself does nothing; implementing it is the
|
||||
// marker:
|
||||
//
|
||||
// func (SecretRef) ConfigOneOf() {}
|
||||
//
|
||||
// UndocumentedKeys then accepts a template that sets one alternative
|
||||
// (and explains the others in comments), and Missing offers none of the
|
||||
// others to a file that already chose one.
|
||||
type OneOf interface{ ConfigOneOf() }
|
||||
|
||||
var oneOfType = reflect.TypeOf((*OneOf)(nil)).Elem()
|
||||
|
||||
// isOneOf reports whether t (or a pointer to it) implements OneOf.
|
||||
func isOneOf(t reflect.Type) bool {
|
||||
if t == nil {
|
||||
return false
|
||||
}
|
||||
t = deref(t)
|
||||
return t.Implements(oneOfType) || reflect.PointerTo(t).Implements(oneOfType)
|
||||
}
|
||||
|
||||
// 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.
|
||||
// item. A struct implementing OneOf counts as documented when the
|
||||
// template sets any one of its fields. 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 {
|
||||
@@ -251,6 +278,8 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
||||
if t.Kind() != reflect.Struct {
|
||||
return
|
||||
}
|
||||
// One alternative set: the others are not missing.
|
||||
chosen := isOneOf(t) && len(m.Content) > 0
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||
@@ -268,7 +297,9 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
||||
sub := append(append([]string(nil), path...), name)
|
||||
_, val := lookup(m, name)
|
||||
if val == nil {
|
||||
if !chosen {
|
||||
*out = append(*out, strings.Join(sub, "."))
|
||||
}
|
||||
continue
|
||||
}
|
||||
ft := deref(f.Type)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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, " + ")
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
+31
-3
@@ -36,11 +36,16 @@ type Path struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Check is one named check.
|
||||
// Check is one named check. Area (a group such as "config" or
|
||||
// "services") and Hint (what to do about a failed check) are optional
|
||||
// and omitted from the JSON form when empty, so a report without them
|
||||
// looks exactly as before they existed.
|
||||
type Check struct {
|
||||
Area string `json:"area,omitempty"`
|
||||
Name string `json:"name"`
|
||||
OK bool `json:"ok"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
// Report is "<program> doctor --json"'s output.
|
||||
@@ -110,6 +115,12 @@ func (r *Report) Check(name string, ok bool, note string) {
|
||||
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
|
||||
}
|
||||
|
||||
// Add records a check with all its fields, for a program that groups its
|
||||
// checks into areas or gives hints.
|
||||
func (r *Report) Add(c Check) {
|
||||
r.Checks = append(r.Checks, c)
|
||||
}
|
||||
|
||||
// Problems counts failed checks.
|
||||
func (r Report) Problems() int {
|
||||
n := 0
|
||||
@@ -148,9 +159,26 @@ func (r Report) Write(w io.Writer, asJSON bool) error {
|
||||
}
|
||||
fmt.Fprintln(tw)
|
||||
}
|
||||
fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n")
|
||||
// The AREA and HINT columns only appear when some check uses them,
|
||||
// so the table of a program without them is unchanged.
|
||||
withArea, withHint := false, false
|
||||
for _, c := range r.Checks {
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note)
|
||||
withArea = withArea || c.Area != ""
|
||||
withHint = withHint || c.Hint != ""
|
||||
}
|
||||
row := func(area, name, ok, note, hint string) {
|
||||
cols := []string{name, ok, note}
|
||||
if withArea {
|
||||
cols = append([]string{area}, cols...)
|
||||
}
|
||||
if withHint {
|
||||
cols = append(cols, hint)
|
||||
}
|
||||
fmt.Fprintln(tw, strings.Join(cols, "\t"))
|
||||
}
|
||||
row("AREA", "CHECK", "OK", "NOTE", "HINT")
|
||||
for _, c := range r.Checks {
|
||||
row(c.Area, c.Name, yesNo(c.OK), c.Note, c.Hint)
|
||||
}
|
||||
return tw.Flush()
|
||||
}
|
||||
|
||||
@@ -49,3 +49,37 @@ func TestAddPaths(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAreaAndHint(t *testing.T) {
|
||||
// Without area/hint neither the JSON nor the table mentions them.
|
||||
plain := Report{Program: "tool"}
|
||||
plain.Check("config valid", true, "")
|
||||
var out strings.Builder
|
||||
if err := plain.Write(&out, true); err != nil || strings.Contains(out.String(), "area") || strings.Contains(out.String(), "hint") {
|
||||
t.Fatalf("plain json: %v %s", err, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
if err := plain.Write(&out, false); err != nil || strings.Contains(out.String(), "AREA") || strings.Contains(out.String(), "HINT") {
|
||||
t.Fatalf("plain table: %v %s", err, out.String())
|
||||
}
|
||||
|
||||
r := Report{Program: "tool"}
|
||||
r.Add(Check{Area: "config", Name: "config loads", OK: false, Note: "line 3", Hint: "run tool config validate"})
|
||||
r.Check("other", true, "")
|
||||
out.Reset()
|
||||
if err := r.Write(&out, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got Report
|
||||
if err := json.Unmarshal([]byte(out.String()), &got); err != nil || got.Checks[0].Area != "config" || got.Checks[0].Hint != "run tool config validate" || got.Checks[1].Area != "" {
|
||||
t.Fatalf("json: %v %+v", err, got)
|
||||
}
|
||||
out.Reset()
|
||||
if err := r.Write(&out, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := strings.Split(out.String(), "\n")
|
||||
if !strings.HasPrefix(lines[0], "AREA") || !strings.Contains(lines[0], "HINT") || !strings.HasPrefix(lines[1], "config") || !strings.Contains(lines[1], "run tool config validate") {
|
||||
t.Fatalf("table:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
# 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, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`, `ShowFileDialog` (UI thread) / `ChooseFile` (any goroutine, waits): a native open or save dialog (`FileDialog{Save, Title, Directory, Name, Extensions}`; macOS NSOpenPanel/NSSavePanel as a sheet, Windows GetOpenFileNameW/GetSaveFileNameW), "" when cancelled -- it only returns a path, nothing is read or written. |
|
||||
|
||||
## 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).
|
||||
|
||||
`FrameFile` (since `gui/v0.2.0`) keeps the window's position, size and
|
||||
maximized state across starts: a small JSON file the program places in
|
||||
its `core/paths` state directory. It is read at `New` -- a frame that is
|
||||
on no connected screen any more is ignored and the window opens
|
||||
centered -- and written shortly after every move or resize and at
|
||||
`Destroy`. The coordinates are the platform's own (macOS: points from
|
||||
the bottom left; Windows: `WINDOWPLACEMENT`'s normal position).
|
||||
|
||||
## 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.
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
});
|
||||
})();
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 & b\">x < y …</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("/assets/images/b.png")">`
|
||||
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
@@ -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
@@ -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=
|
||||
@@ -0,0 +1,23 @@
|
||||
#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,
|
||||
int hasFrame, int fx, int fy, int fw, int fh, int zoomed);
|
||||
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);
|
||||
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,368 @@
|
||||
//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>
|
||||
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.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);
|
||||
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
|
||||
extern void ytGoFileDone(uintptr_t h, const char *path);
|
||||
|
||||
// YTWebView takes the first mouse click in an inactive window: without
|
||||
// it the click only activates the window, so a page (a dialog shown at
|
||||
// start) looks dead until clicked twice.
|
||||
@interface YTWebView : WKWebView
|
||||
@end
|
||||
|
||||
@implementation YTWebView
|
||||
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
||||
@end
|
||||
|
||||
@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;
|
||||
@property (assign) NSRect normalFrame; // the last frame while not zoomed
|
||||
@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);
|
||||
}
|
||||
|
||||
// The frame is reported after every move and resize; while zoomed, the
|
||||
// normal frame underneath is kept, so un-zooming returns to it.
|
||||
- (void)reportFrame {
|
||||
if (self.closed || !self.window) return;
|
||||
BOOL zoomed = self.window.isZoomed;
|
||||
if (!zoomed) self.normalFrame = self.window.frame;
|
||||
NSRect f = self.normalFrame;
|
||||
if (f.size.width <= 0) return;
|
||||
ytGoFrame(self.goHandle, (int)f.origin.x, (int)f.origin.y, (int)f.size.width, (int)f.size.height, zoomed ? 1 : 0);
|
||||
}
|
||||
- (void)windowDidMove:(NSNotification *)n { [self reportFrame]; }
|
||||
- (void)windowDidResize:(NSNotification *)n { [self reportFrame]; }
|
||||
|
||||
- (void)windowWillClose:(NSNotification *)n {
|
||||
[self reportFrame];
|
||||
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];
|
||||
}
|
||||
|
||||
// onScreen: at least a 120 x 60 point piece of the frame (with its title
|
||||
// bar) is on a connected screen -- a frame saved on a display that is
|
||||
// gone is not restored off screen.
|
||||
static BOOL onScreen(NSRect f) {
|
||||
for (NSScreen *s in [NSScreen screens]) {
|
||||
NSRect i = NSIntersectionRect(f, s.visibleFrame);
|
||||
if (i.size.width >= 120 && i.size.height >= 60) return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
|
||||
int hasFrame, int fx, int fy, int fw, int fh, int zoomed) {
|
||||
@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 = [[YTWebView 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;
|
||||
NSRect saved = NSMakeRect(fx, fy, fw, fh);
|
||||
BOOL restore = hasFrame && onScreen(saved);
|
||||
if (restore) {
|
||||
[host.window setFrame:saved display:NO];
|
||||
} else {
|
||||
[host.window center];
|
||||
}
|
||||
host.normalFrame = host.window.frame;
|
||||
host.window.delegate = host;
|
||||
[host.window makeKeyAndOrderFront:nil];
|
||||
if (restore && zoomed && !host.window.isZoomed) [host.window zoom: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 reportFrame]; // a window ended by Terminate, not closed by the user
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// --- file dialogs ------------------------------------------------------------
|
||||
|
||||
// yt_file_dialog shows an open (save = 0) or save panel as a sheet on the
|
||||
// window. dir: the folder to start in, name: a save panel's suggested file
|
||||
// name, types: allowed file extensions, comma-separated ("" = any). The
|
||||
// chosen path, or NULL when cancelled, goes to ytGoFileDone.
|
||||
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
uintptr_t gh = host.goHandle;
|
||||
NSSavePanel *panel;
|
||||
if (save) {
|
||||
panel = [NSSavePanel savePanel];
|
||||
if (name && name[0]) panel.nameFieldStringValue = str(name);
|
||||
} else {
|
||||
NSOpenPanel *open = [NSOpenPanel openPanel];
|
||||
open.canChooseFiles = YES;
|
||||
open.canChooseDirectories = NO;
|
||||
open.allowsMultipleSelection = NO;
|
||||
open.resolvesAliases = YES;
|
||||
panel = open;
|
||||
}
|
||||
if (title && title[0]) { panel.title = str(title); panel.message = str(title); }
|
||||
if (dir && dir[0]) panel.directoryURL = [NSURL fileURLWithPath:str(dir) isDirectory:YES];
|
||||
if (types && types[0]) {
|
||||
NSMutableArray<UTType *> *uts = [NSMutableArray array];
|
||||
for (NSString *ext in [str(types) componentsSeparatedByString:@","]) {
|
||||
UTType *t = [UTType typeWithFilenameExtension:ext];
|
||||
if (t) [uts addObject:t];
|
||||
}
|
||||
if (uts.count) panel.allowedContentTypes = uts;
|
||||
}
|
||||
[panel beginSheetModalForWindow:host.window completionHandler:^(NSModalResponse r) {
|
||||
if (r != NSModalResponseOK || !panel.URL) { ytGoFileDone(gh, NULL); return; }
|
||||
ytGoFileDone(gh, panel.URL.path.fileSystemRepresentation);
|
||||
}];
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//go:build windows
|
||||
|
||||
package window
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var (
|
||||
comdlg32 = windows.NewLazySystemDLL("comdlg32.dll")
|
||||
pGetOpenFile = comdlg32.NewProc("GetOpenFileNameW")
|
||||
pGetSaveFile = comdlg32.NewProc("GetSaveFileNameW")
|
||||
pCommDlgExtErr = comdlg32.NewProc("CommDlgExtendedError")
|
||||
errNoFileDialog = fmt.Errorf("window: file dialog failed")
|
||||
)
|
||||
|
||||
// openFileName is OPENFILENAMEW (commdlg.h).
|
||||
type openFileName struct {
|
||||
lStructSize uint32
|
||||
hwndOwner uintptr
|
||||
hInstance uintptr
|
||||
lpstrFilter *uint16
|
||||
lpstrCustomFilter *uint16
|
||||
nMaxCustFilter uint32
|
||||
nFilterIndex uint32
|
||||
lpstrFile *uint16
|
||||
nMaxFile uint32
|
||||
lpstrFileTitle *uint16
|
||||
nMaxFileTitle uint32
|
||||
lpstrInitialDir *uint16
|
||||
lpstrTitle *uint16
|
||||
flags uint32
|
||||
nFileOffset uint16
|
||||
nFileExtension uint16
|
||||
lpstrDefExt *uint16
|
||||
lCustData uintptr
|
||||
lpfnHook uintptr
|
||||
lpTemplateName *uint16
|
||||
pvReserved uintptr
|
||||
dwReserved uint32
|
||||
flagsEx uint32
|
||||
}
|
||||
|
||||
const (
|
||||
ofnOverwritePrompt = 0x00000002
|
||||
ofnNoChangeDir = 0x00000008
|
||||
ofnPathMustExist = 0x00000800
|
||||
ofnFileMustExist = 0x00001000
|
||||
ofnExplorer = 0x00080000
|
||||
)
|
||||
|
||||
// fileFilter is the dialog's filter list: the allowed extensions, then
|
||||
// all files; pairs of display text and pattern, each NUL-terminated,
|
||||
// the list ending with an extra NUL.
|
||||
func fileFilter(exts []string) []uint16 {
|
||||
var b strings.Builder
|
||||
if len(exts) > 0 {
|
||||
pats := make([]string, len(exts))
|
||||
for i, e := range exts {
|
||||
pats[i] = "*." + strings.TrimPrefix(e, ".")
|
||||
}
|
||||
p := strings.Join(pats, ";")
|
||||
b.WriteString(p + " (" + p + ")\x00" + p + "\x00")
|
||||
}
|
||||
b.WriteString("All files (*.*)\x00*.*\x00\x00")
|
||||
return windows.StringToUTF16(b.String())
|
||||
}
|
||||
|
||||
// FileDialog shows the common open or save dialog, modal to the window
|
||||
// (it runs its own message loop on the UI thread); done runs right after.
|
||||
func (b *winBackend) FileDialog(d FileDialog, done func(string, error)) {
|
||||
buf := make([]uint16, 32768)
|
||||
if d.Save && d.Name != "" {
|
||||
copy(buf[:len(buf)-1], windows.StringToUTF16(d.Name))
|
||||
}
|
||||
filter := fileFilter(d.Extensions)
|
||||
ofn := openFileName{
|
||||
hwndOwner: b.hwnd,
|
||||
lpstrFilter: &filter[0],
|
||||
nFilterIndex: 1,
|
||||
lpstrFile: &buf[0],
|
||||
nMaxFile: uint32(len(buf)),
|
||||
flags: ofnExplorer | ofnNoChangeDir | ofnPathMustExist,
|
||||
}
|
||||
ofn.lStructSize = uint32(unsafe.Sizeof(ofn))
|
||||
if d.Title != "" {
|
||||
ofn.lpstrTitle, _ = windows.UTF16PtrFromString(d.Title)
|
||||
}
|
||||
if d.Directory != "" {
|
||||
ofn.lpstrInitialDir, _ = windows.UTF16PtrFromString(d.Directory)
|
||||
}
|
||||
proc := pGetOpenFile
|
||||
if d.Save {
|
||||
proc = pGetSaveFile
|
||||
ofn.flags |= ofnOverwritePrompt
|
||||
if len(d.Extensions) > 0 {
|
||||
ofn.lpstrDefExt, _ = windows.UTF16PtrFromString(strings.TrimPrefix(d.Extensions[0], "."))
|
||||
}
|
||||
} else {
|
||||
ofn.flags |= ofnFileMustExist
|
||||
}
|
||||
if r, _, _ := proc.Call(uintptr(unsafe.Pointer(&ofn))); r == 0 {
|
||||
if code, _, _ := pCommDlgExtErr.Call(); code != 0 {
|
||||
done("", fmt.Errorf("%w: CommDlgExtendedError 0x%x", errNoFileDialog, code))
|
||||
return
|
||||
}
|
||||
done("", nil) // cancelled
|
||||
return
|
||||
}
|
||||
done(windows.UTF16ToString(buf), nil)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build windows
|
||||
|
||||
package window
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFileFilter(t *testing.T) {
|
||||
raw := fileFilter([]string{"pdf", ".txt"})
|
||||
s := string(utf16Runes(raw))
|
||||
want := "*.pdf;*.txt (*.pdf;*.txt)\x00*.pdf;*.txt\x00All files (*.*)\x00*.*\x00\x00\x00"
|
||||
if s != want {
|
||||
t.Errorf("filter = %q, want %q", s, want)
|
||||
}
|
||||
}
|
||||
|
||||
func utf16Runes(u []uint16) []rune {
|
||||
r := make([]rune, len(u))
|
||||
for i, c := range u {
|
||||
r[i] = rune(c)
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Frame is a window's position and size in the platform's own screen
|
||||
// coordinates (macOS: points, origin bottom left; Windows: pixels of the
|
||||
// virtual screen, origin top left). It is only ever read back on the
|
||||
// platform that wrote it. Maximized (macOS: zoomed) keeps the normal
|
||||
// frame underneath, so un-maximizing returns to it.
|
||||
type Frame struct {
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Maximized bool `json:"maximized,omitempty"`
|
||||
}
|
||||
|
||||
// minFrame is the smallest frame restored; anything smaller is a broken
|
||||
// file, not a window someone made.
|
||||
const minFrame = 200
|
||||
|
||||
func (f Frame) usable() bool { return f.Width >= minFrame && f.Height >= minFrame }
|
||||
|
||||
// loadFrame reads a frame file written by frameSaver. A missing,
|
||||
// unreadable or implausible file is no frame: the window opens with its
|
||||
// default size, centered.
|
||||
func loadFrame(path string) (Frame, bool) {
|
||||
if path == "" {
|
||||
return Frame{}, false
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Frame{}, false
|
||||
}
|
||||
var f Frame
|
||||
if json.Unmarshal(data, &f) != nil || !f.usable() {
|
||||
return Frame{}, false
|
||||
}
|
||||
return f, true
|
||||
}
|
||||
|
||||
// frameSaver writes the window's frame to its file, a moment after the
|
||||
// last move or resize (a drag reports many), and once more at Destroy.
|
||||
type frameSaver struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
last Frame
|
||||
dirty bool
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
const frameSaveDelay = 400 * time.Millisecond
|
||||
|
||||
func (s *frameSaver) changed(f Frame) {
|
||||
if s == nil || !f.usable() {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if f == s.last && !s.dirty {
|
||||
return
|
||||
}
|
||||
s.last, s.dirty = f, true
|
||||
if s.timer == nil {
|
||||
s.timer = time.AfterFunc(frameSaveDelay, s.flush)
|
||||
} else {
|
||||
s.timer.Reset(frameSaveDelay)
|
||||
}
|
||||
}
|
||||
|
||||
// flush writes a pending frame (temp file + rename, so a crash never
|
||||
// leaves half a file). Errors are not fatal: the next start just opens
|
||||
// with the default frame.
|
||||
func (s *frameSaver) flush() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.timer != nil {
|
||||
s.timer.Stop()
|
||||
}
|
||||
f, dirty := s.last, s.dirty
|
||||
s.dirty = false
|
||||
s.mu.Unlock()
|
||||
if !dirty {
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(f)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
|
||||
debugf("window: frame file: %v", err)
|
||||
return
|
||||
}
|
||||
tmp := s.path + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
|
||||
debugf("window: frame file: %v", err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, s.path); err != nil {
|
||||
debugf("window: frame file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func debugf(format string, args ...any) {
|
||||
if Debugf != nil {
|
||||
Debugf(format, args...)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package window
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFrameFileRoundTrip(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state", "window.json")
|
||||
if _, ok := loadFrame(path); ok {
|
||||
t.Fatal("a missing file is a frame")
|
||||
}
|
||||
s := &frameSaver{path: path}
|
||||
s.changed(Frame{X: 10, Y: 20, Width: 300, Height: 200})
|
||||
s.changed(Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) // the last one wins
|
||||
s.flush()
|
||||
f, ok := loadFrame(path)
|
||||
if !ok || f != (Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) {
|
||||
t.Fatalf("loaded %+v, %v", f, ok)
|
||||
}
|
||||
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
|
||||
t.Errorf("temp file left behind: %v", err)
|
||||
}
|
||||
|
||||
// Too small or broken: no frame, the window opens with its default.
|
||||
for _, data := range []string{`{"x":0,"y":0,"width":50,"height":40}`, `not json`, ``} {
|
||||
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, ok := loadFrame(path); ok {
|
||||
t.Errorf("%q loaded as %+v", data, f)
|
||||
}
|
||||
}
|
||||
s.changed(Frame{Width: 10, Height: 10}) // ignored
|
||||
s.flush()
|
||||
if data, _ := os.ReadFile(path); string(data) != "" {
|
||||
t.Errorf("an unusable frame was written: %q", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// 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
|
||||
// FrameFile, if set, keeps the window's position and size across
|
||||
// starts: read at New (a frame that is no longer on any screen is
|
||||
// ignored), written a moment after every move or resize and at
|
||||
// Destroy. A small JSON file (Frame); the program picks the path,
|
||||
// e.g. in its state directory.
|
||||
FrameFile string
|
||||
|
||||
// Set by New for the backend.
|
||||
restore *Frame // the frame to open with, nil: default, centered
|
||||
onFrame func(Frame) // the backend reports a moved or resized window
|
||||
}
|
||||
|
||||
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 {
|
||||
frames *frameSaver
|
||||
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
|
||||
}
|
||||
var frames *frameSaver
|
||||
if opt.FrameFile != "" {
|
||||
frames = &frameSaver{path: opt.FrameFile}
|
||||
if f, ok := loadFrame(opt.FrameFile); ok {
|
||||
opt.restore = &f
|
||||
frames.last = f
|
||||
}
|
||||
opt.onFrame = frames.changed
|
||||
}
|
||||
b, name, base, err := newBackend(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Window{b: b, alive: true, name: name, base: base, frames: frames}, 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()
|
||||
w.frames.flush()
|
||||
}
|
||||
|
||||
// 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() }
|
||||
|
||||
// FileDialog describes a native open or save dialog.
|
||||
type FileDialog struct {
|
||||
Save bool // a save dialog; otherwise open one existing file
|
||||
Title string // the prompt; "" for the system's
|
||||
Directory string // the folder to start in; "" for the system's choice
|
||||
Name string // save: the suggested file name
|
||||
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
|
||||
}
|
||||
|
||||
// ErrDialogOpen: a file dialog of this window is already open.
|
||||
var ErrDialogOpen = errors.New("window: a file dialog is already open")
|
||||
|
||||
// fileDialoger is implemented by backends with native file dialogs.
|
||||
type fileDialoger interface {
|
||||
FileDialog(d FileDialog, done func(path string, err error))
|
||||
}
|
||||
|
||||
// ShowFileDialog shows a native open or save dialog for the window (UI
|
||||
// thread; one at a time). done runs on the UI thread with the chosen
|
||||
// path, or "" and a nil error when the user cancelled. A save dialog
|
||||
// has asked about replacing an existing file already; nothing is read
|
||||
// or written here -- that is the program's choice.
|
||||
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
|
||||
f, ok := w.b.(fileDialoger)
|
||||
if !ok {
|
||||
done("", errors.New("window: file dialogs not supported by "+w.name))
|
||||
return
|
||||
}
|
||||
f.FileDialog(d, done)
|
||||
}
|
||||
|
||||
// ChooseFile shows a file dialog from any goroutine and waits for the
|
||||
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
|
||||
// request was dropped) stops the wait, not the dialog.
|
||||
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
|
||||
type result struct {
|
||||
path string
|
||||
err error
|
||||
}
|
||||
ch := make(chan result, 1)
|
||||
w.mu.Lock()
|
||||
alive := w.alive
|
||||
w.mu.Unlock()
|
||||
if !alive {
|
||||
return "", errors.New("window: destroyed")
|
||||
}
|
||||
w.Dispatch(func() {
|
||||
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
|
||||
})
|
||||
select {
|
||||
case r := <-ch:
|
||||
return r.path, r.err
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
package window
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
||||
#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework UniformTypeIdentifiers
|
||||
#include <stdlib.h>
|
||||
#include "darwin.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"runtime/cgo"
|
||||
"strings"
|
||||
"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)
|
||||
fileDone func(path string, err 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
|
||||
}
|
||||
var has, zoomed C.int
|
||||
var f Frame
|
||||
if opt.restore != nil {
|
||||
has, f = 1, *opt.restore
|
||||
if f.Maximized {
|
||||
zoomed = 1
|
||||
}
|
||||
}
|
||||
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme,
|
||||
has, C.int(f.X), C.int(f.Y), C.int(f.Width), C.int(f.Height), zoomed)
|
||||
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 ytGoFrame
|
||||
func ytGoFrame(h C.uintptr_t, x, y, w, hgt, zoomed C.int) {
|
||||
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||
if b.opt.onFrame != nil {
|
||||
b.opt.onFrame(Frame{X: int(x), Y: int(y), Width: int(w), Height: int(hgt), Maximized: zoomed != 0})
|
||||
}
|
||||
}
|
||||
|
||||
//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) })
|
||||
}
|
||||
|
||||
// FileDialog shows a native open or save panel as a sheet on the window;
|
||||
// done runs on the UI thread.
|
||||
func (b *darwinBackend) FileDialog(d FileDialog, done func(string, error)) {
|
||||
b.mu.Lock()
|
||||
if b.fileDone != nil {
|
||||
b.mu.Unlock()
|
||||
done("", ErrDialogOpen)
|
||||
return
|
||||
}
|
||||
b.fileDone = done
|
||||
b.mu.Unlock()
|
||||
save := 0
|
||||
if d.Save {
|
||||
save = 1
|
||||
}
|
||||
title, dir, name, types := cstr(d.Title), cstr(d.Directory), cstr(d.Name), cstr(strings.Join(d.Extensions, ","))
|
||||
defer func() {
|
||||
for _, c := range []*C.char{title, dir, name, types} {
|
||||
C.free(unsafe.Pointer(c))
|
||||
}
|
||||
}()
|
||||
if !b.with(func(h unsafe.Pointer) { C.yt_file_dialog(h, C.int(save), title, dir, name, types) }) {
|
||||
b.mu.Lock()
|
||||
b.fileDone = nil
|
||||
b.mu.Unlock()
|
||||
done("", errUnavailable("file dialog: the window is gone"))
|
||||
}
|
||||
}
|
||||
|
||||
//export ytGoFileDone
|
||||
func ytGoFileDone(h C.uintptr_t, path *C.char) {
|
||||
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||
b.mu.Lock()
|
||||
done := b.fileDone
|
||||
b.fileDone = nil
|
||||
b.mu.Unlock()
|
||||
if done == nil {
|
||||
return
|
||||
}
|
||||
if path == nil {
|
||||
done("", nil)
|
||||
return
|
||||
}
|
||||
done(C.GoString(path), nil)
|
||||
}
|
||||
@@ -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) {}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,775 @@
|
||||
//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")
|
||||
pGetPlacement = user32.NewProc("GetWindowPlacement")
|
||||
pSetPlacement = user32.NewProc("SetWindowPlacement")
|
||||
pMonitorFromRect = user32.NewProc("MonitorFromRect")
|
||||
)
|
||||
|
||||
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
|
||||
|
||||
const (
|
||||
wmDestroy = 0x0002
|
||||
wmMove = 0x0003
|
||||
wmSize = 0x0005
|
||||
wmSetFocus = 0x0007
|
||||
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()
|
||||
if f := opt.restore; f == nil || !restorePlacement(hwnd, *f) {
|
||||
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()
|
||||
c.Focus() // the window got WM_SETFOCUS before the control existed
|
||||
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()
|
||||
}
|
||||
b.reportFrame()
|
||||
case wmMove, wmMoving:
|
||||
if b.chromium != nil {
|
||||
_ = b.chromium.NotifyParentWindowPositionChanged()
|
||||
}
|
||||
b.reportFrame()
|
||||
case wmSetFocus:
|
||||
// The keyboard focus belongs in the WebView2 control (its own
|
||||
// child window): without this a page gets no keys after the
|
||||
// start or after Alt-Tab until it is clicked.
|
||||
if b.chromium != nil {
|
||||
b.chromium.Focus()
|
||||
}
|
||||
return 0
|
||||
case wmApp:
|
||||
b.runQueue()
|
||||
return 0
|
||||
case wmClose:
|
||||
b.reportFrame()
|
||||
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
|
||||
}
|
||||
|
||||
// windowPlacement is WINDOWPLACEMENT. rcNormalPosition is the restored
|
||||
// (not maximized) frame in workspace coordinates; Get and Set use the
|
||||
// same ones, so a saved frame comes back where it was.
|
||||
type windowPlacement struct {
|
||||
length uint32
|
||||
flags uint32
|
||||
showCmd uint32
|
||||
ptMinPosition [2]int32
|
||||
ptMaxPosition [2]int32
|
||||
rcNormalPosition [4]int32 // left, top, right, bottom
|
||||
}
|
||||
|
||||
const (
|
||||
swShowNormal = 1
|
||||
swShowMinimized = 2
|
||||
swShowMaximized = 3
|
||||
wpfRestoreToMaximize = 0x0002
|
||||
)
|
||||
|
||||
// reportFrame hands the window's normal frame and maximized state to
|
||||
// Options.FrameFile's saver.
|
||||
func (b *winBackend) reportFrame() {
|
||||
if b.opt.onFrame == nil {
|
||||
return
|
||||
}
|
||||
var wp windowPlacement
|
||||
wp.length = uint32(unsafe.Sizeof(wp))
|
||||
if r, _, _ := pGetPlacement.Call(b.hwnd, uintptr(unsafe.Pointer(&wp))); r == 0 {
|
||||
return
|
||||
}
|
||||
rc := wp.rcNormalPosition
|
||||
maximized := wp.showCmd == swShowMaximized || (wp.showCmd == swShowMinimized && wp.flags&wpfRestoreToMaximize != 0)
|
||||
b.opt.onFrame(Frame{X: int(rc[0]), Y: int(rc[1]), Width: int(rc[2] - rc[0]), Height: int(rc[3] - rc[1]), Maximized: maximized})
|
||||
}
|
||||
|
||||
// restorePlacement shows the window with a saved frame, when that frame
|
||||
// is still on a monitor (MONITOR_DEFAULTTONULL); false: show it as new.
|
||||
func restorePlacement(hwnd uintptr, f Frame) bool {
|
||||
rc := [4]int32{int32(f.X), int32(f.Y), int32(f.X + f.Width), int32(f.Y + f.Height)}
|
||||
if m, _, _ := pMonitorFromRect.Call(uintptr(unsafe.Pointer(&rc)), 0); m == 0 {
|
||||
return false
|
||||
}
|
||||
wp := windowPlacement{showCmd: swShowNormal, rcNormalPosition: rc}
|
||||
if f.Maximized {
|
||||
wp.showCmd = swShowMaximized
|
||||
}
|
||||
wp.length = uint32(unsafe.Sizeof(wp))
|
||||
r, _, _ := pSetPlacement.Call(hwnd, uintptr(unsafe.Pointer(&wp)))
|
||||
return r != 0
|
||||
}
|
||||
|
||||
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 {
|
||||
b.reportFrame() // a window ended by Terminate, not closed by the user
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# yetano.dev/yetano/core/solutions
|
||||
|
||||
The engine of the **Yetano Solutions Guide** (Yetano Knowledge &
|
||||
Solutions): from what a user wants to achieve, through questions, rules
|
||||
and existing knowledge, to native, checked configuration. Design and
|
||||
requirements: `docs/knowledge-solutions/` in the meta-repo; the catalog
|
||||
it reads: `assets/solutions/`.
|
||||
|
||||
```text
|
||||
module yetano.dev/yetano/core/solutions tags: solutions/v0.1.0, ... go 1.25
|
||||
```
|
||||
|
||||
A nested module of the core repository (like `core/gui`, `core/tui`):
|
||||
standard library, `gopkg.in/yaml.v3` and `yetano.dev/yetano/core`
|
||||
(`secretref`, `paths`). No cgo; builds for js/wasm.
|
||||
|
||||
| Package | What |
|
||||
|---|---|
|
||||
| `catalog` | manifest model, strict loader, Big Picture view, validation, condition language, JSON Schemas |
|
||||
| `ref` | `yetano:<kind>/<path>[#section][@version]` references, heading slugs |
|
||||
| `engine` | `Evaluate` (questions, rules, packages, capabilities, providers, modules, configuration with origins, graph, steps, checks), `Generate`/`Write` (lock, plan, handbook, hand-edit protection), presets |
|
||||
| `knowledge` | index over catalog, Big Picture and manuals; `Resolve`, `Read`, `Search`, backlinks, `Lint`, coverage |
|
||||
| `store` | instances, sessions, presets, favorites, recent as files |
|
||||
| `cli` | `solution`, `task`, `knowledge`, `open` with yet's conventions (`cli.Run`) |
|
||||
| `cmd/yetano-solutions` | the same commands standalone (catalog CI, development) |
|
||||
|
||||
The engine is pure: it never runs a command and never opens a network
|
||||
connection (tested); only the CLI's `doctor` resolves DNS and probes
|
||||
local ports.
|
||||
|
||||
```sh
|
||||
go test ./...
|
||||
go run ./cmd/yetano-solutions --catalog ../../assets/solutions solution setup mail-server
|
||||
```
|
||||
|
||||
Tags carry the `solutions/` prefix; never move a tag.
|
||||
@@ -0,0 +1,228 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// BigPicture is the read-only view of assets/bigpicture/verse that the
|
||||
// guide builds on (ADR-0002). Validation of these files belongs to bpgen;
|
||||
// here they are decoded leniently and only the fields the guide uses are
|
||||
// kept.
|
||||
type BigPicture struct {
|
||||
Dir string `json:"-"`
|
||||
fsys fs.FS
|
||||
Title string `json:"title"`
|
||||
WebPath string `json:"webPath"` // "map/"
|
||||
Topics map[string]*BPTopic `json:"topics"`
|
||||
Stories map[string]*BPStory `json:"stories"`
|
||||
Products map[string]*BPProduct `json:"products"`
|
||||
Connections []BPConnection `json:"connections"`
|
||||
Interfaces map[string]BPInterface `json:"interfaces"`
|
||||
Files []FileHash `json:"-"`
|
||||
}
|
||||
|
||||
// BPTopic is a Big Picture topic.
|
||||
type BPTopic struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Summary string `yaml:"summary" json:"summary"`
|
||||
EntryStory string `yaml:"entryStory" json:"entryStory,omitempty"`
|
||||
}
|
||||
|
||||
// BPStory is a Big Picture goal (user story).
|
||||
type BPStory struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Intent string `yaml:"intent" json:"intent"`
|
||||
Outcome string `yaml:"outcome" json:"outcome"`
|
||||
Explanation string `yaml:"explanation" json:"explanation,omitempty"`
|
||||
PrimaryTopic string `yaml:"primaryTopic" json:"primaryTopic"`
|
||||
RelatedTopics []string `yaml:"relatedTopics" json:"relatedTopics,omitempty"`
|
||||
Roles []struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Product string `yaml:"product" json:"product"`
|
||||
Contribution string `yaml:"contribution" json:"contribution"`
|
||||
Participation string `yaml:"participation" json:"participation"`
|
||||
} `yaml:"roles" json:"roles"`
|
||||
Next []struct {
|
||||
Story string `yaml:"story" json:"story"`
|
||||
Reason string `yaml:"reason" json:"reason"`
|
||||
} `yaml:"next" json:"next,omitempty"`
|
||||
}
|
||||
|
||||
// BPProduct is a Big Picture program.
|
||||
type BPProduct struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Summary string `yaml:"summary" json:"summary"`
|
||||
PrimaryTopic string `yaml:"primaryTopic" json:"primaryTopic"`
|
||||
Tasks []string `yaml:"tasks" json:"tasks,omitempty"`
|
||||
Links []struct {
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Href string `yaml:"href" json:"href"`
|
||||
} `yaml:"links" json:"links,omitempty"`
|
||||
}
|
||||
|
||||
// BPConnection is a technical relation between programs/interfaces.
|
||||
type BPConnection struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
From string `yaml:"from" json:"from"`
|
||||
To string `yaml:"to" json:"to"`
|
||||
Type string `yaml:"type" json:"type"`
|
||||
Label string `yaml:"label" json:"label"`
|
||||
Scope string `yaml:"scope" json:"scope"`
|
||||
Review string `yaml:"review" json:"review"`
|
||||
Stories []string `yaml:"stories" json:"stories,omitempty"`
|
||||
}
|
||||
|
||||
// BPInterface is a shared interface (OCI registry, ...).
|
||||
type BPInterface struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Summary string `yaml:"summary" json:"summary"`
|
||||
}
|
||||
|
||||
// LoadBigPicture reads dir/manifest.yaml and the files it names.
|
||||
func LoadBigPicture(dir string) (*BigPicture, error) {
|
||||
return LoadBigPictureFS(os.DirFS(dir), dir)
|
||||
}
|
||||
|
||||
// LoadBigPictureFS reads manifest.yaml and the files it names from fsys
|
||||
// (an embedded copy, e.g. in the browser); dir only names it in messages.
|
||||
func LoadBigPictureFS(fsys fs.FS, dir string) (*BigPicture, error) {
|
||||
bp := &BigPicture{
|
||||
Dir: dir, fsys: fsys, WebPath: "map/",
|
||||
Topics: map[string]*BPTopic{}, Stories: map[string]*BPStory{},
|
||||
Products: map[string]*BPProduct{}, Interfaces: map[string]BPInterface{},
|
||||
}
|
||||
var manifest struct {
|
||||
Title string `yaml:"title"`
|
||||
Content struct {
|
||||
Topics string `yaml:"topics"`
|
||||
Products string `yaml:"products"`
|
||||
Stories string `yaml:"stories"`
|
||||
Connections string `yaml:"connections"`
|
||||
} `yaml:"content"`
|
||||
}
|
||||
if err := bp.read("manifest.yaml", &manifest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bp.Title = manifest.Title
|
||||
var topics struct {
|
||||
Topics []*BPTopic `yaml:"topics"`
|
||||
}
|
||||
if err := bp.read(manifest.Content.Topics, &topics); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, t := range topics.Topics {
|
||||
bp.Topics[t.ID] = t
|
||||
}
|
||||
if err := bp.readDir(manifest.Content.Products, func(name string) error {
|
||||
var p BPProduct
|
||||
if err := bp.read(name, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
bp.Products[p.ID] = &p
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := bp.readDir(manifest.Content.Stories, func(name string) error {
|
||||
var s BPStory
|
||||
if err := bp.read(name, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
bp.Stories[s.ID] = &s
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var conns struct {
|
||||
Interfaces []BPInterface `yaml:"interfaces"`
|
||||
Connections []BPConnection `yaml:"connections"`
|
||||
}
|
||||
if manifest.Content.Connections != "" {
|
||||
if err := bp.read(manifest.Content.Connections, &conns); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, i := range conns.Interfaces {
|
||||
bp.Interfaces[i.ID] = i
|
||||
}
|
||||
bp.Connections = conns.Connections
|
||||
sort.Slice(bp.Files, func(i, j int) bool { return bp.Files[i].Path < bp.Files[j].Path })
|
||||
return bp, nil
|
||||
}
|
||||
|
||||
func (bp *BigPicture) read(name string, v any) error {
|
||||
if name == "" {
|
||||
return fmt.Errorf("big picture: manifest names no file")
|
||||
}
|
||||
b, err := fs.ReadFile(bp.fsys, path.Clean(filepath.ToSlash(name)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("big picture: %w", err)
|
||||
}
|
||||
if len(b) > MaxFileSize {
|
||||
return fmt.Errorf("big picture: %s too large", name)
|
||||
}
|
||||
bp.Files = append(bp.Files, FileHash{Path: "bigpicture:" + filepath.ToSlash(name), Hash: sha(b)})
|
||||
if err := yaml.Unmarshal(b, v); err != nil {
|
||||
return fmt.Errorf("big picture: %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bp *BigPicture) readDir(sub string, fn func(string) error) error {
|
||||
ents, err := fs.ReadDir(bp.fsys, path.Clean(filepath.ToSlash(sub)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("big picture: %w", err)
|
||||
}
|
||||
for _, e := range ents {
|
||||
if e.IsDir() || !strings.HasSuffix(e.Name(), ".yaml") {
|
||||
continue
|
||||
}
|
||||
if err := fn(filepath.Join(sub, e.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Has reports whether a Big Picture element ID exists.
|
||||
func (bp *BigPicture) Has(id string) bool {
|
||||
if bp == nil {
|
||||
return false
|
||||
}
|
||||
if _, ok := bp.Topics[id]; ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := bp.Stories[id]; ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := bp.Products[id]; ok {
|
||||
return true
|
||||
}
|
||||
_, ok := bp.Interfaces[id]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Fragment is the map URL fragment for an element (story.x -> story=x).
|
||||
func (bp *BigPicture) Fragment(id string) string {
|
||||
kind, slug, ok := strings.Cut(id, ".")
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
switch kind {
|
||||
case "topic", "story", "product", "interface":
|
||||
return kind + "=" + slug
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package catalog
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCond(t *testing.T) {
|
||||
env := Env{Answers: map[string]any{"a": "x", "n": 3, "l": []any{"p", "q"}, "b": true, "e": ""}, Mode: LevelGuided}
|
||||
cases := []struct {
|
||||
c Cond
|
||||
want bool
|
||||
}{
|
||||
{Cond{}, true},
|
||||
{Cond{"a": "x"}, true},
|
||||
{Cond{"a": "y"}, false},
|
||||
{Cond{"a": []any{"y", "x"}}, true},
|
||||
{Cond{"l": "q"}, true},
|
||||
{Cond{"l": "z"}, false},
|
||||
{Cond{"a": map[string]any{"not": "x"}}, false},
|
||||
{Cond{"n": map[string]any{"gte": 3, "lt": 4}}, true},
|
||||
{Cond{"l": map[string]any{"count_gte": 2}}, true},
|
||||
{Cond{"e": map[string]any{"set": false}}, true},
|
||||
{Cond{"missing": map[string]any{"set": true}}, false},
|
||||
{Cond{"b": true}, true},
|
||||
{Cond{"b": "true"}, true},
|
||||
{Cond{"any": []any{map[string]any{"a": "y"}, map[string]any{"n": 3}}}, true},
|
||||
{Cond{"all": []any{map[string]any{"a": "x"}, map[string]any{"n": 4}}}, false},
|
||||
{Cond{"not": map[string]any{"a": "x"}}, false},
|
||||
{Cond{"$mode": "guided"}, true},
|
||||
}
|
||||
for i, c := range cases {
|
||||
got, err := c.c.Eval(env)
|
||||
if err != nil || got != c.want {
|
||||
t.Errorf("%d %v: got %v %v", i, c.c, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := (Cond{"a": map[string]any{"regex": "x"}}).Eval(env); err == nil {
|
||||
t.Error("unknown operator accepted")
|
||||
}
|
||||
deep := Cond{"a": "x"}
|
||||
for i := 0; i < MaxCondDepth+2; i++ {
|
||||
deep = Cond{"not": map[string]any(deep)}
|
||||
}
|
||||
if _, err := deep.Eval(env); err == nil {
|
||||
t.Error("unbounded nesting accepted")
|
||||
}
|
||||
if r := (Cond{"any": []any{map[string]any{"x": 1}}, "y": 2, "$mode": "q"}).Refs(); len(r) != 2 || r[0] != "x" || r[1] != "y" {
|
||||
t.Errorf("refs %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeRelPath(t *testing.T) {
|
||||
for _, ok := range []string{"a/b.yaml", "yamase/yamase.yaml"} {
|
||||
if !SafeRelPath(ok) {
|
||||
t.Errorf("%s rejected", ok)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "/etc/passwd", "../x", "a/../../x", "a/./b", "a//b", ".hidden/x", `a\b`, "c:/x"} {
|
||||
if SafeRelPath(bad) {
|
||||
t.Errorf("%q accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Cond is a condition over wizard answers (ADR-0003). It is plain data:
|
||||
//
|
||||
// {q: v} answer equals v (a multiselect answer: contains v)
|
||||
// {q: [a, b]} answer is one of a, b (multiselect: contains one)
|
||||
// {q: {in: [..]}} same as a list
|
||||
// {q: {not: v}} answer is not v (not one of a list)
|
||||
// {q: {set: true|false}} answer is (not) given and non-empty
|
||||
// {q: {gt|gte|lt|lte: n}} numeric comparison
|
||||
// {q: {count_gte|count_lte: n}} number of list items
|
||||
// {all: [c, ..]} {any: [c, ..]} {not: c}
|
||||
// {$mode: guided} wizard mode; {$platform: linux}
|
||||
//
|
||||
// Several keys in one map must all hold. An empty condition is true.
|
||||
type Cond map[string]any
|
||||
|
||||
// Env is what a condition is evaluated against.
|
||||
type Env struct {
|
||||
Answers map[string]any
|
||||
Mode Level
|
||||
Platform string
|
||||
}
|
||||
|
||||
// MaxCondDepth bounds nesting (RULE-08).
|
||||
const MaxCondDepth = 16
|
||||
|
||||
// Eval evaluates c. Errors are malformed conditions (the linter reports
|
||||
// them before a catalog is used).
|
||||
func (c Cond) Eval(env Env) (bool, error) { return evalMap(map[string]any(c), env, 0) }
|
||||
|
||||
// Holds is Eval for callers that validated the catalog: a malformed
|
||||
// condition counts as false.
|
||||
func (c Cond) Holds(env Env) bool {
|
||||
ok, err := c.Eval(env)
|
||||
return err == nil && ok
|
||||
}
|
||||
|
||||
func evalMap(m map[string]any, env Env, depth int) (bool, error) {
|
||||
if depth > MaxCondDepth {
|
||||
return false, fmt.Errorf("condition nested deeper than %d", MaxCondDepth)
|
||||
}
|
||||
keys := sortedKeys(m)
|
||||
for _, k := range keys {
|
||||
v := m[k]
|
||||
var ok bool
|
||||
var err error
|
||||
switch k {
|
||||
case "all", "any":
|
||||
list, isList := v.([]any)
|
||||
if !isList {
|
||||
return false, fmt.Errorf("%s: want a list of conditions", k)
|
||||
}
|
||||
ok = k == "all"
|
||||
for _, item := range list {
|
||||
sub, isMap := asMap(item)
|
||||
if !isMap {
|
||||
return false, fmt.Errorf("%s: want a list of conditions", k)
|
||||
}
|
||||
r, err := evalMap(sub, env, depth+1)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if k == "all" && !r {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
if k == "any" && r {
|
||||
ok = true
|
||||
break
|
||||
}
|
||||
}
|
||||
case "not":
|
||||
sub, isMap := asMap(v)
|
||||
if !isMap {
|
||||
return false, fmt.Errorf("not: want a condition")
|
||||
}
|
||||
r, err := evalMap(sub, env, depth+1)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ok = !r
|
||||
case "$mode":
|
||||
ok, err = match(string(env.Mode), v)
|
||||
case "$platform":
|
||||
ok, err = match(env.Platform, v)
|
||||
default:
|
||||
ok, err = match(env.Answers[k], v)
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s: %w", k, err)
|
||||
}
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// match compares one answer with a condition value.
|
||||
func match(answer any, want any) (bool, error) {
|
||||
if ops, ok := asMap(want); ok {
|
||||
for _, op := range sortedKeys(ops) {
|
||||
arg := ops[op]
|
||||
var r bool
|
||||
switch op {
|
||||
case "in":
|
||||
r = matchAny(answer, arg)
|
||||
case "not":
|
||||
r = !matchAny(answer, arg)
|
||||
case "set":
|
||||
b, isBool := arg.(bool)
|
||||
if !isBool {
|
||||
return false, fmt.Errorf("set: want true or false")
|
||||
}
|
||||
r = IsSet(answer) == b
|
||||
case "gt", "gte", "lt", "lte":
|
||||
a, aok := toFloat(answer)
|
||||
n, nok := toFloat(arg)
|
||||
if !nok {
|
||||
return false, fmt.Errorf("%s: want a number", op)
|
||||
}
|
||||
if !aok {
|
||||
r = false
|
||||
break
|
||||
}
|
||||
switch op {
|
||||
case "gt":
|
||||
r = a > n
|
||||
case "gte":
|
||||
r = a >= n
|
||||
case "lt":
|
||||
r = a < n
|
||||
case "lte":
|
||||
r = a <= n
|
||||
}
|
||||
case "count_gte", "count_lte":
|
||||
n, nok := toFloat(arg)
|
||||
if !nok {
|
||||
return false, fmt.Errorf("%s: want a number", op)
|
||||
}
|
||||
cnt := float64(len(asList(answer)))
|
||||
if op == "count_gte" {
|
||||
r = cnt >= n
|
||||
} else {
|
||||
r = cnt <= n
|
||||
}
|
||||
default:
|
||||
return false, fmt.Errorf("unknown operator %q", op)
|
||||
}
|
||||
if !r {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
return matchAny(answer, want), nil
|
||||
}
|
||||
|
||||
// matchAny: want is a scalar or a list of scalars; answer a scalar or list.
|
||||
func matchAny(answer any, want any) bool {
|
||||
wants := asList(want)
|
||||
if want != nil && len(wants) == 0 {
|
||||
if _, isList := want.([]any); !isList {
|
||||
wants = []any{want}
|
||||
}
|
||||
}
|
||||
answers := asList(answer)
|
||||
if _, isList := answer.([]any); !isList {
|
||||
if _, isStrList := answer.([]string); !isStrList {
|
||||
answers = []any{answer}
|
||||
}
|
||||
}
|
||||
for _, a := range answers {
|
||||
for _, w := range wants {
|
||||
if Equal(a, w) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Equal compares two scalar answer values loosely: numbers by value,
|
||||
// everything else by its string form ("true" == true).
|
||||
func Equal(a, b any) bool {
|
||||
if a == nil || b == nil {
|
||||
return a == nil && b == nil
|
||||
}
|
||||
if fa, ok := toFloat(a); ok {
|
||||
if fb, ok := toFloat(b); ok {
|
||||
return fa == fb
|
||||
}
|
||||
}
|
||||
return Scalar(a) == Scalar(b)
|
||||
}
|
||||
|
||||
// Scalar renders a scalar answer as text.
|
||||
func Scalar(v any) string {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return x
|
||||
case bool:
|
||||
return strconv.FormatBool(x)
|
||||
case int:
|
||||
return strconv.Itoa(x)
|
||||
case int64:
|
||||
return strconv.FormatInt(x, 10)
|
||||
case float64:
|
||||
return strconv.FormatFloat(x, 'f', -1, 64)
|
||||
}
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
|
||||
// IsSet reports whether an answer is present and not empty.
|
||||
func IsSet(v any) bool {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case string:
|
||||
return strings.TrimSpace(x) != ""
|
||||
case []any:
|
||||
return len(x) > 0
|
||||
case []string:
|
||||
return len(x) > 0
|
||||
case map[string]any:
|
||||
return len(x) > 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func toFloat(v any) (float64, bool) {
|
||||
switch x := v.(type) {
|
||||
case int:
|
||||
return float64(x), true
|
||||
case int64:
|
||||
return float64(x), true
|
||||
case float64:
|
||||
return x, true
|
||||
case uint64:
|
||||
return float64(x), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func asList(v any) []any {
|
||||
switch x := v.(type) {
|
||||
case []any:
|
||||
return x
|
||||
case []string:
|
||||
out := make([]any, len(x))
|
||||
for i, s := range x {
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func asMap(v any) (map[string]any, bool) {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
return x, true
|
||||
case Cond:
|
||||
return map[string]any(x), true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]any) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// Refs returns the question IDs a condition reads (for the linter).
|
||||
func (c Cond) Refs() []string {
|
||||
seen := map[string]bool{}
|
||||
var walk func(m map[string]any, depth int)
|
||||
walk = func(m map[string]any, depth int) {
|
||||
if depth > MaxCondDepth {
|
||||
return
|
||||
}
|
||||
for k, v := range m {
|
||||
switch k {
|
||||
case "all", "any":
|
||||
if list, ok := v.([]any); ok {
|
||||
for _, item := range list {
|
||||
if sub, ok := asMap(item); ok {
|
||||
walk(sub, depth+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
case "not":
|
||||
if sub, ok := asMap(v); ok {
|
||||
walk(sub, depth+1)
|
||||
}
|
||||
case "$mode", "$platform":
|
||||
default:
|
||||
seen[k] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(map[string]any(c), 0)
|
||||
out := make([]string, 0, len(seen))
|
||||
for k := range seen {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Limits protect against hostile catalogs (SEC-03).
|
||||
const (
|
||||
MaxFileSize = 4 << 20
|
||||
MaxFiles = 10000
|
||||
MaxQuestions = 500
|
||||
MaxRules = 1000
|
||||
)
|
||||
|
||||
// Entity fields shared by all loaded manifests.
|
||||
type Entity struct {
|
||||
Kind string `json:"kind"`
|
||||
Meta Meta `json:"metadata"`
|
||||
File string `json:"file"` // relative to the catalog root (or "bigpicture:...")
|
||||
Line int `json:"line"`
|
||||
Hash string `json:"hash"` // sha256 of the document's source
|
||||
}
|
||||
|
||||
// Package is a loaded Package manifest.
|
||||
type Package struct {
|
||||
Entity
|
||||
Spec PackageSpec `json:"spec"`
|
||||
}
|
||||
|
||||
// Module returns the module with that ID.
|
||||
func (p *Package) Module(id string) *Module {
|
||||
for i := range p.Spec.Modules {
|
||||
if p.Spec.Modules[i].ID == id {
|
||||
return &p.Spec.Modules[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Profile is a loaded Profile manifest.
|
||||
type Profile struct {
|
||||
Entity
|
||||
Spec ProfileSpec `json:"spec"`
|
||||
}
|
||||
|
||||
// Key is "<package>/<id>".
|
||||
func (p *Profile) Key() string { return p.Meta.Package + "/" + p.Meta.ID }
|
||||
|
||||
// Solution is a loaded Solution or Task manifest.
|
||||
type Solution struct {
|
||||
Entity
|
||||
Spec SolutionSpec `json:"spec"`
|
||||
}
|
||||
|
||||
// IsTask reports whether this is a Task.
|
||||
func (s *Solution) IsTask() bool { return s.Kind == KindTask }
|
||||
|
||||
// Question returns the question with that ID and its index.
|
||||
func (s *Solution) Question(id string) (*Question, int) {
|
||||
for i := range s.Spec.Questions {
|
||||
if s.Spec.Questions[i].ID == id {
|
||||
return &s.Spec.Questions[i], i
|
||||
}
|
||||
}
|
||||
return nil, -1
|
||||
}
|
||||
|
||||
// Example is a loaded Example manifest.
|
||||
type Example struct {
|
||||
Entity
|
||||
Spec ExampleSpec `json:"spec"`
|
||||
}
|
||||
|
||||
// Key is "<solution>/<id>".
|
||||
func (e *Example) Key() string { return e.Spec.Solution + "/" + e.Meta.ID }
|
||||
|
||||
// KnowledgeSource is a loaded KnowledgeSource manifest.
|
||||
type KnowledgeSource struct {
|
||||
Entity
|
||||
Spec KnowledgeSourceSpec `json:"spec"`
|
||||
}
|
||||
|
||||
// Catalog is everything loaded from one catalog root.
|
||||
type Catalog struct {
|
||||
Root string `json:"-"`
|
||||
Meta Meta `json:"metadata"`
|
||||
Spec CatalogSpec `json:"spec"`
|
||||
Capabilities map[string]*Capability `json:"capabilities"`
|
||||
Packages map[string]*Package `json:"packages"`
|
||||
Profiles map[string]*Profile `json:"profiles"`
|
||||
Solutions map[string]*Solution `json:"solutions"`
|
||||
Tasks map[string]*Solution `json:"tasks"`
|
||||
Examples map[string]*Example `json:"examples"`
|
||||
Sources map[string]*KnowledgeSource `json:"sources"`
|
||||
BigPicture *BigPicture `json:"bigpicture"`
|
||||
// Files are all source files with their hashes, sorted (for locks).
|
||||
Files []FileHash `json:"files"`
|
||||
// Issues found while loading (fatal ones make Load fail).
|
||||
Issues []Issue `json:"-"`
|
||||
|
||||
capFile map[string]string
|
||||
}
|
||||
|
||||
// FileHash is one source file and its sha256.
|
||||
type FileHash struct {
|
||||
Path string `json:"path"`
|
||||
Hash string `json:"sha256"`
|
||||
}
|
||||
|
||||
// Issue is a problem in a catalog (load, validation or lint).
|
||||
type Issue struct {
|
||||
Severity string `json:"severity"` // error | warning
|
||||
File string `json:"file,omitempty"`
|
||||
Line int `json:"line,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (i Issue) String() string {
|
||||
loc := i.File
|
||||
if i.Line > 0 {
|
||||
loc = fmt.Sprintf("%s:%d", i.File, i.Line)
|
||||
}
|
||||
if loc != "" {
|
||||
loc += ": "
|
||||
}
|
||||
id := ""
|
||||
if i.ID != "" {
|
||||
id = i.ID + ": "
|
||||
}
|
||||
return fmt.Sprintf("%s%s%s (%s)", loc, id, i.Message, i.Code)
|
||||
}
|
||||
|
||||
// ErrInvalid wraps load errors.
|
||||
var ErrInvalid = errors.New("invalid catalog")
|
||||
|
||||
// Load reads a catalog root directory (the one with catalog.yaml).
|
||||
func Load(root string) (*Catalog, error) {
|
||||
return LoadFS(os.DirFS(root), root)
|
||||
}
|
||||
|
||||
// LoadFS reads a catalog from fsys (root is only used for messages and
|
||||
// to find the Big Picture relative to it, when fsys is a directory).
|
||||
func LoadFS(fsys fs.FS, root string) (*Catalog, error) {
|
||||
return LoadFSWith(fsys, root, nil)
|
||||
}
|
||||
|
||||
// LoadFSWith is LoadFS with the Big Picture read from bigPicture instead
|
||||
// of the directory catalog.yaml names -- for a catalog without a disk
|
||||
// (embedded in a program, or in the browser as WebAssembly). nil: as
|
||||
// LoadFS.
|
||||
func LoadFSWith(fsys fs.FS, root string, bigPicture fs.FS) (*Catalog, error) {
|
||||
c := &Catalog{
|
||||
Root: root,
|
||||
Capabilities: map[string]*Capability{},
|
||||
Packages: map[string]*Package{},
|
||||
Profiles: map[string]*Profile{},
|
||||
Solutions: map[string]*Solution{},
|
||||
Tasks: map[string]*Solution{},
|
||||
Examples: map[string]*Example{},
|
||||
Sources: map[string]*KnowledgeSource{},
|
||||
capFile: map[string]string{},
|
||||
}
|
||||
var files []string
|
||||
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := d.Name()
|
||||
if d.IsDir() {
|
||||
if p != "." && (strings.HasPrefix(name, ".") || name == "schema" || name == "testdata" || name == "golden") {
|
||||
return fs.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml") {
|
||||
files = append(files, p)
|
||||
if len(files) > MaxFiles {
|
||||
return fmt.Errorf("more than %d files", MaxFiles)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||
}
|
||||
sort.Strings(files)
|
||||
sawRoot := false
|
||||
for _, f := range files {
|
||||
b, err := readLimited(fsys, f)
|
||||
if err != nil {
|
||||
c.add("error", f, 0, "", "read", err.Error())
|
||||
continue
|
||||
}
|
||||
c.Files = append(c.Files, FileHash{Path: f, Hash: sha(b)})
|
||||
if c.loadFile(f, b) {
|
||||
sawRoot = true
|
||||
}
|
||||
}
|
||||
if !sawRoot {
|
||||
c.add("error", "catalog.yaml", 0, "", "no-root", "no Catalog manifest (catalog.yaml) found")
|
||||
}
|
||||
if c.Spec.BigPicture != "" && bigPicture != nil {
|
||||
bp, err := LoadBigPictureFS(bigPicture, c.Spec.BigPicture)
|
||||
if err != nil {
|
||||
c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error())
|
||||
} else {
|
||||
c.BigPicture = bp
|
||||
c.Files = append(c.Files, bp.Files...)
|
||||
}
|
||||
} else if c.Spec.BigPicture != "" {
|
||||
bpDir := c.Spec.BigPicture
|
||||
if !filepath.IsAbs(bpDir) {
|
||||
bpDir = filepath.Join(root, bpDir)
|
||||
}
|
||||
bp, err := LoadBigPicture(bpDir)
|
||||
if err != nil {
|
||||
c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error())
|
||||
} else {
|
||||
c.BigPicture = bp
|
||||
c.Files = append(c.Files, bp.Files...)
|
||||
}
|
||||
}
|
||||
sort.Slice(c.Files, func(i, j int) bool { return c.Files[i].Path < c.Files[j].Path })
|
||||
if errs := c.Errors(); len(errs) > 0 {
|
||||
return c, fmt.Errorf("%w: %d error(s), first: %s", ErrInvalid, len(errs), errs[0])
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func readLimited(fsys fs.FS, p string) ([]byte, error) {
|
||||
f, err := fsys.Open(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(f, MaxFileSize+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(b) > MaxFileSize {
|
||||
return nil, fmt.Errorf("larger than %d bytes", MaxFileSize)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func sha(b []byte) string {
|
||||
h := sha256.Sum256(b)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func (c *Catalog) add(sev, file string, line int, id, code, msg string) {
|
||||
c.Issues = append(c.Issues, Issue{Severity: sev, File: file, Line: line, ID: id, Code: code, Message: msg})
|
||||
}
|
||||
|
||||
// Errors returns the issues with severity error.
|
||||
func (c *Catalog) Errors() []Issue {
|
||||
var out []Issue
|
||||
for _, i := range c.Issues {
|
||||
if i.Severity == "error" {
|
||||
out = append(out, i)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// loadFile decodes all documents of one file; reports whether it held the root.
|
||||
func (c *Catalog) loadFile(file string, b []byte) bool {
|
||||
dec := yaml.NewDecoder(bytes.NewReader(b))
|
||||
root := false
|
||||
for {
|
||||
var doc yaml.Node
|
||||
err := dec.Decode(&doc)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
c.add("error", file, 0, "", "yaml", err.Error())
|
||||
return root
|
||||
}
|
||||
if len(doc.Content) == 0 {
|
||||
continue
|
||||
}
|
||||
raw, _ := yaml.Marshal(&doc)
|
||||
var h Header
|
||||
if err := strictDecode(raw, &h); err != nil {
|
||||
c.add("error", file, doc.Line, "", "header", err.Error())
|
||||
continue
|
||||
}
|
||||
line := doc.Content[0].Line
|
||||
if h.APIVersion != APIVersion {
|
||||
c.add("error", file, line, h.Metadata.ID, "api-version", fmt.Sprintf("apiVersion %q, want %q", h.APIVersion, APIVersion))
|
||||
continue
|
||||
}
|
||||
ent := Entity{Kind: h.Kind, Meta: h.Metadata, File: file, Line: line, Hash: sha(raw)}
|
||||
specRaw, _ := yaml.Marshal(&h.Spec)
|
||||
if h.Spec.Kind == 0 {
|
||||
specRaw = []byte("{}")
|
||||
}
|
||||
if err := c.addEntity(ent, specRaw); err != nil {
|
||||
c.add("error", file, line, h.Metadata.ID, "spec", err.Error())
|
||||
continue
|
||||
}
|
||||
if h.Kind == KindCatalog {
|
||||
root = true
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
func strictDecode(b []byte, v any) error {
|
||||
d := yaml.NewDecoder(bytes.NewReader(b))
|
||||
d.KnownFields(true)
|
||||
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Catalog) addEntity(e Entity, spec []byte) error {
|
||||
dup := func(kind, id, other string) error {
|
||||
return fmt.Errorf("duplicate %s %q (also in %s)", kind, id, other)
|
||||
}
|
||||
switch e.Kind {
|
||||
case KindCatalog:
|
||||
if c.Meta.ID != "" {
|
||||
return fmt.Errorf("more than one Catalog manifest")
|
||||
}
|
||||
if err := strictDecode(spec, &c.Spec); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Meta = e.Meta
|
||||
case KindCapabilities:
|
||||
var s CapabilitiesSpec
|
||||
if err := strictDecode(spec, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range s.Capabilities {
|
||||
cp := s.Capabilities[i]
|
||||
if other, ok := c.capFile[cp.ID]; ok {
|
||||
return dup("capability", cp.ID, other)
|
||||
}
|
||||
c.Capabilities[cp.ID] = &cp
|
||||
c.capFile[cp.ID] = e.File
|
||||
}
|
||||
case KindPackage:
|
||||
p := &Package{Entity: e}
|
||||
if err := strictDecode(spec, &p.Spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if o, ok := c.Packages[e.Meta.ID]; ok {
|
||||
return dup("package", e.Meta.ID, o.File)
|
||||
}
|
||||
c.Packages[e.Meta.ID] = p
|
||||
case KindProfile:
|
||||
p := &Profile{Entity: e}
|
||||
if err := strictDecode(spec, &p.Spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Meta.Package == "" {
|
||||
return fmt.Errorf("profile %q: metadata.package is required", e.Meta.ID)
|
||||
}
|
||||
if o, ok := c.Profiles[p.Key()]; ok {
|
||||
return dup("profile", p.Key(), o.File)
|
||||
}
|
||||
c.Profiles[p.Key()] = p
|
||||
case KindSolution, KindTask:
|
||||
s := &Solution{Entity: e}
|
||||
if err := strictDecode(spec, &s.Spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s.Spec.Questions) > MaxQuestions || len(s.Spec.Rules) > MaxRules {
|
||||
return fmt.Errorf("more than %d questions or %d rules", MaxQuestions, MaxRules)
|
||||
}
|
||||
m := c.Solutions
|
||||
if e.Kind == KindTask {
|
||||
m = c.Tasks
|
||||
}
|
||||
if o, ok := m[e.Meta.ID]; ok {
|
||||
return dup(strings.ToLower(e.Kind), e.Meta.ID, o.File)
|
||||
}
|
||||
m[e.Meta.ID] = s
|
||||
case KindExample:
|
||||
x := &Example{Entity: e}
|
||||
if err := strictDecode(spec, &x.Spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if x.Spec.Solution == "" {
|
||||
// default: the solution directory the example lives in
|
||||
x.Spec.Solution = solutionDirOf(e.File)
|
||||
}
|
||||
if o, ok := c.Examples[x.Key()]; ok {
|
||||
return dup("example", x.Key(), o.File)
|
||||
}
|
||||
c.Examples[x.Key()] = x
|
||||
case KindKnowledgeSource:
|
||||
k := &KnowledgeSource{Entity: e}
|
||||
if err := strictDecode(spec, &k.Spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if o, ok := c.Sources[e.Meta.ID]; ok {
|
||||
return dup("knowledge source", e.Meta.ID, o.File)
|
||||
}
|
||||
c.Sources[e.Meta.ID] = k
|
||||
default:
|
||||
return fmt.Errorf("unknown kind %q", e.Kind)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// solutionDirOf: solutions/<category>/<id>/examples/x.yaml -> <id>.
|
||||
func solutionDirOf(file string) string {
|
||||
dir := path.Dir(path.Dir(file))
|
||||
return path.Base(dir)
|
||||
}
|
||||
|
||||
// SortedIDs returns the keys of a map in order.
|
||||
func SortedIDs[V any](m map[string]V) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// Lookup finds a solution or task by ID (solutions first).
|
||||
func (c *Catalog) Lookup(id string) *Solution {
|
||||
if s, ok := c.Solutions[id]; ok {
|
||||
return s
|
||||
}
|
||||
if s, ok := c.Tasks[id]; ok {
|
||||
return s
|
||||
}
|
||||
for _, m := range []map[string]*Solution{c.Solutions, c.Tasks} {
|
||||
for _, s := range m {
|
||||
for _, a := range s.Meta.Aliases {
|
||||
if a == id {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProvidersOf lists package modules providing a capability, best first.
|
||||
func (c *Catalog) ProvidersOf(capID string) []ModuleRef {
|
||||
var out []ModuleRef
|
||||
for _, pid := range SortedIDs(c.Packages) {
|
||||
p := c.Packages[pid]
|
||||
for _, m := range p.Spec.Modules {
|
||||
for _, pr := range m.Provides {
|
||||
if pr == capID {
|
||||
out = append(out, ModuleRef{Package: pid, Module: m.ID, Priority: m.Priority, Support: m.Support})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool { return out[i].Priority > out[j].Priority })
|
||||
return out
|
||||
}
|
||||
|
||||
// ModuleRef points at one module of one package.
|
||||
type ModuleRef struct {
|
||||
Package string `json:"package"`
|
||||
Module string `json:"module"`
|
||||
Priority int `json:"priority,omitempty"`
|
||||
Support Support `json:"support,omitempty"`
|
||||
}
|
||||
|
||||
func (m ModuleRef) String() string { return m.Package + "/" + m.Module }
|
||||
|
||||
// ProfileChain returns the profile and its ancestors, base first; it
|
||||
// fails on unknown profiles and cycles (PROF-03).
|
||||
func (c *Catalog) ProfileChain(pkg, id string) ([]*Profile, error) {
|
||||
var chain []*Profile
|
||||
seen := map[string]bool{}
|
||||
for cur := id; cur != ""; {
|
||||
key := pkg + "/" + cur
|
||||
if seen[key] {
|
||||
return nil, fmt.Errorf("profile %s: inheritance cycle", key)
|
||||
}
|
||||
seen[key] = true
|
||||
p, ok := c.Profiles[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown profile %s", key)
|
||||
}
|
||||
chain = append(chain, p)
|
||||
cur = p.Spec.Extends
|
||||
}
|
||||
for i, j := 0, len(chain)-1; i < j; i, j = i+1, j-1 {
|
||||
chain[i], chain[j] = chain[j], chain[i]
|
||||
}
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
// Hash is a digest over all catalog files (catalog version for locks).
|
||||
func (c *Catalog) Hash() string {
|
||||
h := sha256.New()
|
||||
for _, f := range c.Files {
|
||||
fmt.Fprintf(h, "%s %s\n", f.Path, f.Hash)
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A catalog without a disk (embedded, or in the browser) loads the Big
|
||||
// Picture from its own fs.FS and gives the same catalog as from disk.
|
||||
func TestLoadFSWith(t *testing.T) {
|
||||
disk, err := Load("../engine/testdata/cat")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// "/nonexistent" as root: nothing may be read from disk
|
||||
emb, err := LoadFSWith(os.DirFS("../engine/testdata/cat"), "/nonexistent", os.DirFS("../engine/testdata/bp"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if emb.BigPicture == nil || len(emb.BigPicture.Products) == 0 {
|
||||
t.Fatal("no Big Picture")
|
||||
}
|
||||
if !reflect.DeepEqual(SortedIDs(disk.BigPicture.Products), SortedIDs(emb.BigPicture.Products)) || disk.Hash() != emb.Hash() {
|
||||
t.Fatalf("embedded catalog differs: %v / %v", disk.Hash(), emb.Hash())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
// Package catalog is the data model of Yetano Knowledge & Solutions: the
|
||||
// manifests under assets/solutions (Capability, Package, Profile,
|
||||
// Solution, Task, Example, KnowledgeSource) and the read-only view of the
|
||||
// Big Picture sources (topics, goals, programs) they build on.
|
||||
//
|
||||
// Everything here is data. Nothing in a catalog is ever executed: there
|
||||
// are no template functions, no commands run by the engine and no network
|
||||
// access (see docs/knowledge-solutions/SECURITY.md in the meta-repo).
|
||||
package catalog
|
||||
|
||||
import "gopkg.in/yaml.v3"
|
||||
|
||||
// APIVersion is the only manifest version this package reads.
|
||||
const APIVersion = "yetano.dev/v1"
|
||||
|
||||
// Manifest kinds.
|
||||
const (
|
||||
KindCatalog = "Catalog"
|
||||
KindCapabilities = "Capabilities"
|
||||
KindPackage = "Package"
|
||||
KindProfile = "Profile"
|
||||
KindSolution = "Solution"
|
||||
KindTask = "Task"
|
||||
KindExample = "Example"
|
||||
KindPreset = "Preset"
|
||||
KindInstance = "SolutionInstance"
|
||||
KindSession = "WizardSession"
|
||||
KindKnowledgeSource = "KnowledgeSource"
|
||||
)
|
||||
|
||||
// Support says how far an option, module or solution is backed by the
|
||||
// real programs (RULE-03). Only Supported, Experimental, Untested and
|
||||
// Discouraged can be selected; the others are shown with their reason.
|
||||
type Support string
|
||||
|
||||
const (
|
||||
Supported Support = "supported"
|
||||
Experimental Support = "experimental"
|
||||
Untested Support = "untested"
|
||||
Discouraged Support = "discouraged"
|
||||
NeedsPrereq Support = "needs-prerequisites"
|
||||
NotImplemented Support = "not-implemented"
|
||||
NotSupported Support = "not-supported"
|
||||
Impossible Support = "impossible"
|
||||
Insecure Support = "insecure"
|
||||
)
|
||||
|
||||
// Selectable reports whether an option with this support level may be chosen.
|
||||
func (s Support) Selectable() bool {
|
||||
switch s {
|
||||
case "", Supported, Experimental, Untested, Discouraged, NeedsPrereq:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Valid reports whether s is a known support level ("" means supported).
|
||||
func (s Support) Valid() bool {
|
||||
switch s {
|
||||
case "", Supported, Experimental, Untested, Discouraged, NeedsPrereq,
|
||||
NotImplemented, NotSupported, Impossible, Insecure:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Text is a translatable string set: the English base plus translations.
|
||||
type Translations map[string]map[string]string // lang -> field -> text
|
||||
|
||||
// Meta is the common metadata block.
|
||||
type Meta struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name,omitempty" json:"name,omitempty"` // presets/instances
|
||||
Package string `yaml:"package,omitempty" json:"package,omitempty"`
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||
Title string `yaml:"title,omitempty" json:"title,omitempty"`
|
||||
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Category string `yaml:"category,omitempty" json:"category,omitempty"`
|
||||
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
|
||||
Synonyms []string `yaml:"synonyms,omitempty" json:"synonyms,omitempty"`
|
||||
Difficulty string `yaml:"difficulty,omitempty" json:"difficulty,omitempty"`
|
||||
Status Support `yaml:"status,omitempty" json:"status,omitempty"`
|
||||
Audience []string `yaml:"audience,omitempty" json:"audience,omitempty"`
|
||||
Featured bool `yaml:"featured,omitempty" json:"featured,omitempty"`
|
||||
Origin string `yaml:"origin,omitempty" json:"origin,omitempty"` // official | local | org | community | ai
|
||||
Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"`
|
||||
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||
}
|
||||
|
||||
// Header is the envelope every manifest file has.
|
||||
type Header struct {
|
||||
APIVersion string `yaml:"apiVersion"`
|
||||
Kind string `yaml:"kind"`
|
||||
Metadata Meta `yaml:"metadata"`
|
||||
Spec yaml.Node `yaml:"spec"`
|
||||
}
|
||||
|
||||
// ---- Catalog root -------------------------------------------------------
|
||||
|
||||
// CatalogSpec is catalog.yaml: where the other sources are.
|
||||
type CatalogSpec struct {
|
||||
// BigPicture is the directory with the Big Picture manifest.yaml,
|
||||
// relative to catalog.yaml.
|
||||
BigPicture string `yaml:"bigpicture"`
|
||||
// SourcesRoot is where repositories named in knowledge sources are
|
||||
// checked out, relative to catalog.yaml (optional; manuals are then
|
||||
// only referenced, not indexed).
|
||||
SourcesRoot string `yaml:"sourcesRoot,omitempty"`
|
||||
// WebBase resolves web references (https://yetano.app/).
|
||||
WebBase string `yaml:"webBase"`
|
||||
// Categories maps Big Picture topics to guide categories (order = display order).
|
||||
Categories []Category `yaml:"categories"`
|
||||
// Locales the catalog is (partly) translated into; English is the base.
|
||||
Locales []string `yaml:"locales,omitempty"`
|
||||
}
|
||||
|
||||
// Category is a guide category, normally one Big Picture topic.
|
||||
type Category struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Topic string `yaml:"topic,omitempty" json:"topic,omitempty"`
|
||||
Title string `yaml:"title,omitempty" json:"title,omitempty"`
|
||||
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
|
||||
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||
}
|
||||
|
||||
// ---- Capabilities ---------------------------------------------------------
|
||||
|
||||
// Capability is an abstract ability (mail.smtp.server); see CAPABILITIES.md.
|
||||
type Capability struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Requires []string `yaml:"requires,omitempty" json:"requires,omitempty"`
|
||||
Conflicts []string `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
|
||||
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||
// Providers outside Yetano (an existing LDAP, PostgreSQL, ...).
|
||||
External []ExternalProvider `yaml:"external,omitempty" json:"external,omitempty"`
|
||||
}
|
||||
|
||||
// ExternalProvider is a provider that is not a Yetano package.
|
||||
type ExternalProvider struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
|
||||
}
|
||||
|
||||
// CapabilitiesSpec is a capabilities file.
|
||||
type CapabilitiesSpec struct {
|
||||
Capabilities []Capability `yaml:"capabilities"`
|
||||
}
|
||||
|
||||
// ---- Packages -------------------------------------------------------------
|
||||
|
||||
// PackageSpec describes a Yetano package for the guide. Its human summary
|
||||
// comes from the Big Picture program (BigPicture), never copied here.
|
||||
type PackageSpec struct {
|
||||
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"` // product.<name>
|
||||
Registry string `yaml:"registry,omitempty" json:"registry,omitempty"` // yetano.app/yetano/<pkg>
|
||||
Microsite string `yaml:"microsite,omitempty" json:"microsite,omitempty"` // path below webBase
|
||||
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||
Modules []Module `yaml:"modules" json:"modules"`
|
||||
// Sources back every claim about what the package can do (ANA-02).
|
||||
Sources []string `yaml:"sources" json:"sources"`
|
||||
}
|
||||
|
||||
// Module is one functional part of a package (a yamase-* program, ...).
|
||||
type Module struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Program string `yaml:"program,omitempty" json:"program,omitempty"` // binary name
|
||||
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` // daemon | cli | plugin | library
|
||||
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"`
|
||||
Requires []string `yaml:"requires,omitempty" json:"requires,omitempty"` // capabilities
|
||||
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
|
||||
// Priority orders providers of the same capability (higher first).
|
||||
Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`
|
||||
// Manual is the knowledge source with this module's manual, if any.
|
||||
Manual string `yaml:"manual,omitempty" json:"manual,omitempty"`
|
||||
Doctor []string `yaml:"doctor,omitempty" json:"doctor,omitempty"` // commands that check it
|
||||
Sources []string `yaml:"sources,omitempty" json:"sources,omitempty"`
|
||||
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||
}
|
||||
|
||||
// ---- Profiles -------------------------------------------------------------
|
||||
|
||||
// ProfileSpec is a recommended way to run one package.
|
||||
type ProfileSpec struct {
|
||||
Extends string `yaml:"extends,omitempty" json:"extends,omitempty"`
|
||||
Modules map[string]string `yaml:"modules,omitempty" json:"modules,omitempty"` // module -> enabled|disabled
|
||||
Parameters []string `yaml:"parameters,omitempty" json:"parameters,omitempty"`
|
||||
Config []Fragment `yaml:"config,omitempty" json:"config,omitempty"`
|
||||
Recommendations []Recommendation `yaml:"recommendations,omitempty" json:"recommendations,omitempty"`
|
||||
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||
}
|
||||
|
||||
// Recommendation names something worth adding, with the reason.
|
||||
type Recommendation struct {
|
||||
Package string `yaml:"package,omitempty" json:"package,omitempty"`
|
||||
Capability string `yaml:"capability,omitempty" json:"capability,omitempty"`
|
||||
Reason string `yaml:"reason" json:"reason"`
|
||||
}
|
||||
|
||||
// Fragment is a typed YAML piece for one generated file (ADR-0005).
|
||||
type Fragment struct {
|
||||
ID string `yaml:"id,omitempty" json:"id,omitempty"`
|
||||
File string `yaml:"file" json:"file"`
|
||||
// Module: the fragment only applies while this module of the file's
|
||||
// package is enabled (a disabled program gets no configuration).
|
||||
Module string `yaml:"module,omitempty" json:"module,omitempty"`
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
Set yaml.Node `yaml:"set" json:"-"`
|
||||
}
|
||||
|
||||
// ---- Solutions and tasks ----------------------------------------------------
|
||||
|
||||
// SolutionSpec is a complete use case. Tasks use the same structure.
|
||||
type SolutionSpec struct {
|
||||
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` // tasks: read-only|generate|diagnostic|planning|mutating|deployment|maintenance
|
||||
Goals []string `yaml:"goals,omitempty" json:"goals,omitempty"`
|
||||
Scenarios []string `yaml:"scenarios,omitempty" json:"scenarios,omitempty"`
|
||||
NotFor []string `yaml:"notFor,omitempty" json:"notFor,omitempty"`
|
||||
AppliesTo *AppliesTo `yaml:"appliesTo,omitempty" json:"appliesTo,omitempty"`
|
||||
Capabilities CapSets `yaml:"capabilities,omitempty" json:"capabilities"`
|
||||
Packages []PackageUse `yaml:"packages,omitempty" json:"packages"`
|
||||
Questions []Question `yaml:"questions,omitempty" json:"questions"`
|
||||
Rules []Rule `yaml:"rules,omitempty" json:"rules,omitempty"`
|
||||
Config []Fragment `yaml:"configuration,omitempty" json:"-"`
|
||||
Steps []Step `yaml:"steps,omitempty" json:"steps,omitempty"`
|
||||
Requirements []Check `yaml:"requirements,omitempty" json:"requirements,omitempty"`
|
||||
Architecture Architecture `yaml:"architecture,omitempty" json:"architecture"`
|
||||
References References `yaml:"references,omitempty" json:"references"`
|
||||
Related []string `yaml:"related,omitempty" json:"related,omitempty"`
|
||||
Operations []string `yaml:"operations,omitempty" json:"operations,omitempty"`
|
||||
Lifecycle Lifecycle `yaml:"lifecycle,omitempty" json:"lifecycle"`
|
||||
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||
Sources []string `yaml:"sources,omitempty" json:"sources,omitempty"`
|
||||
}
|
||||
|
||||
// AppliesTo limits a task to solutions/capabilities (applicableWhen).
|
||||
type AppliesTo struct {
|
||||
Solutions []string `yaml:"solutions,omitempty" json:"solutions,omitempty"`
|
||||
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||
}
|
||||
|
||||
// CapSets are the capabilities a solution needs.
|
||||
type CapSets struct {
|
||||
Required []string `yaml:"required,omitempty" json:"required,omitempty"`
|
||||
Recommended []string `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||
Optional []string `yaml:"optional,omitempty" json:"optional,omitempty"`
|
||||
}
|
||||
|
||||
// PackageUse puts a package into a solution, optionally under a condition.
|
||||
type PackageUse struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Profile string `yaml:"profile,omitempty" json:"profile,omitempty"`
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
Role string `yaml:"role,omitempty" json:"role,omitempty"` // core | optional
|
||||
Recommended bool `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// Level orders the wizard modes.
|
||||
type Level string
|
||||
|
||||
const (
|
||||
LevelQuick Level = "quick"
|
||||
LevelGuided Level = "guided"
|
||||
LevelAdvanced Level = "advanced"
|
||||
)
|
||||
|
||||
// Rank is the order of the modes (quick < guided < advanced).
|
||||
func (l Level) Rank() int {
|
||||
switch l {
|
||||
case LevelGuided:
|
||||
return 1
|
||||
case LevelAdvanced:
|
||||
return 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Question is one wizard question.
|
||||
type Question struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Type string `yaml:"type" json:"type"`
|
||||
Item string `yaml:"item,omitempty" json:"item,omitempty"` // list element type
|
||||
Group string `yaml:"group,omitempty" json:"group,omitempty"`
|
||||
Level Level `yaml:"level,omitempty" json:"level,omitempty"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Help string `yaml:"help,omitempty" json:"help,omitempty"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Decide string `yaml:"decide,omitempty" json:"decide,omitempty"` // "Help me decide" text
|
||||
Placeholder string `yaml:"placeholder,omitempty" json:"placeholder,omitempty"`
|
||||
Examples []string `yaml:"examples,omitempty" json:"examples,omitempty"`
|
||||
Default any `yaml:"default,omitempty" json:"default,omitempty"`
|
||||
DefaultWhen []CondValue `yaml:"defaultWhen,omitempty" json:"defaultWhen,omitempty"`
|
||||
Recommended any `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||
Required bool `yaml:"required,omitempty" json:"required,omitempty"`
|
||||
RequiredWhen Cond `yaml:"requiredWhen,omitempty" json:"requiredWhen,omitempty"`
|
||||
VisibleWhen Cond `yaml:"visibleWhen,omitempty" json:"visibleWhen,omitempty"`
|
||||
InstanceSpecific bool `yaml:"instanceSpecific,omitempty" json:"instanceSpecific,omitempty"`
|
||||
Options []Option `yaml:"options,omitempty" json:"options,omitempty"`
|
||||
Validation Validation `yaml:"validation,omitempty" json:"validation"`
|
||||
ValidateWhen []CondCheck `yaml:"validateWhen,omitempty" json:"validateWhen,omitempty"`
|
||||
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||
Warnings []CondText `yaml:"warnings,omitempty" json:"warnings,omitempty"`
|
||||
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||
}
|
||||
|
||||
// Option is one choice of a select/multiselect question.
|
||||
type Option struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Recommended bool `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
|
||||
SupportNote string `yaml:"supportNote,omitempty" json:"supportNote,omitempty"`
|
||||
EnabledWhen Cond `yaml:"enabledWhen,omitempty" json:"enabledWhen,omitempty"`
|
||||
Effects Effects `yaml:",inline" json:"effects"`
|
||||
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||
}
|
||||
|
||||
// Effects are what a rule or a chosen option does (RULE-01).
|
||||
type Effects struct {
|
||||
Requires *Targets `yaml:"requires,omitempty" json:"requires,omitempty"`
|
||||
Excludes *Targets `yaml:"excludes,omitempty" json:"excludes,omitempty"`
|
||||
Conflicts *Targets `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
|
||||
Implies *Targets `yaml:"implies,omitempty" json:"implies,omitempty"`
|
||||
Recommends *Targets `yaml:"recommends,omitempty" json:"recommends,omitempty"`
|
||||
Discourages *Targets `yaml:"discourages,omitempty" json:"discourages,omitempty"`
|
||||
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"` // capabilities provided outside Yetano
|
||||
}
|
||||
|
||||
// Targets lists packages, capabilities, modules and option answers.
|
||||
type Targets struct {
|
||||
Packages []string `yaml:"packages,omitempty" json:"packages,omitempty"`
|
||||
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||
Modules []string `yaml:"modules,omitempty" json:"modules,omitempty"` // pkg/module
|
||||
Answers map[string]any `yaml:"answers,omitempty" json:"answers,omitempty"` // question -> option
|
||||
}
|
||||
|
||||
// Rule is a declarative rule of a solution or task.
|
||||
type Rule struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
Effects Effects `yaml:",inline" json:"effects"`
|
||||
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` // for warnings: info|warning|error
|
||||
Message string `yaml:"message,omitempty" json:"message,omitempty"`
|
||||
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||
Source string `yaml:"source,omitempty" json:"source,omitempty"`
|
||||
}
|
||||
|
||||
// Validation constrains an answer.
|
||||
type Validation struct {
|
||||
Min *float64 `yaml:"min,omitempty" json:"min,omitempty"`
|
||||
Max *float64 `yaml:"max,omitempty" json:"max,omitempty"`
|
||||
MinItems int `yaml:"minItems,omitempty" json:"minItems,omitempty"`
|
||||
MaxItems int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"`
|
||||
MinLength int `yaml:"minLength,omitempty" json:"minLength,omitempty"`
|
||||
MaxLength int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"`
|
||||
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"`
|
||||
Message string `yaml:"message,omitempty" json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// CondValue is a conditional default.
|
||||
type CondValue struct {
|
||||
When Cond `yaml:"when" json:"when"`
|
||||
Value any `yaml:"value" json:"value"`
|
||||
}
|
||||
|
||||
// CondText is a conditional message.
|
||||
type CondText struct {
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"`
|
||||
Text string `yaml:"text" json:"text"`
|
||||
}
|
||||
|
||||
// CondCheck is a conditional validation (validateWhen).
|
||||
type CondCheck struct {
|
||||
When Cond `yaml:"when" json:"when"`
|
||||
Validation Validation `yaml:"validation" json:"validation"`
|
||||
}
|
||||
|
||||
// Step is a setup step that is not configuration (yamase-ctl directory
|
||||
// domain add ...). The engine only lists steps; it never runs them.
|
||||
type Step struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
Package string `yaml:"package,omitempty" json:"package,omitempty"`
|
||||
Module string `yaml:"module,omitempty" json:"module,omitempty"`
|
||||
ForEach string `yaml:"forEach,omitempty" json:"forEach,omitempty"` // list parameter; ${item}
|
||||
Run string `yaml:"run,omitempty" json:"run,omitempty"`
|
||||
Note string `yaml:"note,omitempty" json:"note,omitempty"`
|
||||
Phase string `yaml:"phase,omitempty" json:"phase,omitempty"` // install | configure | data | dns | start | verify
|
||||
Mutating bool `yaml:"mutating,omitempty" json:"mutating,omitempty"`
|
||||
Reversible *bool `yaml:"reversible,omitempty" json:"reversible,omitempty"`
|
||||
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||
}
|
||||
|
||||
// Check is a requirement or doctor check (DR-01).
|
||||
type Check struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Kind string `yaml:"kind" json:"kind"` // os | arch | port | dns | tls | program | command | manual
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` // error | warning | info
|
||||
Local bool `yaml:"local,omitempty" json:"local,omitempty"` // needs the target system
|
||||
Params map[string]string `yaml:"params,omitempty" json:"params,omitempty"`
|
||||
Run string `yaml:"run,omitempty" json:"run,omitempty"` // command the operator can run
|
||||
Hint string `yaml:"hint,omitempty" json:"hint,omitempty"`
|
||||
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||
}
|
||||
|
||||
// Architecture adds solution-specific nodes and edges to the resolved graph.
|
||||
type Architecture struct {
|
||||
Nodes []ArchNode `yaml:"nodes,omitempty" json:"nodes,omitempty"`
|
||||
Edges []ArchEdge `yaml:"edges,omitempty" json:"edges,omitempty"`
|
||||
}
|
||||
|
||||
// ArchNode is an extra node (clients, external services, storage, ...).
|
||||
type ArchNode struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Type string `yaml:"type" json:"type"` // client | external | storage | network | identity | target
|
||||
Title string `yaml:"title" json:"title"`
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
}
|
||||
|
||||
// ArchEdge connects two nodes; IDs are node IDs, "pkg:<id>", "mod:<pkg>/<id>" or "cap:<id>".
|
||||
type ArchEdge struct {
|
||||
From string `yaml:"from" json:"from"`
|
||||
To string `yaml:"to" json:"to"`
|
||||
Type string `yaml:"type" json:"type"`
|
||||
Label string `yaml:"label,omitempty" json:"label,omitempty"`
|
||||
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||
}
|
||||
|
||||
// References are typed yetano: references.
|
||||
type References struct {
|
||||
Manuals []string `yaml:"manuals,omitempty" json:"manuals,omitempty"`
|
||||
Microsites []string `yaml:"microsites,omitempty" json:"microsites,omitempty"`
|
||||
BigPicture []string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||
Other []string `yaml:"other,omitempty" json:"other,omitempty"`
|
||||
}
|
||||
|
||||
// All returns every reference in a stable order.
|
||||
func (r References) All() []string {
|
||||
var out []string
|
||||
out = append(out, r.Manuals...)
|
||||
out = append(out, r.Microsites...)
|
||||
out = append(out, r.BigPicture...)
|
||||
out = append(out, r.Other...)
|
||||
return out
|
||||
}
|
||||
|
||||
// Lifecycle says which lifecycle operations a solution supports.
|
||||
type Lifecycle struct {
|
||||
Configure bool `yaml:"configure,omitempty" json:"configure"`
|
||||
Validate bool `yaml:"validate,omitempty" json:"validate"`
|
||||
Plan bool `yaml:"plan,omitempty" json:"plan"`
|
||||
Deploy string `yaml:"deploy,omitempty" json:"deploy,omitempty"` // no | optional | yes
|
||||
Doctor bool `yaml:"doctor,omitempty" json:"doctor"`
|
||||
Update string `yaml:"update,omitempty" json:"update,omitempty"`
|
||||
}
|
||||
|
||||
// ---- Examples, presets, instances ------------------------------------------
|
||||
|
||||
// ExampleSpec is a curated answer set for a solution (EX-01). Examples
|
||||
// are generated by the engine like any session, so they cannot drift.
|
||||
type ExampleSpec struct {
|
||||
Solution string `yaml:"solution" json:"solution"`
|
||||
Mode Level `yaml:"mode,omitempty" json:"mode,omitempty"`
|
||||
Scenario string `yaml:"scenario,omitempty" json:"scenario,omitempty"`
|
||||
Parameters map[string]any `yaml:"parameters" json:"parameters"`
|
||||
Tested bool `yaml:"tested,omitempty" json:"tested"`
|
||||
}
|
||||
|
||||
// ---- Knowledge sources --------------------------------------------------------
|
||||
|
||||
// KnowledgeSourceSpec points at existing documentation (KNOW-04/06): the
|
||||
// documents stay where they are; sections are extracted from headings.
|
||||
type KnowledgeSourceSpec struct {
|
||||
Package string `yaml:"package" json:"package"`
|
||||
Type string `yaml:"type" json:"type"` // manual
|
||||
Format string `yaml:"format" json:"format"` // markdown
|
||||
Repository string `yaml:"repository" json:"repository"`
|
||||
Root string `yaml:"root,omitempty" json:"root,omitempty"` // dir with README.md and docs/
|
||||
Program string `yaml:"program,omitempty" json:"program,omitempty"`
|
||||
Layout string `yaml:"layout,omitempty" json:"layout,omitempty"` // core-manual (README + docs/**) | docs-tree
|
||||
Web string `yaml:"web,omitempty" json:"web,omitempty"` // URL base for topics, {slug} placeholder
|
||||
Exclude []string `yaml:"exclude,omitempty" json:"exclude,omitempty"`
|
||||
Topics []SourceTopic `yaml:"topics,omitempty" json:"topics,omitempty"`
|
||||
}
|
||||
|
||||
// SourceTopic attaches capabilities/modules to one manual topic.
|
||||
type SourceTopic struct {
|
||||
Slug string `yaml:"slug" json:"slug"`
|
||||
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||
Modules []string `yaml:"modules,omitempty" json:"modules,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// SchemaKinds maps a schema file name to the manifest it describes.
|
||||
var SchemaKinds = map[string]struct {
|
||||
Kind string
|
||||
Spec any
|
||||
}{
|
||||
"catalog": {KindCatalog, CatalogSpec{}},
|
||||
"capabilities": {KindCapabilities, CapabilitiesSpec{}},
|
||||
"package": {KindPackage, PackageSpec{}},
|
||||
"profile": {KindProfile, ProfileSpec{}},
|
||||
"solution": {KindSolution, SolutionSpec{}},
|
||||
"example": {KindExample, ExampleSpec{}},
|
||||
"knowledge-source": {KindKnowledgeSource, KnowledgeSourceSpec{}},
|
||||
}
|
||||
|
||||
// JSONSchema returns the JSON Schema (draft 2020-12) of a manifest kind,
|
||||
// derived from the Go types the loader decodes with KnownFields -- so the
|
||||
// editor's check and the loader cannot disagree (CAT-05). Several
|
||||
// documents per file ("---") are not expressible in JSON Schema; the
|
||||
// schema describes one document. Solution and Task share a schema.
|
||||
func JSONSchema(name string) map[string]any {
|
||||
k := SchemaKinds[name]
|
||||
kinds := []any{k.Kind}
|
||||
if k.Kind == KindSolution {
|
||||
kinds = append(kinds, KindTask)
|
||||
}
|
||||
return map[string]any{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://yetano.app/schema/solutions/" + name + ".schema.json",
|
||||
"title": "Yetano " + k.Kind + " manifest",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": []any{"apiVersion", "kind", "metadata"},
|
||||
"properties": map[string]any{
|
||||
"apiVersion": map[string]any{"const": APIVersion},
|
||||
"kind": map[string]any{"enum": kinds},
|
||||
"metadata": schemaOf(reflect.TypeOf(Meta{}), 0),
|
||||
"spec": schemaOf(reflect.TypeOf(k.Spec), 0),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
nodeType = reflect.TypeOf(yaml.Node{})
|
||||
condType = reflect.TypeOf(Cond{})
|
||||
)
|
||||
|
||||
func schemaOf(t reflect.Type, depth int) map[string]any {
|
||||
if depth > 12 {
|
||||
return map[string]any{}
|
||||
}
|
||||
if t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
switch {
|
||||
case t == nodeType:
|
||||
return map[string]any{"description": "native configuration (any YAML)"}
|
||||
case t == condType:
|
||||
return map[string]any{"type": "object", "description": "condition over earlier answers (ADR-0003)"}
|
||||
case t == reflect.TypeOf(Support("")):
|
||||
return map[string]any{"enum": []any{"supported", "experimental", "untested", "discouraged", "needs-prerequisites", "not-implemented", "not-supported", "impossible", "insecure"}}
|
||||
case t == reflect.TypeOf(Level("")):
|
||||
return map[string]any{"enum": []any{"quick", "guided", "advanced"}}
|
||||
}
|
||||
switch t.Kind() {
|
||||
case reflect.String:
|
||||
return map[string]any{"type": "string"}
|
||||
case reflect.Bool:
|
||||
return map[string]any{"type": "boolean"}
|
||||
case reflect.Int, reflect.Int64:
|
||||
return map[string]any{"type": "integer"}
|
||||
case reflect.Float64:
|
||||
return map[string]any{"type": "number"}
|
||||
case reflect.Slice:
|
||||
return map[string]any{"type": "array", "items": schemaOf(t.Elem(), depth+1)}
|
||||
case reflect.Map:
|
||||
return map[string]any{"type": "object", "additionalProperties": schemaOf(t.Elem(), depth+1)}
|
||||
case reflect.Interface:
|
||||
return map[string]any{}
|
||||
case reflect.Struct:
|
||||
props := map[string]any{}
|
||||
addFields(t, props, depth)
|
||||
return map[string]any{"type": "object", "additionalProperties": false, "properties": props}
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
func addFields(t reflect.Type, props map[string]any, depth int) {
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
f := t.Field(i)
|
||||
if !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
tag := f.Tag.Get("yaml")
|
||||
name, opts, _ := strings.Cut(tag, ",")
|
||||
if name == "-" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(opts, "inline") {
|
||||
addFields(f.Type, props, depth)
|
||||
continue
|
||||
}
|
||||
if name == "" {
|
||||
name = strings.ToLower(f.Name)
|
||||
}
|
||||
props[name] = schemaOf(f.Type, depth+1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// QuestionTypes are the built-in question types (WIZ-03).
|
||||
var QuestionTypes = map[string]bool{
|
||||
"boolean": true, "select": true, "multiselect": true,
|
||||
"string": true, "text": true, "integer": true, "decimal": true,
|
||||
"date": true, "duration": true, "hostname": true, "domain": true,
|
||||
"email": true, "ip": true, "cidr": true, "port": true, "url": true,
|
||||
"path": true, "dir": true, "list": true, "keyvalue": true,
|
||||
"package": true, "profile": true, "capability": true, "provider": true,
|
||||
"target": true, "secret": true,
|
||||
}
|
||||
|
||||
// ListItemTypes may be used as list items.
|
||||
var ListItemTypes = map[string]bool{
|
||||
"string": true, "hostname": true, "domain": true, "email": true, "ip": true,
|
||||
"cidr": true, "port": true, "url": true, "path": true, "integer": true,
|
||||
}
|
||||
|
||||
var idRE = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]*[a-z0-9]$|^[a-z0-9]$`)
|
||||
var questionIDRE = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`)
|
||||
|
||||
// SafeRelPath reports whether p is a clean relative slash path without
|
||||
// "..", usable as an output file name (SEC-03).
|
||||
func SafeRelPath(p string) bool {
|
||||
if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, "\\") || strings.Contains(p, ":") {
|
||||
return false
|
||||
}
|
||||
if path.Clean(p) != p {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == ".." || part == "." || part == "" || strings.HasPrefix(part, ".") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Validate checks the catalog's internal consistency and returns all
|
||||
// issues (load issues included). Reference targets outside the catalog
|
||||
// (manual sections, microsites) are checked by knowledge.Lint.
|
||||
func (c *Catalog) Validate() []Issue {
|
||||
v := &validator{c: c, issues: append([]Issue(nil), c.Issues...)}
|
||||
v.root()
|
||||
for _, id := range SortedIDs(c.Capabilities) {
|
||||
v.capability(c.Capabilities[id])
|
||||
}
|
||||
for _, id := range SortedIDs(c.Packages) {
|
||||
v.pkg(c.Packages[id])
|
||||
}
|
||||
for _, id := range SortedIDs(c.Profiles) {
|
||||
v.profile(c.Profiles[id])
|
||||
}
|
||||
for _, id := range SortedIDs(c.Solutions) {
|
||||
v.solution(c.Solutions[id])
|
||||
}
|
||||
for _, id := range SortedIDs(c.Tasks) {
|
||||
v.solution(c.Tasks[id])
|
||||
}
|
||||
for _, id := range SortedIDs(c.Examples) {
|
||||
v.example(c.Examples[id])
|
||||
}
|
||||
for _, id := range SortedIDs(c.Sources) {
|
||||
v.source(c.Sources[id])
|
||||
}
|
||||
return v.issues
|
||||
}
|
||||
|
||||
type validator struct {
|
||||
c *Catalog
|
||||
issues []Issue
|
||||
}
|
||||
|
||||
func (v *validator) errf(e *Entity, id, code, f string, a ...any) {
|
||||
i := Issue{Severity: "error", ID: id, Code: code, Message: fmt.Sprintf(f, a...)}
|
||||
if e != nil {
|
||||
i.File, i.Line = e.File, e.Line
|
||||
}
|
||||
v.issues = append(v.issues, i)
|
||||
}
|
||||
|
||||
func (v *validator) warnf(e *Entity, id, code, f string, a ...any) {
|
||||
i := Issue{Severity: "warning", ID: id, Code: code, Message: fmt.Sprintf(f, a...)}
|
||||
if e != nil {
|
||||
i.File, i.Line = e.File, e.Line
|
||||
}
|
||||
v.issues = append(v.issues, i)
|
||||
}
|
||||
|
||||
func (v *validator) root() {
|
||||
c := v.c
|
||||
if c.Spec.WebBase == "" {
|
||||
v.errf(nil, "catalog", "web-base", "catalog.yaml: spec.webBase is required")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, cat := range c.Spec.Categories {
|
||||
if seen[cat.ID] {
|
||||
v.errf(nil, cat.ID, "duplicate", "duplicate category %q", cat.ID)
|
||||
}
|
||||
seen[cat.ID] = true
|
||||
if cat.Topic != "" && c.BigPicture != nil {
|
||||
if _, ok := c.BigPicture.Topics[cat.Topic]; !ok {
|
||||
v.errf(nil, cat.ID, "bigpicture-ref", "category %q: unknown Big Picture topic %q", cat.ID, cat.Topic)
|
||||
}
|
||||
}
|
||||
if cat.Topic == "" && cat.Title == "" {
|
||||
v.errf(nil, cat.ID, "category", "category %q needs a topic or a title", cat.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) capability(cp *Capability) {
|
||||
e := &Entity{File: v.c.capFile[cp.ID]}
|
||||
if !idRE.MatchString(cp.ID) || strings.Contains(cp.ID, "@") {
|
||||
v.errf(e, cp.ID, "id", "capability ID %q: lower case, dot separated, no '@' (ADR-0003)", cp.ID)
|
||||
}
|
||||
if cp.Title == "" {
|
||||
v.errf(e, cp.ID, "required", "capability %q: title is required", cp.ID)
|
||||
}
|
||||
for _, r := range append(append([]string{}, cp.Requires...), cp.Conflicts...) {
|
||||
if _, ok := v.c.Capabilities[r]; !ok {
|
||||
v.errf(e, cp.ID, "capability-ref", "capability %q names unknown capability %q", cp.ID, r)
|
||||
}
|
||||
}
|
||||
for _, x := range cp.External {
|
||||
if !x.Support.Valid() {
|
||||
v.errf(e, cp.ID, "support", "external provider %q: unknown support %q", x.ID, x.Support)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) caps(e *Entity, id string, list []string) {
|
||||
for _, cp := range list {
|
||||
if _, ok := v.c.Capabilities[cp]; !ok {
|
||||
v.errf(e, id, "capability-ref", "unknown capability %q", cp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) pkg(p *Package) {
|
||||
e := &p.Entity
|
||||
if !idRE.MatchString(p.Meta.ID) {
|
||||
v.errf(e, p.Meta.ID, "id", "package ID %q is not valid", p.Meta.ID)
|
||||
}
|
||||
if p.Spec.BigPicture != "" && v.c.BigPicture != nil {
|
||||
if _, ok := v.c.BigPicture.Products[p.Spec.BigPicture]; !ok {
|
||||
v.errf(e, p.Meta.ID, "bigpicture-ref", "unknown Big Picture program %q", p.Spec.BigPicture)
|
||||
}
|
||||
}
|
||||
if p.Spec.BigPicture == "" && p.Meta.Summary == "" {
|
||||
v.errf(e, p.Meta.ID, "required", "package needs spec.bigpicture or metadata.summary")
|
||||
}
|
||||
if len(p.Spec.Sources) == 0 {
|
||||
v.errf(e, p.Meta.ID, "sources", "package claims need sources (ANA-02)")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, m := range p.Spec.Modules {
|
||||
if seen[m.ID] {
|
||||
v.errf(e, p.Meta.ID, "duplicate", "duplicate module %q", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
if !m.Support.Valid() {
|
||||
v.errf(e, p.Meta.ID, "support", "module %q: unknown support %q", m.ID, m.Support)
|
||||
}
|
||||
v.caps(e, p.Meta.ID+"/"+m.ID, m.Provides)
|
||||
v.caps(e, p.Meta.ID+"/"+m.ID, m.Requires)
|
||||
if m.Manual != "" {
|
||||
if _, ok := v.c.Sources[m.Manual]; !ok {
|
||||
v.errf(e, p.Meta.ID+"/"+m.ID, "source-ref", "unknown knowledge source %q", m.Manual)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) profile(p *Profile) {
|
||||
e := &p.Entity
|
||||
pkg, ok := v.c.Packages[p.Meta.Package]
|
||||
if !ok {
|
||||
v.errf(e, p.Key(), "package-ref", "profile of unknown package %q", p.Meta.Package)
|
||||
return
|
||||
}
|
||||
if _, err := v.c.ProfileChain(p.Meta.Package, p.Meta.ID); err != nil {
|
||||
v.errf(e, p.Key(), "extends", "%v", err)
|
||||
}
|
||||
for m, state := range p.Spec.Modules {
|
||||
if pkg.Module(m) == nil {
|
||||
v.errf(e, p.Key(), "module-ref", "unknown module %q", m)
|
||||
}
|
||||
if state != "enabled" && state != "disabled" {
|
||||
v.errf(e, p.Key(), "module-state", "module %q: want enabled or disabled, got %q", m, state)
|
||||
}
|
||||
}
|
||||
for _, f := range p.Spec.Config {
|
||||
v.fragment(e, p.Key(), f, nil, 0)
|
||||
}
|
||||
for _, r := range p.Spec.Recommendations {
|
||||
if r.Package != "" {
|
||||
if _, ok := v.c.Packages[r.Package]; !ok {
|
||||
v.errf(e, p.Key(), "package-ref", "recommendation names unknown package %q", r.Package)
|
||||
}
|
||||
}
|
||||
if r.Capability != "" {
|
||||
v.caps(e, p.Key(), []string{r.Capability})
|
||||
}
|
||||
if r.Reason == "" {
|
||||
v.errf(e, p.Key(), "reason", "a recommendation needs a reason (EX-03)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) fragment(e *Entity, id string, f Fragment, s *Solution, upto int) {
|
||||
if !SafeRelPath(f.File) {
|
||||
v.errf(e, id, "path", "fragment file %q: want a clean relative path", f.File)
|
||||
}
|
||||
if f.Set.Kind == 0 {
|
||||
v.errf(e, id, "fragment", "fragment for %q has no set", f.File)
|
||||
}
|
||||
if s != nil {
|
||||
v.cond(e, id, "fragment "+f.File, f.When, s, upto)
|
||||
} else if len(f.When) > 0 {
|
||||
v.errf(e, id, "fragment", "profile fragments cannot have conditions")
|
||||
}
|
||||
}
|
||||
|
||||
// cond checks a condition: well-formed and only naming questions before
|
||||
// index upto (ADR-0003).
|
||||
func (v *validator) cond(e *Entity, id, where string, c Cond, s *Solution, upto int) {
|
||||
if len(c) == 0 {
|
||||
return
|
||||
}
|
||||
if _, err := c.Eval(Env{Answers: map[string]any{}}); err != nil {
|
||||
v.errf(e, id, "condition", "%s: %v", where, err)
|
||||
}
|
||||
for _, ref := range c.Refs() {
|
||||
_, idx := s.Question(ref)
|
||||
if idx < 0 {
|
||||
v.errf(e, id, "condition", "%s: unknown question %q", where, ref)
|
||||
} else if idx >= upto {
|
||||
v.errf(e, id, "condition-order", "%s: names question %q, which is not asked before it", where, ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) targets(e *Entity, id string, t *Targets, s *Solution) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
for _, p := range t.Packages {
|
||||
if _, ok := v.c.Packages[p]; !ok {
|
||||
v.errf(e, id, "package-ref", "unknown package %q", p)
|
||||
}
|
||||
}
|
||||
v.caps(e, id, t.Capabilities)
|
||||
for _, m := range t.Modules {
|
||||
pkg, mod, _ := strings.Cut(m, "/")
|
||||
p, ok := v.c.Packages[pkg]
|
||||
if !ok || p.Module(mod) == nil {
|
||||
v.errf(e, id, "module-ref", "unknown module %q (want package/module)", m)
|
||||
}
|
||||
}
|
||||
for q, val := range t.Answers {
|
||||
qq, _ := s.Question(q)
|
||||
if qq == nil {
|
||||
v.errf(e, id, "question-ref", "unknown question %q", q)
|
||||
continue
|
||||
}
|
||||
v.optionValue(e, id, qq, val)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) optionValue(e *Entity, id string, q *Question, val any) {
|
||||
if q.Type != "select" && q.Type != "multiselect" {
|
||||
return
|
||||
}
|
||||
vals := asList(val)
|
||||
if _, isList := val.([]any); !isList {
|
||||
vals = []any{val}
|
||||
}
|
||||
for _, x := range vals {
|
||||
found := false
|
||||
for _, o := range q.Options {
|
||||
if Equal(o.ID, x) {
|
||||
found = true
|
||||
if !o.Support.Selectable() {
|
||||
v.errf(e, id, "default-unselectable", "question %q: value %q is %s and cannot be selected", q.ID, Scalar(x), o.Support)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
v.errf(e, id, "option-ref", "question %q has no option %q", q.ID, Scalar(x))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) solution(s *Solution) {
|
||||
e := &s.Entity
|
||||
id := s.Meta.ID
|
||||
if !idRE.MatchString(id) {
|
||||
v.errf(e, id, "id", "ID %q is not valid", id)
|
||||
}
|
||||
if s.Meta.Version == "" {
|
||||
v.errf(e, id, "version", "metadata.version is required (LOCK)")
|
||||
}
|
||||
if !s.Meta.Status.Valid() {
|
||||
v.errf(e, id, "support", "unknown status %q", s.Meta.Status)
|
||||
}
|
||||
if s.Spec.BigPicture != "" && v.c.BigPicture != nil {
|
||||
if _, ok := v.c.BigPicture.Stories[s.Spec.BigPicture]; !ok {
|
||||
v.errf(e, id, "bigpicture-ref", "unknown Big Picture goal %q", s.Spec.BigPicture)
|
||||
}
|
||||
}
|
||||
if s.Meta.Title == "" && s.Spec.BigPicture == "" {
|
||||
v.errf(e, id, "required", "title or spec.bigpicture is required")
|
||||
}
|
||||
if s.Kind == KindSolution && s.Meta.Category != "" {
|
||||
found := false
|
||||
for _, cat := range v.c.Spec.Categories {
|
||||
found = found || cat.ID == s.Meta.Category
|
||||
}
|
||||
if !found {
|
||||
v.errf(e, id, "category", "unknown category %q", s.Meta.Category)
|
||||
}
|
||||
}
|
||||
if s.Kind == KindTask {
|
||||
switch s.Spec.Kind {
|
||||
case "read-only", "generate", "diagnostic", "planning", "mutating", "deployment", "maintenance":
|
||||
default:
|
||||
v.errf(e, id, "task-kind", "spec.kind %q: want read-only, generate, diagnostic, planning, mutating, deployment or maintenance", s.Spec.Kind)
|
||||
}
|
||||
if s.Spec.AppliesTo != nil {
|
||||
for _, sid := range s.Spec.AppliesTo.Solutions {
|
||||
if _, ok := v.c.Solutions[sid]; !ok {
|
||||
v.errf(e, id, "solution-ref", "appliesTo: unknown solution %q", sid)
|
||||
}
|
||||
}
|
||||
v.caps(e, id, s.Spec.AppliesTo.Capabilities)
|
||||
}
|
||||
}
|
||||
v.caps(e, id, s.Spec.Capabilities.Required)
|
||||
v.caps(e, id, s.Spec.Capabilities.Recommended)
|
||||
v.caps(e, id, s.Spec.Capabilities.Optional)
|
||||
nq := len(s.Spec.Questions)
|
||||
for _, pu := range s.Spec.Packages {
|
||||
if _, ok := v.c.Packages[pu.ID]; !ok {
|
||||
v.errf(e, id, "package-ref", "unknown package %q", pu.ID)
|
||||
continue
|
||||
}
|
||||
if pu.Profile != "" {
|
||||
if _, ok := v.c.Profiles[pu.ID+"/"+pu.Profile]; !ok {
|
||||
v.errf(e, id, "profile-ref", "unknown profile %s/%s", pu.ID, pu.Profile)
|
||||
}
|
||||
}
|
||||
v.cond(e, id, "package "+pu.ID, pu.When, s, nq)
|
||||
}
|
||||
seenQ := map[string]bool{}
|
||||
for i := range s.Spec.Questions {
|
||||
q := &s.Spec.Questions[i]
|
||||
qid := id + "." + q.ID
|
||||
if !questionIDRE.MatchString(q.ID) {
|
||||
v.errf(e, qid, "id", "question ID %q: letters, digits and _ only", q.ID)
|
||||
}
|
||||
if seenQ[q.ID] {
|
||||
v.errf(e, qid, "duplicate", "duplicate question %q", q.ID)
|
||||
}
|
||||
seenQ[q.ID] = true
|
||||
if !QuestionTypes[q.Type] {
|
||||
v.errf(e, qid, "type", "unknown question type %q", q.Type)
|
||||
}
|
||||
if q.Type == "list" && !ListItemTypes[q.Item] {
|
||||
v.errf(e, qid, "type", "list needs item: one of the scalar types, got %q", q.Item)
|
||||
}
|
||||
if q.Title == "" {
|
||||
v.errf(e, qid, "required", "question needs a title")
|
||||
}
|
||||
switch q.Level {
|
||||
case "", LevelQuick, LevelGuided, LevelAdvanced:
|
||||
default:
|
||||
v.errf(e, qid, "level", "unknown level %q", q.Level)
|
||||
}
|
||||
if (q.Type == "select" || q.Type == "multiselect") && len(q.Options) == 0 {
|
||||
v.errf(e, qid, "options", "%s question without options", q.Type)
|
||||
}
|
||||
if q.Type == "secret" && q.Default != nil {
|
||||
v.errf(e, qid, "secret-default", "a secret question cannot have a default (SEC-01)")
|
||||
}
|
||||
seenO := map[string]bool{}
|
||||
anySelectable := false
|
||||
for _, o := range q.Options {
|
||||
if seenO[o.ID] {
|
||||
v.errf(e, qid, "duplicate", "duplicate option %q", o.ID)
|
||||
}
|
||||
seenO[o.ID] = true
|
||||
if !o.Support.Valid() {
|
||||
v.errf(e, qid, "support", "option %q: unknown support %q", o.ID, o.Support)
|
||||
}
|
||||
if o.Support.Selectable() {
|
||||
anySelectable = true
|
||||
} else if o.SupportNote == "" {
|
||||
v.errf(e, qid, "support-note", "option %q is %s: supportNote must say why", o.ID, o.Support)
|
||||
}
|
||||
if o.Recommended && o.Reason == "" {
|
||||
v.errf(e, qid, "reason", "recommended option %q needs a reason (EX-03)", o.ID)
|
||||
}
|
||||
v.cond(e, qid, "option "+o.ID+" enabledWhen", o.EnabledWhen, s, i)
|
||||
v.effects(e, qid+"/"+o.ID, o.Effects, s)
|
||||
}
|
||||
if len(q.Options) > 0 && !anySelectable {
|
||||
v.errf(e, qid, "unsatisfiable", "no option of %q can be selected", q.ID)
|
||||
}
|
||||
if q.Default != nil {
|
||||
v.optionValue(e, qid, q, q.Default)
|
||||
}
|
||||
for _, d := range q.DefaultWhen {
|
||||
v.cond(e, qid, "defaultWhen", d.When, s, i)
|
||||
v.optionValue(e, qid, q, d.Value)
|
||||
}
|
||||
v.cond(e, qid, "visibleWhen", q.VisibleWhen, s, i)
|
||||
v.cond(e, qid, "requiredWhen", q.RequiredWhen, s, i)
|
||||
for _, w := range q.ValidateWhen {
|
||||
v.cond(e, qid, "validateWhen", w.When, s, i)
|
||||
}
|
||||
for _, w := range q.Warnings {
|
||||
v.cond(e, qid, "warning", w.When, s, i+1)
|
||||
}
|
||||
if q.Validation.Pattern != "" {
|
||||
if _, err := regexp.Compile(q.Validation.Pattern); err != nil {
|
||||
v.errf(e, qid, "pattern", "validation pattern: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
seenR := map[string]bool{}
|
||||
for _, r := range s.Spec.Rules {
|
||||
rid := id + "#" + r.ID
|
||||
if r.ID == "" || seenR[r.ID] {
|
||||
v.errf(e, rid, "rule-id", "every rule needs a unique id")
|
||||
}
|
||||
seenR[r.ID] = true
|
||||
v.cond(e, rid, "rule when", r.When, s, nq)
|
||||
v.effects(e, rid, r.Effects, s)
|
||||
switch r.Severity {
|
||||
case "", "info", "warning", "error":
|
||||
default:
|
||||
v.errf(e, rid, "severity", "unknown severity %q", r.Severity)
|
||||
}
|
||||
}
|
||||
for i, f := range s.Spec.Config {
|
||||
fid := f.ID
|
||||
if fid == "" {
|
||||
fid = fmt.Sprint(i)
|
||||
}
|
||||
v.fragment(e, id+"#config:"+fid, f, s, nq)
|
||||
if pkg, _, ok := strings.Cut(f.File, "/"); !ok || v.c.Packages[pkg] == nil {
|
||||
v.errf(e, id, "fragment-file", "fragment file %q must start with a package directory", f.File)
|
||||
}
|
||||
}
|
||||
for _, st := range s.Spec.Steps {
|
||||
v.cond(e, id+"#step:"+st.ID, "step", st.When, s, nq)
|
||||
if st.ForEach == "$modules" && st.Package == "" {
|
||||
v.errf(e, id+"#step:"+st.ID, "step", "forEach: $modules needs a package")
|
||||
} else if st.ForEach != "" && st.ForEach != "$modules" {
|
||||
if q, _ := s.Question(st.ForEach); q == nil {
|
||||
v.errf(e, id+"#step:"+st.ID, "question-ref", "forEach names unknown question %q", st.ForEach)
|
||||
}
|
||||
}
|
||||
if st.Package != "" && v.c.Packages[st.Package] == nil {
|
||||
v.errf(e, id+"#step:"+st.ID, "package-ref", "unknown package %q", st.Package)
|
||||
}
|
||||
}
|
||||
for _, ck := range s.Spec.Requirements {
|
||||
v.cond(e, id+"#check:"+ck.ID, "requirement", ck.When, s, nq)
|
||||
}
|
||||
for _, n := range s.Spec.Architecture.Nodes {
|
||||
v.cond(e, id+"#node:"+n.ID, "node", n.When, s, nq)
|
||||
}
|
||||
for _, ed := range s.Spec.Architecture.Edges {
|
||||
v.cond(e, id+"#edge", "edge", ed.When, s, nq)
|
||||
}
|
||||
for _, r := range s.Spec.Related {
|
||||
if v.c.Lookup(r) == nil {
|
||||
v.errf(e, id, "related", "related: unknown solution or task %q", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) effects(e *Entity, id string, fx Effects, s *Solution) {
|
||||
for _, t := range []*Targets{fx.Requires, fx.Excludes, fx.Conflicts, fx.Implies, fx.Recommends, fx.Discourages} {
|
||||
v.targets(e, id, t, s)
|
||||
}
|
||||
v.caps(e, id, fx.Provides)
|
||||
}
|
||||
|
||||
func (v *validator) example(x *Example) {
|
||||
e := &x.Entity
|
||||
s, ok := v.c.Solutions[x.Spec.Solution]
|
||||
if !ok {
|
||||
s, ok = v.c.Tasks[x.Spec.Solution]
|
||||
}
|
||||
if !ok {
|
||||
v.errf(e, x.Key(), "solution-ref", "example of unknown solution %q", x.Spec.Solution)
|
||||
return
|
||||
}
|
||||
for k, val := range x.Spec.Parameters {
|
||||
q, _ := s.Question(k)
|
||||
if q == nil {
|
||||
v.errf(e, x.Key(), "question-ref", "unknown parameter %q", k)
|
||||
continue
|
||||
}
|
||||
v.optionValue(e, x.Key(), q, val)
|
||||
}
|
||||
if x.Meta.Title == "" {
|
||||
v.errf(e, x.Key(), "required", "an example needs a title")
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) source(k *KnowledgeSource) {
|
||||
e := &k.Entity
|
||||
if _, ok := v.c.Packages[k.Spec.Package]; !ok {
|
||||
v.errf(e, k.Meta.ID, "package-ref", "unknown package %q", k.Spec.Package)
|
||||
}
|
||||
if k.Spec.Type != "manual" {
|
||||
v.errf(e, k.Meta.ID, "type", "type %q: only manual is supported", k.Spec.Type)
|
||||
}
|
||||
if k.Spec.Format != "markdown" {
|
||||
v.errf(e, k.Meta.ID, "format", "format %q: only markdown is supported", k.Spec.Format)
|
||||
}
|
||||
switch k.Spec.Layout {
|
||||
case "", "core-manual", "docs-tree":
|
||||
default:
|
||||
v.errf(e, k.Meta.ID, "layout", "layout %q: want core-manual or docs-tree", k.Spec.Layout)
|
||||
}
|
||||
if k.Spec.Root != "" && !SafeRelPath(k.Spec.Root) {
|
||||
v.errf(e, k.Meta.ID, "path", "root %q: want a clean relative path", k.Spec.Root)
|
||||
}
|
||||
if !SafeRelPath(k.Spec.Repository) {
|
||||
v.errf(e, k.Meta.ID, "path", "repository %q: want a plain name", k.Spec.Repository)
|
||||
}
|
||||
for _, t := range k.Spec.Topics {
|
||||
v.caps(e, k.Meta.ID+"/"+t.Slug, t.Capabilities)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
// Package cli implements the guide's commands -- solution, task,
|
||||
// knowledge and open -- with yet's conventions (stdlib flag, --json on
|
||||
// every command, data on stdout, messages on stderr, stable exit codes).
|
||||
// The guide's own program calls Run from main; yet does not embed it.
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
"yetano.dev/yetano/core/solutions/engine"
|
||||
"yetano.dev/yetano/core/solutions/knowledge"
|
||||
"yetano.dev/yetano/core/solutions/store"
|
||||
)
|
||||
|
||||
// Exit codes, the same as yet's (yet/internal/cliutil). 0-3 are the
|
||||
// family-wide ones (docs/program-conventions.md in the meta-repo); 3 is
|
||||
// "interrupted" there, so "not found" is 7 (owner decision 2026-12-01,
|
||||
// it was 3 up to solutions/v0.1.0).
|
||||
const (
|
||||
ExitOK = 0
|
||||
ExitError = 1
|
||||
ExitUsage = 2
|
||||
ExitInterrupted = 3 // stopped by SIGINT/SIGTERM (the context was cancelled)
|
||||
ExitConflict = 4
|
||||
ExitNotFound = 7
|
||||
)
|
||||
|
||||
// Env is what the embedding program provides.
|
||||
type Env struct {
|
||||
Stdin io.Reader
|
||||
Stdout io.Writer
|
||||
Stderr io.Writer
|
||||
// Interactive: stdin and stdout are a terminal. Without it no command
|
||||
// ever waits for input (CLI-03).
|
||||
Interactive bool
|
||||
// Program is the command name in messages.
|
||||
Program string
|
||||
// Catalogs are default catalog directories (an installed knowledge
|
||||
// bundle); --catalog and $YETANO_SOLUTIONS_CATALOG come first.
|
||||
Catalogs []string
|
||||
// StoreDir keeps instances, sessions, presets (from core/paths).
|
||||
StoreDir string
|
||||
// Version is stamped into lock files.
|
||||
Version string
|
||||
// Getenv defaults to os.Getenv.
|
||||
Getenv func(string) string
|
||||
}
|
||||
|
||||
type app struct {
|
||||
env Env
|
||||
ctx context.Context
|
||||
catDir string
|
||||
locale string
|
||||
cat *catalog.Catalog
|
||||
ix *knowledge.Index
|
||||
eng *engine.Engine
|
||||
store store.Store
|
||||
jsonOut bool
|
||||
}
|
||||
|
||||
// exitErr carries an exit code.
|
||||
type exitErr struct {
|
||||
code int
|
||||
err error
|
||||
}
|
||||
|
||||
func (e exitErr) Error() string { return e.err.Error() }
|
||||
|
||||
func fail(code int, f string, a ...any) error { return exitErr{code, fmt.Errorf(f, a...)} }
|
||||
|
||||
// Run runs one command; args start with the command name.
|
||||
func Run(ctx context.Context, args []string, env Env) int {
|
||||
if env.Getenv == nil {
|
||||
env.Getenv = os.Getenv
|
||||
}
|
||||
if env.Program == "" {
|
||||
env.Program = "yetano-solutions"
|
||||
}
|
||||
if env.Stdin == nil {
|
||||
env.Stdin = os.Stdin
|
||||
}
|
||||
a := &app{env: env, ctx: ctx, store: store.Store{Dir: env.StoreDir}}
|
||||
if env.Version != "" {
|
||||
engine.GeneratorVersion = env.Version
|
||||
}
|
||||
err := a.dispatch(args)
|
||||
if err == nil {
|
||||
return ExitOK
|
||||
}
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return ExitOK
|
||||
}
|
||||
code := ExitError
|
||||
var ee exitErr
|
||||
if errors.As(err, &ee) {
|
||||
code = ee.code
|
||||
}
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
// whatever failed, it failed because we were told to stop
|
||||
code = ExitInterrupted
|
||||
case errors.Is(err, engine.ErrNotFound), errors.Is(err, store.ErrNotFound):
|
||||
code = ExitNotFound
|
||||
case errors.Is(err, engine.ErrModified):
|
||||
code = ExitConflict
|
||||
case errors.Is(err, engine.ErrIncomplete):
|
||||
code = ExitUsage
|
||||
}
|
||||
if a.jsonOut {
|
||||
enc := json.NewEncoder(env.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(map[string]any{"error": err.Error(), "code": code})
|
||||
} else if err.Error() != "" {
|
||||
fmt.Fprintf(env.Stderr, "error: %v\n", err)
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func (a *app) dispatch(args []string) error {
|
||||
// global flags before the command (--catalog dir solution list) move
|
||||
// behind it, where every subcommand's flag set parses them
|
||||
var lead []string
|
||||
for len(args) > 0 && strings.HasPrefix(args[0], "-") && args[0] != "-h" && args[0] != "--help" {
|
||||
lead = append(lead, args[0])
|
||||
name := strings.TrimLeft(args[0], "-")
|
||||
args = args[1:]
|
||||
if (name == "catalog" || name == "locale") && len(args) > 0 {
|
||||
lead = append(lead, args[0])
|
||||
args = args[1:]
|
||||
}
|
||||
}
|
||||
if len(lead) > 0 && len(args) > 0 {
|
||||
args = append(append([]string{}, args...), lead...)
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return a.usage("")
|
||||
}
|
||||
cmd, rest := args[0], args[1:]
|
||||
switch cmd {
|
||||
case "solution", "solutions":
|
||||
return a.solution(rest)
|
||||
case "task", "tasks":
|
||||
return a.task(rest)
|
||||
case "knowledge":
|
||||
return a.knowledge(rest)
|
||||
case "open":
|
||||
return a.open(rest)
|
||||
case "help", "-h", "--help":
|
||||
return a.usage("")
|
||||
}
|
||||
return a.usage(cmd)
|
||||
}
|
||||
|
||||
// Usage is the help text.
|
||||
const Usage = `Solutions Guide -- describe what you want to achieve, get native configuration:
|
||||
|
||||
solution list|search|show|setup|generate|validate|plan|doctor
|
||||
solution config show|explain, architecture, handbook, package
|
||||
solution instance list|show|export|import|delete
|
||||
solution preset list|save|show|export|import|delete
|
||||
solution catalog validate|test|coverage
|
||||
task list|search|show|run
|
||||
knowledge search|show|status|backlinks|coverage
|
||||
open <yetano:reference>
|
||||
|
||||
Common flags: --catalog DIR, --locale de, --json.
|
||||
`
|
||||
|
||||
func (a *app) usage(unknown string) error {
|
||||
if unknown != "" {
|
||||
fmt.Fprintf(a.env.Stderr, "unknown command %q\n\n", unknown)
|
||||
}
|
||||
fmt.Fprint(a.env.Stderr, Usage)
|
||||
if unknown != "" {
|
||||
return exitErr{ExitUsage, errors.New("")}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// flags makes a flag set with the common flags.
|
||||
func (a *app) flags(name string) *flag.FlagSet {
|
||||
fs := flag.NewFlagSet(a.env.Program+" "+name, flag.ContinueOnError)
|
||||
fs.SetOutput(a.env.Stderr)
|
||||
fs.StringVar(&a.catDir, "catalog", "", "catalog directory (default: $YETANO_SOLUTIONS_CATALOG, then the installed bundle)")
|
||||
fs.StringVar(&a.locale, "locale", "", "language of texts (en, de); default from $LANG")
|
||||
fs.BoolVar(&a.jsonOut, "json", false, "machine-readable output")
|
||||
return fs
|
||||
}
|
||||
|
||||
func (a *app) parse(fs *flag.FlagSet, args []string) error {
|
||||
// allow flags after positional arguments (yet does the same)
|
||||
var flags, pos []string
|
||||
for i := 0; i < len(args); i++ {
|
||||
s := args[i]
|
||||
if s == "--" {
|
||||
pos = append(pos, args[i+1:]...)
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(s, "-") && len(s) > 1 {
|
||||
flags = append(flags, s)
|
||||
name := strings.TrimLeft(s, "-")
|
||||
if !strings.Contains(name, "=") {
|
||||
if f := fs.Lookup(name); f != nil {
|
||||
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); !ok || !bf.IsBoolFlag() {
|
||||
if i+1 < len(args) {
|
||||
flags = append(flags, args[i+1])
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
pos = append(pos, s)
|
||||
}
|
||||
if err := fs.Parse(flags); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return err
|
||||
}
|
||||
return exitErr{ExitUsage, err}
|
||||
}
|
||||
return fs.Parse(append([]string{"--"}, pos...))
|
||||
}
|
||||
|
||||
// load finds and loads the catalog and the index.
|
||||
func (a *app) load() error {
|
||||
if a.cat != nil {
|
||||
return nil
|
||||
}
|
||||
if a.locale == "" {
|
||||
lang := a.env.Getenv("LANG")
|
||||
if strings.HasPrefix(lang, "de") {
|
||||
a.locale = "de"
|
||||
} else {
|
||||
a.locale = "en"
|
||||
}
|
||||
}
|
||||
candidates := []string{a.catDir, a.env.Getenv("YETANO_SOLUTIONS_CATALOG")}
|
||||
candidates = append(candidates, a.env.Catalogs...)
|
||||
dir := ""
|
||||
for _, c := range candidates {
|
||||
if c == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(c, "catalog.yaml")); err == nil {
|
||||
dir = c
|
||||
break
|
||||
}
|
||||
if c == a.catDir {
|
||||
return fail(ExitUsage, "--catalog %s: no catalog.yaml there", c)
|
||||
}
|
||||
}
|
||||
if dir == "" {
|
||||
return fail(ExitNotFound, "no solutions catalog found: pass --catalog <dir> or set YETANO_SOLUTIONS_CATALOG (the meta-repo's assets/solutions)")
|
||||
}
|
||||
c, err := catalog.Load(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cat = c
|
||||
a.ix = knowledge.Build(c)
|
||||
a.eng = engine.New(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *app) out() io.Writer { return a.env.Stdout }
|
||||
|
||||
func (a *app) printJSON(v any) error {
|
||||
enc := json.NewEncoder(a.env.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(v)
|
||||
}
|
||||
|
||||
func (a *app) say(f string, args ...any) { fmt.Fprintf(a.env.Stdout, f, args...) }
|
||||
|
||||
func (a *app) note(f string, args ...any) { fmt.Fprintf(a.env.Stderr, f, args...) }
|
||||
|
||||
// tr localizes a meta field.
|
||||
func (a *app) tr(t catalog.Translations, field, base string) string {
|
||||
return engine.Tr(t, a.locale, field, base)
|
||||
}
|
||||
|
||||
func (a *app) readLine(r *bufio.Reader) (string, error) {
|
||||
s, err := r.ReadString('\n')
|
||||
if err != nil && (s == "" || !errors.Is(err, io.EOF)) {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(s), nil
|
||||
}
|
||||
|
||||
func sortedKeys[V any](m map[string]V) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func wrap(s string, width int, indent string) string {
|
||||
words := strings.Fields(s)
|
||||
var b strings.Builder
|
||||
line := 0
|
||||
for _, w := range words {
|
||||
if line > 0 && line+len(w)+1 > width {
|
||||
b.WriteString("\n" + indent)
|
||||
line = 0
|
||||
} else if line > 0 {
|
||||
b.WriteByte(' ')
|
||||
line++
|
||||
}
|
||||
b.WriteString(w)
|
||||
line += len(w)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type result struct {
|
||||
code int
|
||||
stdout, stderr string
|
||||
}
|
||||
|
||||
func run(t *testing.T, store string, args ...string) result {
|
||||
t.Helper()
|
||||
var out, errb bytes.Buffer
|
||||
code := Run(context.Background(), args, Env{
|
||||
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
|
||||
Program: "yetano-solutions", StoreDir: store, Catalogs: []string{"../engine/testdata/cat"},
|
||||
Getenv: func(string) string { return "" },
|
||||
})
|
||||
return result{code, out.String(), errb.String()}
|
||||
}
|
||||
|
||||
// Scenario D: CI use without a terminal (ACC-D, CLI-03).
|
||||
func TestNonInteractive(t *testing.T) {
|
||||
store := t.TempDir()
|
||||
out := filepath.Join(t.TempDir(), "gen")
|
||||
// missing answers: exit 2, never a prompt
|
||||
r := run(t, store, "solution", "setup", "app-run", "--json")
|
||||
if r.code != ExitUsage || !strings.Contains(r.stdout, `"missing"`) || !strings.Contains(r.stdout, "hosts") {
|
||||
t.Fatalf("missing: %d %s %s", r.code, r.stdout, r.stderr)
|
||||
}
|
||||
// invalid value: exit 2
|
||||
if r := run(t, store, "solution", "setup", "app-run", "--set", "hosts=bad_host!"); r.code != ExitUsage {
|
||||
t.Errorf("invalid value: %d %s", r.code, r.stderr)
|
||||
}
|
||||
// unknown question: exit 2
|
||||
if r := run(t, store, "solution", "setup", "app-run", "--set", "nope=1"); r.code != ExitUsage {
|
||||
t.Errorf("unknown question: %d", r.code)
|
||||
}
|
||||
// unknown solution: exit 3
|
||||
if r := run(t, store, "solution", "show", "nope"); r.code != ExitNotFound {
|
||||
t.Errorf("unknown solution: %d", r.code)
|
||||
}
|
||||
// complete: files written, instance saved
|
||||
r = run(t, store, "solution", "setup", "app-run", "--set", "hosts=a.example.org", "--name", "prod", "--save", "--output", out)
|
||||
if r.code != 0 {
|
||||
t.Fatalf("setup: %d %s", r.code, r.stderr)
|
||||
}
|
||||
for _, f := range []string{"solution.yaml", "solution.lock.yaml", "config/app/app.yaml", "deployment-plan.yaml", "handbook/index.md", "architecture/graph.json"} {
|
||||
if _, err := os.Stat(filepath.Join(out, f)); err != nil {
|
||||
t.Errorf("missing %s", f)
|
||||
}
|
||||
}
|
||||
// regenerate from the manifest: same files, exit 0
|
||||
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out, "--locked"); r.code != 0 {
|
||||
t.Fatalf("regenerate: %d %s", r.code, r.stderr)
|
||||
}
|
||||
// a hand edit: exit 4 (conflict)
|
||||
os.WriteFile(filepath.Join(out, "config/app/app.yaml"), []byte("# mine\n"), 0o644)
|
||||
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out); r.code != ExitConflict {
|
||||
t.Errorf("hand edit: %d %s", r.code, r.stderr)
|
||||
}
|
||||
// stored instance works by name
|
||||
if r := run(t, store, "solution", "validate", "prod"); r.code != 0 {
|
||||
t.Errorf("validate prod: %d %s %s", r.code, r.stdout, r.stderr)
|
||||
}
|
||||
r = run(t, store, "solution", "instance", "list", "--json")
|
||||
var rows []map[string]string
|
||||
if err := json.Unmarshal([]byte(r.stdout), &rows); err != nil || len(rows) != 1 || rows[0]["status"] != "Configured" {
|
||||
t.Errorf("instance list: %s %v", r.stdout, err)
|
||||
}
|
||||
// preset from it; a new instance needs only the instance-specific answer
|
||||
if r := run(t, store, "solution", "preset", "save", "mine", "--from", "prod"); r.code != 0 {
|
||||
t.Fatalf("preset: %d %s", r.code, r.stderr)
|
||||
}
|
||||
if r := run(t, store, "solution", "setup", "app-run", "--preset", "mine", "--set", "hosts=b.example.org", "--json"); r.code != 0 {
|
||||
t.Errorf("setup with preset: %d %s", r.code, r.stderr)
|
||||
}
|
||||
// explain
|
||||
r = run(t, store, "solution", "config", "explain", "prod", "app/app.yaml", "limits.max")
|
||||
if r.code != 0 || !strings.Contains(r.stdout, "profile:app/base") {
|
||||
t.Errorf("explain: %d %s %s", r.code, r.stdout, r.stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateJSONIsTheAPI(t *testing.T) {
|
||||
store := t.TempDir()
|
||||
f := filepath.Join(t.TempDir(), "s.yaml")
|
||||
os.WriteFile(f, []byte("apiVersion: yetano.dev/v1\nkind: WizardSession\nmetadata: {name: x}\nspec:\n solution: {id: app-run}\n mode: guided\n parameters: {hosts: [a.example.org], identity: central}\n"), 0o644)
|
||||
r := run(t, store, "solution", "state", "--file", f)
|
||||
var st map[string]any
|
||||
if err := json.Unmarshal([]byte(r.stdout), &st); err != nil {
|
||||
t.Fatalf("%v: %s %s", err, r.stdout, r.stderr)
|
||||
}
|
||||
if st["complete"] != false || st["next"] != "realm" {
|
||||
t.Errorf("state: complete=%v next=%v", st["complete"], st["next"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchOpenKnowledge(t *testing.T) {
|
||||
store := t.TempDir()
|
||||
if r := run(t, store, "solution", "search", "run", "app"); r.code != 0 || !strings.Contains(r.stdout, "yetano:solution/app-run") {
|
||||
t.Errorf("search: %d %s", r.code, r.stdout)
|
||||
}
|
||||
if r := run(t, store, "open", "yetano:solution/app-run"); r.code != 0 {
|
||||
t.Errorf("open: %d %s", r.code, r.stderr)
|
||||
}
|
||||
if r := run(t, store, "open", "yetano:solution/missing"); r.code != ExitNotFound {
|
||||
t.Errorf("open missing: %d", r.code)
|
||||
}
|
||||
if r := run(t, store, "open", "not a ref"); r.code != ExitUsage {
|
||||
t.Errorf("open bad: %d", r.code)
|
||||
}
|
||||
if r := run(t, store, "solution", "catalog", "validate"); r.code != 0 {
|
||||
t.Errorf("catalog validate: %d %s %s", r.code, r.stdout, r.stderr)
|
||||
}
|
||||
if r := run(t, store, "nonsense"); r.code != ExitUsage {
|
||||
t.Errorf("unknown command: %d", r.code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveWizard(t *testing.T) {
|
||||
store := t.TempDir()
|
||||
out := filepath.Join(t.TempDir(), "gen")
|
||||
var o, e bytes.Buffer
|
||||
// size: Enter (default small), hosts: a.example.org, then actions: 6 export, 8 quit
|
||||
in := strings.NewReader("\na.example.org\n6\n8\n")
|
||||
code := Run(context.Background(), []string{"solution", "setup", "app-run", "--output", out}, Env{
|
||||
Stdin: in, Stdout: &o, Stderr: &e, Interactive: true, Program: "yetano-solutions", StoreDir: store,
|
||||
Catalogs: []string{"../engine/testdata/cat"}, Getenv: func(string) string { return "" },
|
||||
})
|
||||
if code != 0 {
|
||||
t.Fatalf("%d\n%s\n%s", code, o.String(), e.String())
|
||||
}
|
||||
for _, want := range []string{"[1/2] How big?", "(recommended)", "YOUR SOLUTION", "Actions:"} {
|
||||
if !strings.Contains(o.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, o.String())
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(out, "config/app/app.yaml")); err != nil {
|
||||
t.Error("export did not write the configuration")
|
||||
}
|
||||
}
|
||||
|
||||
// Ctrl-C: a cancelled context is exit 3, the family-wide "interrupted"
|
||||
// (docs/program-conventions.md); "not found" moved to 7 for it.
|
||||
func TestInterrupted(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
var out, errb bytes.Buffer
|
||||
code := Run(ctx, []string{"solution", "show", "nope"}, Env{
|
||||
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
|
||||
Program: "yetano-solutions", StoreDir: t.TempDir(), Catalogs: []string{"../engine/testdata/cat"},
|
||||
Getenv: func(string) string { return "" },
|
||||
})
|
||||
if code != ExitInterrupted || ExitInterrupted != 3 || ExitNotFound != 7 {
|
||||
t.Fatalf("cancelled: exit %d (%s)", code, errb.String())
|
||||
}
|
||||
if r := run(t, t.TempDir(), "solution", "show", "nope"); r.code != 7 {
|
||||
t.Fatalf("not found: exit %d", r.code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/engine"
|
||||
)
|
||||
|
||||
// doctor runs a state's requirement checks on this machine (DR-01/03).
|
||||
// Only kinds it can really check get PASS/WARNING/ERROR; everything else
|
||||
// stays NOT_CHECKED with the command to run -- never a fake PASS.
|
||||
func (a *app) doctor(args []string) error {
|
||||
fs := a.flags("solution doctor")
|
||||
f := a.instFlags(fs)
|
||||
offline := fs.Bool("offline", false, "skip checks that need the network (DNS)")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(a.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
worst := 0
|
||||
for i := range st.Checks {
|
||||
c := &st.Checks[i]
|
||||
if c.Status == engine.CheckNotApplicable {
|
||||
continue
|
||||
}
|
||||
runCheck(ctx, c, *offline)
|
||||
if c.Status == engine.CheckError || c.Status == engine.CheckBlocked {
|
||||
worst = 1
|
||||
}
|
||||
}
|
||||
if a.jsonOut {
|
||||
if err := a.printJSON(map[string]any{"solution": st.Solution.ID, "instance": st.Instance, "checks": st.Checks}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
for _, c := range st.Checks {
|
||||
a.say("%-14s %s\n", c.Status, c.Title)
|
||||
if c.Note != "" {
|
||||
a.say("%-14s %s\n", "", wrap(c.Note, 62, strings.Repeat(" ", 15)))
|
||||
}
|
||||
if c.Status == engine.CheckNotChecked && c.Run != "" {
|
||||
a.say("%-14s run: %s\n", "", c.Run)
|
||||
}
|
||||
if (c.Status == engine.CheckWarning || c.Status == engine.CheckError) && c.Hint != "" {
|
||||
a.say("%-14s hint: %s\n", "", wrap(c.Hint, 60, strings.Repeat(" ", 21)))
|
||||
}
|
||||
}
|
||||
}
|
||||
if worst > 0 {
|
||||
return exitErr{ExitError, errors.New("")}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sevStatus(sev string) string {
|
||||
switch sev {
|
||||
case "warning":
|
||||
return engine.CheckWarning
|
||||
case "info":
|
||||
return engine.CheckInfo
|
||||
}
|
||||
return engine.CheckError
|
||||
}
|
||||
|
||||
func runCheck(ctx context.Context, c *engine.CheckResult, offline bool) {
|
||||
p := c.Params
|
||||
switch c.Kind {
|
||||
case "os":
|
||||
want := strings.Split(p["want"], ",")
|
||||
for _, w := range want {
|
||||
if w == runtime.GOOS {
|
||||
c.Status, c.Note = engine.CheckPass, runtime.GOOS
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Status, c.Note = sevStatus(c.Severity), runtime.GOOS+" is not supported"
|
||||
case "port":
|
||||
var busy, denied []string
|
||||
for _, port := range strings.Split(p["port"], ",") {
|
||||
l, err := net.Listen("tcp", ":"+strings.TrimSpace(port))
|
||||
if err == nil {
|
||||
l.Close()
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, syscall.EACCES) || errors.Is(err, os.ErrPermission) {
|
||||
denied = append(denied, port)
|
||||
} else {
|
||||
busy = append(busy, port)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(busy) > 0:
|
||||
c.Status, c.Note = sevStatus(c.Severity), "in use: "+strings.Join(busy, ", ")
|
||||
case len(denied) > 0:
|
||||
c.Status, c.Note = engine.CheckNotChecked, "no permission to test port(s) "+strings.Join(denied, ", ")+" as this user"
|
||||
default:
|
||||
c.Status = engine.CheckPass
|
||||
}
|
||||
case "file":
|
||||
var missing []string
|
||||
for _, f := range strings.Split(p["paths"], ",") {
|
||||
if _, err := os.Stat(strings.TrimSpace(f)); err != nil {
|
||||
missing = append(missing, f)
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
c.Status, c.Note = sevStatus(c.Severity), "missing: "+strings.Join(missing, ", ")
|
||||
} else {
|
||||
c.Status = engine.CheckPass
|
||||
}
|
||||
case "dns":
|
||||
if offline {
|
||||
c.Status, c.Note = engine.CheckNotChecked, "offline"
|
||||
return
|
||||
}
|
||||
dnsCheck(ctx, c)
|
||||
case "manual":
|
||||
c.Status = engine.CheckInfo
|
||||
c.Note = "check this yourself"
|
||||
default:
|
||||
c.Status = engine.CheckNotChecked
|
||||
}
|
||||
}
|
||||
|
||||
func dnsCheck(ctx context.Context, c *engine.CheckResult) {
|
||||
p := c.Params
|
||||
r := net.DefaultResolver
|
||||
var problems []string
|
||||
names := strings.Split(p["names"], ",")
|
||||
for _, name := range names {
|
||||
name = p["prefix"] + strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
qctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
switch strings.ToUpper(p["type"]) {
|
||||
case "MX":
|
||||
mx, err := r.LookupMX(qctx, name)
|
||||
if err != nil || len(mx) == 0 {
|
||||
problems = append(problems, name+": no MX record")
|
||||
break
|
||||
}
|
||||
if want := strings.TrimSuffix(p["want"], "."); want != "" {
|
||||
ok := false
|
||||
for _, m := range mx {
|
||||
ok = ok || strings.EqualFold(strings.TrimSuffix(m.Host, "."), want)
|
||||
}
|
||||
if !ok {
|
||||
problems = append(problems, fmt.Sprintf("%s: MX does not point to %s", name, want))
|
||||
}
|
||||
}
|
||||
case "A":
|
||||
if ips, err := r.LookupIPAddr(qctx, name); err != nil || len(ips) == 0 {
|
||||
problems = append(problems, name+": does not resolve")
|
||||
}
|
||||
case "TXT":
|
||||
txt, err := r.LookupTXT(qctx, name)
|
||||
found := false
|
||||
for _, t := range txt {
|
||||
found = found || strings.Contains(t, p["contains"])
|
||||
}
|
||||
if err != nil || !found {
|
||||
problems = append(problems, fmt.Sprintf("%s: no TXT record with %q", name, p["contains"]))
|
||||
}
|
||||
default:
|
||||
c.Status = engine.CheckNotChecked
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
c.Status, c.Note = engine.CheckNotChecked, "timed out"
|
||||
return
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
c.Status, c.Note = sevStatus(c.Severity), strings.Join(problems, "; ")
|
||||
return
|
||||
}
|
||||
c.Status = engine.CheckPass
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
"yetano.dev/yetano/core/solutions/engine"
|
||||
"yetano.dev/yetano/core/solutions/knowledge"
|
||||
"yetano.dev/yetano/core/solutions/ref"
|
||||
)
|
||||
|
||||
// ---- search --------------------------------------------------------------------
|
||||
|
||||
func (a *app) searchCmd(args []string, kinds []string) error {
|
||||
fs := a.flags("search")
|
||||
all := fs.Bool("all", false, "search everything (manuals, packages, Big Picture, ...)")
|
||||
limit := fs.Int("limit", 8, "hits per group")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() == 0 {
|
||||
return fail(ExitUsage, "usage: search <words>")
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if *all {
|
||||
kinds = nil
|
||||
}
|
||||
groups := a.ix.Search(strings.Join(fs.Args(), " "), knowledge.SearchOptions{Kinds: kinds, Limit: *limit, Locale: a.locale})
|
||||
if a.jsonOut {
|
||||
if groups == nil {
|
||||
groups = []knowledge.Group{}
|
||||
}
|
||||
return a.printJSON(groups)
|
||||
}
|
||||
if len(groups) == 0 {
|
||||
a.note("nothing found\n")
|
||||
return exitErr{ExitNotFound, errors.New("")}
|
||||
}
|
||||
for _, g := range groups {
|
||||
a.say("%s\n", g.Title)
|
||||
for _, h := range g.Hits {
|
||||
a.say(" %-44s %s\n", trunc(h.Title, 44), h.Ref)
|
||||
}
|
||||
a.say("\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func trunc(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
return string(r[:n-1]) + "…"
|
||||
}
|
||||
|
||||
// ---- instances --------------------------------------------------------------------
|
||||
|
||||
func (a *app) instance(args []string) error {
|
||||
if len(args) == 0 {
|
||||
args = []string{"list"}
|
||||
}
|
||||
fs := a.flags("solution instance " + args[0])
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
switch args[0] {
|
||||
case "list", "ls":
|
||||
inst, err := a.store.Instances()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sess, err := a.store.Sessions()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type row struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Solution string `json:"solution"`
|
||||
Status string `json:"status"`
|
||||
Updated string `json:"updated"`
|
||||
}
|
||||
var rows []row
|
||||
for _, list := range [][]string{inst, sess} {
|
||||
for _, n := range list {
|
||||
in, err := a.store.LoadInstance(n)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
status := "Draft"
|
||||
if in.Kind == catalog.KindInstance {
|
||||
status = "Configured"
|
||||
if a.load() == nil {
|
||||
if st, err := a.evaluate(in, nil); err == nil && !st.Complete {
|
||||
status = "Invalid"
|
||||
}
|
||||
}
|
||||
}
|
||||
rows = append(rows, row{n, in.Kind, in.Spec.Solution.ID, status, in.Metadata.Updated})
|
||||
}
|
||||
}
|
||||
if a.jsonOut {
|
||||
if rows == nil {
|
||||
rows = []row{}
|
||||
}
|
||||
return a.printJSON(rows)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
a.note("no saved solutions (save one with: %s solution setup <id> --save)\n", a.env.Program)
|
||||
}
|
||||
for _, r := range rows {
|
||||
a.say("%-24s %-14s %-11s %s\n", r.Name, r.Solution, r.Status, r.Updated)
|
||||
}
|
||||
return nil
|
||||
case "show", "export":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution instance %s <name>", a.env.Program, args[0])
|
||||
}
|
||||
in, err := a.store.LoadInstance(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(in)
|
||||
}
|
||||
b, err := engine.Marshal(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.say("%s", b)
|
||||
return nil
|
||||
case "import":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution instance import <file>", a.env.Program)
|
||||
}
|
||||
f, err := os.Open(fs.Arg(0))
|
||||
if err != nil {
|
||||
return fail(ExitNotFound, "%v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
in, err := engine.ReadInstance(f)
|
||||
if err != nil {
|
||||
return fail(ExitUsage, "%v", err)
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := a.evaluate(in, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.store.SaveInstance(in); err != nil {
|
||||
return err
|
||||
}
|
||||
a.note("imported %s\n", in.Metadata.Name)
|
||||
return nil
|
||||
case "delete", "rm":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution instance delete <name>", a.env.Program)
|
||||
}
|
||||
return a.store.DeleteInstance(fs.Arg(0))
|
||||
case "duplicate", "cp":
|
||||
if fs.NArg() != 2 {
|
||||
return fail(ExitUsage, "usage: %s solution instance duplicate <name> <new-name>", a.env.Program)
|
||||
}
|
||||
in, err := a.store.LoadInstance(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in.Metadata.Name, in.Metadata.Created = fs.Arg(1), ""
|
||||
return a.store.SaveInstance(in)
|
||||
case "favorite":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution instance favorite <name>", a.env.Program)
|
||||
}
|
||||
in, err := a.store.LoadInstance(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in.Metadata.Favorite = !in.Metadata.Favorite
|
||||
return a.store.SaveInstance(in)
|
||||
}
|
||||
return a.usage("solution instance " + args[0])
|
||||
}
|
||||
|
||||
// ---- presets ------------------------------------------------------------------------
|
||||
|
||||
func (a *app) preset(args []string) error {
|
||||
if len(args) == 0 {
|
||||
args = []string{"list"}
|
||||
}
|
||||
fs := a.flags("solution preset " + args[0])
|
||||
from := fs.String("from", "", "save: the instance to take the answers from")
|
||||
file := fs.String("file", "", "save: a solution.yaml to take the answers from")
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
switch args[0] {
|
||||
case "list", "ls":
|
||||
names, err := a.store.Presets()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.jsonOut {
|
||||
if names == nil {
|
||||
names = []string{}
|
||||
}
|
||||
return a.printJSON(names)
|
||||
}
|
||||
for _, n := range names {
|
||||
p, err := a.store.LoadPreset(n)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
a.say("%-24s %-14s %d answer(s)\n", n, p.Spec.Solution, len(p.Spec.Parameters))
|
||||
}
|
||||
return nil
|
||||
case "save":
|
||||
if fs.NArg() != 1 || (*from == "" && *file == "") {
|
||||
return fail(ExitUsage, "usage: %s solution preset save <name> --from <instance> | --file <solution.yaml>", a.env.Program)
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
var in *engine.Instance
|
||||
var err error
|
||||
if *file != "" {
|
||||
in, err = a.instanceFrom(*file, fs)
|
||||
} else {
|
||||
in, err = a.store.LoadInstance(*from)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s := a.cat.Lookup(in.Spec.Solution.ID)
|
||||
if s == nil {
|
||||
return fmt.Errorf("%w: solution %s", engine.ErrNotFound, in.Spec.Solution.ID)
|
||||
}
|
||||
p := engine.PresetFrom(fs.Arg(0), in, s)
|
||||
if err := a.store.SavePreset(p); err != nil {
|
||||
return err
|
||||
}
|
||||
a.note("saved preset %s (%d answers; instance-specific and secret answers are left out)\n", p.Metadata.Name, len(p.Spec.Parameters))
|
||||
return nil
|
||||
case "show", "export":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution preset show <name>", a.env.Program)
|
||||
}
|
||||
p, err := a.store.LoadPreset(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(p)
|
||||
}
|
||||
b, _ := engine.Marshal(p)
|
||||
a.say("%s", b)
|
||||
return nil
|
||||
case "import":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution preset import <file>", a.env.Program)
|
||||
}
|
||||
f, err := os.Open(fs.Arg(0))
|
||||
if err != nil {
|
||||
return fail(ExitNotFound, "%v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
p, err := engine.ReadPreset(f)
|
||||
if err != nil {
|
||||
return fail(ExitUsage, "%v", err)
|
||||
}
|
||||
return a.store.SavePreset(p)
|
||||
case "delete", "rm":
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution preset delete <name>", a.env.Program)
|
||||
}
|
||||
return a.store.DeletePreset(fs.Arg(0))
|
||||
}
|
||||
return a.usage("solution preset " + args[0])
|
||||
}
|
||||
|
||||
// ---- catalog --------------------------------------------------------------------------
|
||||
|
||||
func (a *app) catalogCmd(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fail(ExitUsage, "usage: %s solution catalog validate|test|coverage", a.env.Program)
|
||||
}
|
||||
fs := a.flags("solution catalog " + args[0])
|
||||
update := fs.Bool("update", false, "test: rewrite the golden files")
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
var ee exitErr
|
||||
if a.cat != nil && !errors.As(err, &ee) {
|
||||
// print every load issue, not just the first
|
||||
for _, i := range a.cat.Issues {
|
||||
a.note("%s\n", i)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
switch args[0] {
|
||||
case "validate", "lint":
|
||||
issues := knowledge.Lint(a.ix)
|
||||
errs := 0
|
||||
for _, i := range issues {
|
||||
if i.Severity == "error" {
|
||||
errs++
|
||||
}
|
||||
}
|
||||
if a.jsonOut {
|
||||
if issues == nil {
|
||||
issues = []catalog.Issue{}
|
||||
}
|
||||
_ = a.printJSON(issues)
|
||||
} else {
|
||||
for _, i := range issues {
|
||||
a.say("%-7s %s\n", strings.ToUpper(i.Severity), i)
|
||||
}
|
||||
a.note("%d solution(s), %d task(s), %d package(s), %d capabilities, %d manual topics: %d error(s), %d warning(s)\n",
|
||||
len(a.cat.Solutions), len(a.cat.Tasks), len(a.cat.Packages), len(a.cat.Capabilities), len(a.ix.Topics), errs, len(issues)-errs)
|
||||
}
|
||||
if errs > 0 {
|
||||
return exitErr{ExitError, errors.New("")}
|
||||
}
|
||||
return nil
|
||||
case "test":
|
||||
return a.catalogTest(*update)
|
||||
case "schema":
|
||||
dir := filepath.Join(a.cat.Root, "schema")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range sortedKeys(catalog.SchemaKinds) {
|
||||
b, err := json.MarshalIndent(catalog.JSONSchema(name), "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, name+".schema.json"), append(b, '\n'), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
a.note("wrote %d schemas to %s\n", len(catalog.SchemaKinds), dir)
|
||||
return nil
|
||||
case "coverage":
|
||||
cov := knowledge.ComputeCoverage(a.ix)
|
||||
if a.jsonOut {
|
||||
return a.printJSON(cov)
|
||||
}
|
||||
a.say("Yetano Knowledge Coverage (%d packages in the catalog)\n\n", cov.Packages)
|
||||
for _, m := range cov.Metrics {
|
||||
a.say(" %-38s %5.1f%% (%d/%d)\n", m.Name, m.Pct, m.Have, m.Total)
|
||||
}
|
||||
if len(cov.ProgramsWithout) > 0 {
|
||||
a.say("\nBig Picture programs not in the catalog yet: %s\n", strings.Join(cov.ProgramsWithout, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return a.usage("solution catalog " + args[0])
|
||||
}
|
||||
|
||||
// catalogTest evaluates every example, generates its output and compares
|
||||
// it with the golden files next to the solution (EX-02, QS-08). An example
|
||||
// that stops being complete or changes output fails (ACC-J).
|
||||
func (a *app) catalogTest(update bool) error {
|
||||
failed := 0
|
||||
for _, key := range catalog.SortedIDs(a.cat.Examples) {
|
||||
x := a.cat.Examples[key]
|
||||
s := a.cat.Lookup(x.Spec.Solution)
|
||||
in := engine.NewInstance(x.Meta.ID, s, x.Spec.Mode)
|
||||
in.Kind = catalog.KindInstance
|
||||
for k, v := range x.Spec.Parameters {
|
||||
in.Spec.Parameters[k] = v
|
||||
}
|
||||
in.Spec.Locale = "en"
|
||||
st, err := a.eng.Evaluate(in, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := a.eng.Generate(st, in, nil, false)
|
||||
if err != nil {
|
||||
a.say("FAIL %s: %v\n", key, err)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(a.cat.Root, filepath.FromSlash(path.Dir(path.Dir(x.File))), "testdata", x.Meta.ID)
|
||||
if update {
|
||||
if err := os.RemoveAll(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range out.Files {
|
||||
if f.Kind == "lock" {
|
||||
continue // hashes of the whole catalog: not stable across unrelated edits
|
||||
}
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(p, f.Content, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
a.say("UPDATED %s (%d files)\n", key, len(out.Files)-1)
|
||||
continue
|
||||
}
|
||||
var diffs []string
|
||||
want := map[string]bool{}
|
||||
for _, f := range out.Files {
|
||||
if f.Kind == "lock" {
|
||||
continue
|
||||
}
|
||||
want[f.Path] = true
|
||||
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f.Path)))
|
||||
if err != nil {
|
||||
diffs = append(diffs, f.Path+" (no golden file)")
|
||||
} else if !bytes.Equal(b, f.Content) {
|
||||
diffs = append(diffs, f.Path+" ("+firstDiff(b, f.Content)+")")
|
||||
}
|
||||
}
|
||||
_ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() {
|
||||
rel, _ := filepath.Rel(dir, p)
|
||||
if !want[filepath.ToSlash(rel)] {
|
||||
diffs = append(diffs, filepath.ToSlash(rel)+" (no longer generated)")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.Strings(diffs)
|
||||
if len(diffs) > 0 {
|
||||
a.say("FAIL %s\n", key)
|
||||
for _, d := range diffs {
|
||||
a.say(" %s\n", d)
|
||||
}
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
a.say("ok %s\n", key)
|
||||
}
|
||||
if failed > 0 {
|
||||
a.note("%d example(s) failed; after an intended change: make golden (catalog test --update) and review the diff\n", failed)
|
||||
return exitErr{ExitError, errors.New("")}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func firstDiff(a, b []byte) string {
|
||||
la, lb := strings.Split(string(a), "\n"), strings.Split(string(b), "\n")
|
||||
for i := 0; i < len(la) || i < len(lb); i++ {
|
||||
var x, y string
|
||||
if i < len(la) {
|
||||
x = la[i]
|
||||
}
|
||||
if i < len(lb) {
|
||||
y = lb[i]
|
||||
}
|
||||
if x != y {
|
||||
return fmt.Sprintf("line %d: golden %q, now %q", i+1, trunc(x, 50), trunc(y, 50))
|
||||
}
|
||||
}
|
||||
return "differs"
|
||||
}
|
||||
|
||||
// ---- knowledge, open ------------------------------------------------------------------
|
||||
|
||||
func (a *app) knowledge(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fail(ExitUsage, "usage: %s knowledge search|show|status|backlinks|coverage|validate", a.env.Program)
|
||||
}
|
||||
switch args[0] {
|
||||
case "search":
|
||||
return a.searchCmd(args[1:], nil)
|
||||
case "show":
|
||||
return a.open(args[1:])
|
||||
case "validate", "lint":
|
||||
return a.catalogCmd(append([]string{"validate"}, args[1:]...))
|
||||
case "coverage":
|
||||
return a.catalogCmd(append([]string{"coverage"}, args[1:]...))
|
||||
case "status", "index":
|
||||
fs := a.flags("knowledge " + args[0])
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
kinds := map[string]int{}
|
||||
for _, e := range a.ix.Entries {
|
||||
kinds[e.Kind]++
|
||||
}
|
||||
st := map[string]any{"catalog": a.cat.Root, "id": a.cat.Meta.ID, "version": a.cat.Meta.Version, "hash": a.cat.Hash(),
|
||||
"entries": len(a.ix.Entries), "byKind": kinds, "manualTopics": len(a.ix.Topics), "sourcesNotAvailable": a.ix.Missing}
|
||||
if args[0] == "index" {
|
||||
st["index"] = a.ix.Entries
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(st)
|
||||
}
|
||||
a.say("catalog %s %s (%s)\nentries %d\n", a.cat.Meta.ID, a.cat.Meta.Version, a.cat.Root, len(a.ix.Entries))
|
||||
for _, k := range sortedKeys(kinds) {
|
||||
a.say(" %-12s %d\n", k, kinds[k])
|
||||
}
|
||||
if len(a.ix.Missing) > 0 {
|
||||
a.say("not available locally: %s\n", strings.Join(a.ix.Missing, ", "))
|
||||
}
|
||||
return nil
|
||||
case "backlinks":
|
||||
fs := a.flags("knowledge backlinks")
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s knowledge backlinks <yetano:ref>", a.env.Program)
|
||||
}
|
||||
bl := a.ix.BacklinksOf(fs.Arg(0))
|
||||
if a.jsonOut {
|
||||
if bl == nil {
|
||||
bl = []string{}
|
||||
}
|
||||
return a.printJSON(bl)
|
||||
}
|
||||
for _, b := range bl {
|
||||
a.say("%s\n", b)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return a.usage("knowledge " + args[0])
|
||||
}
|
||||
|
||||
// open shows a reference in the terminal (REF-04): manual text, a
|
||||
// solution's details, or where it lives.
|
||||
func (a *app) open(args []string) error {
|
||||
fs := a.flags("open")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s open <yetano:reference>", a.env.Program)
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
r := fs.Arg(0)
|
||||
if !strings.HasPrefix(r, "yetano:") {
|
||||
r = "yetano:" + r
|
||||
}
|
||||
res, err := a.ix.Resolve(r)
|
||||
if err != nil {
|
||||
return fail(ExitUsage, "%v", err)
|
||||
}
|
||||
if !res.Exists {
|
||||
return fmt.Errorf("%w: %s", engine.ErrNotFound, r)
|
||||
}
|
||||
if !res.SectionExists {
|
||||
return fmt.Errorf("%w: %s has no such section", engine.ErrNotFound, r)
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(res)
|
||||
}
|
||||
p, _ := ref.Parse(r)
|
||||
switch p.Kind {
|
||||
case ref.Solution:
|
||||
return a.show([]string{p.Path[0]}, false)
|
||||
case ref.Task:
|
||||
return a.show([]string{p.Path[0]}, true)
|
||||
case ref.Package:
|
||||
return a.packageCmd([]string{p.Path[0]})
|
||||
case ref.Manual:
|
||||
if _, md, err := a.ix.Read(r); err == nil {
|
||||
a.say("%s", md)
|
||||
return nil
|
||||
}
|
||||
case ref.Example:
|
||||
if x := a.cat.Examples[p.Path[0]+"/"+p.Path[1]]; x != nil {
|
||||
b, _ := engine.Marshal(x.Spec)
|
||||
a.say("# %s\n%s", x.Meta.Title, b)
|
||||
return nil
|
||||
}
|
||||
case ref.Profile:
|
||||
if pr := a.cat.Profiles[p.Path[0]+"/"+p.Path[1]]; pr != nil {
|
||||
b, _ := engine.Marshal(pr.Spec)
|
||||
a.say("# %s\n%s", firstNonEmpty(pr.Meta.Title, pr.Meta.ID), b)
|
||||
return nil
|
||||
}
|
||||
case ref.Capability:
|
||||
a.say("%s -- %s\n", res.Title, res.Summary)
|
||||
for _, pr := range a.cat.ProvidersOf(p.Path[0]) {
|
||||
a.say(" provided by %s\n", pr)
|
||||
}
|
||||
for _, b := range a.ix.BacklinksOf(r) {
|
||||
a.say(" used by %s\n", b)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
a.say("%s\n", res.Title)
|
||||
if res.Summary != "" {
|
||||
a.say("%s\n", wrap(res.Summary, 76, ""))
|
||||
}
|
||||
if res.Web != "" {
|
||||
a.say("web: %s\n", res.Web)
|
||||
}
|
||||
if res.CLI != "" {
|
||||
a.say("cli: %s\n", res.CLI)
|
||||
}
|
||||
if res.Note != "" {
|
||||
a.say("note: %s\n", res.Note)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
"yetano.dev/yetano/core/solutions/engine"
|
||||
"yetano.dev/yetano/core/solutions/ref"
|
||||
"yetano.dev/yetano/core/solutions/store"
|
||||
)
|
||||
|
||||
func (a *app) setup(args []string, task bool) error {
|
||||
cmd := "solution setup"
|
||||
if task {
|
||||
cmd = "task run"
|
||||
}
|
||||
fs := a.flags(cmd)
|
||||
quick := fs.Bool("quick", false, "quick setup: only what is needed, recommended defaults")
|
||||
guided := fs.Bool("guided", false, "guided setup: the relevant choices, with explanations")
|
||||
advanced := fs.Bool("advanced", false, "advanced setup: every option")
|
||||
presetName := fs.String("preset", "", "take answers from a saved preset")
|
||||
example := fs.String("example", "", "start from an example of the solution")
|
||||
answers := fs.String("answers", "", "start from the answers in a solution.yaml")
|
||||
name := fs.String("name", "", "name of the instance (default: the solution ID)")
|
||||
output := fs.String("output", "", "generate the files into this directory when complete")
|
||||
save := fs.Bool("save", false, "save the instance (incomplete: as a draft session)")
|
||||
nonInteractive := fs.Bool("non-interactive", false, "never ask; fail listing what is missing (the default without a terminal)")
|
||||
platform := fs.String("platform", "", "target platform (linux, freebsd, darwin, windows)")
|
||||
force := fs.Bool("force", false, "with --output: overwrite files changed by hand")
|
||||
var sets multi
|
||||
fs.Var(&sets, "set", "answer as question=value (repeatable; lists comma-separated)")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s %s <id> [--quick|--guided|--advanced] [--set q=v]...", a.env.Program, cmd)
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := a.lookup(fs.Arg(0), task)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := catalog.LevelQuick
|
||||
switch {
|
||||
case *advanced:
|
||||
mode = catalog.LevelAdvanced
|
||||
case *guided:
|
||||
mode = catalog.LevelGuided
|
||||
}
|
||||
nm := firstNonEmpty(*name, s.Meta.ID)
|
||||
if err := store.ValidName(nm); err != nil {
|
||||
return fail(ExitUsage, "%v", err)
|
||||
}
|
||||
in := engine.NewInstance(nm, s, mode)
|
||||
in.Spec.Locale = a.locale
|
||||
in.Spec.Platform = *platform
|
||||
if *example != "" {
|
||||
x := a.cat.Examples[s.Meta.ID+"/"+*example]
|
||||
if x == nil {
|
||||
return fmt.Errorf("%w: example %s of %s", engine.ErrNotFound, *example, s.Meta.ID)
|
||||
}
|
||||
for k, v := range x.Spec.Parameters {
|
||||
in.Spec.Parameters[k] = v
|
||||
}
|
||||
if !*quick && !*guided && !*advanced && x.Spec.Mode != "" {
|
||||
in.Spec.Mode = x.Spec.Mode
|
||||
}
|
||||
}
|
||||
if *answers != "" {
|
||||
f, err := os.Open(*answers)
|
||||
if err != nil {
|
||||
return fail(ExitNotFound, "%v", err)
|
||||
}
|
||||
from, err := engine.ReadInstance(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return fail(ExitUsage, "%s: %v", *answers, err)
|
||||
}
|
||||
for k, v := range from.Spec.Parameters {
|
||||
in.Spec.Parameters[k] = v
|
||||
}
|
||||
in.Spec.Overrides = from.Spec.Overrides
|
||||
}
|
||||
for _, kv := range sets {
|
||||
k, v, ok := strings.Cut(kv, "=")
|
||||
if !ok {
|
||||
return fail(ExitUsage, "--set %q: want question=value", kv)
|
||||
}
|
||||
if q, _ := s.Question(k); q == nil {
|
||||
return fail(ExitUsage, "--set %s: %s has no question %q", kv, s.Meta.ID, k)
|
||||
}
|
||||
in.Spec.Parameters[k] = v
|
||||
}
|
||||
var preset *engine.Preset
|
||||
if *presetName != "" {
|
||||
preset, err = a.presetFor(in, *presetName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in.Spec.Preset = preset.Metadata.Name
|
||||
if preset.Spec.Mode != "" && !*quick && !*guided && !*advanced {
|
||||
in.Spec.Mode = preset.Spec.Mode
|
||||
}
|
||||
}
|
||||
kind := ref.Solution
|
||||
if task {
|
||||
kind = ref.Task
|
||||
}
|
||||
_ = a.store.Touch(ref.For(kind, s.Meta.ID), nm)
|
||||
|
||||
if a.env.Interactive && !*nonInteractive && !a.jsonOut {
|
||||
return a.wizard(in, preset, *output, *force)
|
||||
}
|
||||
st, err := a.evaluate(in, preset)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !st.Complete {
|
||||
if *save {
|
||||
in.Kind = catalog.KindSession
|
||||
if err := a.store.SaveInstance(in); err != nil {
|
||||
return err
|
||||
}
|
||||
a.note("saved draft %s\n", nm)
|
||||
}
|
||||
if a.jsonOut {
|
||||
_ = a.printJSON(map[string]any{"complete": false, "missing": st.Progress.Missing, "messages": st.Messages, "state": st})
|
||||
return exitErr{ExitUsage, errors.New("")}
|
||||
}
|
||||
for _, m := range st.Progress.Missing {
|
||||
q := findQ(st, m)
|
||||
a.note("missing: %s (%s) -- --set %s=...\n", m, q.Title, m)
|
||||
}
|
||||
for _, q := range st.Questions {
|
||||
for _, e := range q.Errors {
|
||||
a.note("invalid: %s: %s\n", q.ID, e)
|
||||
}
|
||||
}
|
||||
a.printMessages(st)
|
||||
return fmt.Errorf("%w (%s)", engine.ErrIncomplete, strings.Join(st.Progress.Missing, ", "))
|
||||
}
|
||||
if *save {
|
||||
in.Kind = catalog.KindInstance
|
||||
if err := a.store.SaveInstance(in); err != nil {
|
||||
return err
|
||||
}
|
||||
a.note("saved instance %s\n", nm)
|
||||
}
|
||||
if *output != "" {
|
||||
return a.writeOut(in, st, *output, *force, false, false)
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(st)
|
||||
}
|
||||
a.summary(st)
|
||||
b, _ := engine.Marshal(in)
|
||||
a.note("\nAnswers (save with --save, or as solution.yaml for '%s solution generate --file'):\n", a.env.Program)
|
||||
a.say("%s", b)
|
||||
return nil
|
||||
}
|
||||
|
||||
func findQ(st *engine.State, id string) engine.QuestionState {
|
||||
for _, q := range st.Questions {
|
||||
if q.ID == id {
|
||||
return q
|
||||
}
|
||||
}
|
||||
return engine.QuestionState{ID: id}
|
||||
}
|
||||
|
||||
// summary prints "YOUR SOLUTION" (CLI-02).
|
||||
func (a *app) summary(st *engine.State) {
|
||||
w := a.env.Stdout
|
||||
line := strings.Repeat("-", 60)
|
||||
fmt.Fprintf(w, "%s\nYOUR SOLUTION: %s\n\n", line, st.Solution.Title)
|
||||
fmt.Fprintf(w, "Packages:\n")
|
||||
for _, p := range st.Packages {
|
||||
if p.Selected {
|
||||
var mods []string
|
||||
for _, m := range p.Modules {
|
||||
if m.Enabled && m.Program != "" {
|
||||
mods = append(mods, m.Program)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, " + %-10s %s\n", p.ID, strings.Join(mods, " "))
|
||||
}
|
||||
}
|
||||
for _, p := range st.Packages {
|
||||
if !p.Selected {
|
||||
fmt.Fprintf(w, " ? %-10s recommended: %s\n", p.ID, strings.Join(p.Reasons, "; "))
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, "\nCapabilities:\n")
|
||||
for _, c := range st.Capabilities {
|
||||
switch c.Status {
|
||||
case engine.StRequired, engine.StSelected, engine.StExternal:
|
||||
fmt.Fprintf(w, " + %s\n", c.Title)
|
||||
case engine.StRecommended:
|
||||
fmt.Fprintf(w, " ? %s (recommended)\n", c.Title)
|
||||
case engine.StMissing, engine.StConflicting:
|
||||
fmt.Fprintf(w, " ! %s (%s)\n", c.Title, c.Status)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, "\nConfiguration: %d file(s)", len(st.Files))
|
||||
if st.Complete {
|
||||
fmt.Fprintf(w, ", complete\n")
|
||||
} else {
|
||||
fmt.Fprintf(w, ", INCOMPLETE: %s\n", strings.Join(st.Progress.Missing, ", "))
|
||||
}
|
||||
if len(st.Messages) > 0 {
|
||||
fmt.Fprintf(w, "\nNotes:\n")
|
||||
for _, m := range st.Messages {
|
||||
fmt.Fprintf(w, " %-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 66, " "))
|
||||
}
|
||||
}
|
||||
nc := 0
|
||||
for _, c := range st.Checks {
|
||||
if c.Status == engine.CheckNotChecked {
|
||||
nc++
|
||||
}
|
||||
}
|
||||
if nc > 0 {
|
||||
fmt.Fprintf(w, "\nEnvironment: %d check(s) not run yet -- '%s solution doctor' runs them on the target.\n", nc, a.env.Program)
|
||||
}
|
||||
fmt.Fprintf(w, "%s\n", line)
|
||||
}
|
||||
|
||||
// wizard is the interactive CLI wizard (CLI-02). All decisions come from
|
||||
// the engine: this only asks what the state says, in its order.
|
||||
func (a *app) wizard(in *engine.Instance, preset *engine.Preset, output string, force bool) error {
|
||||
r := bufio.NewReader(a.env.Stdin)
|
||||
w := a.env.Stdout
|
||||
done := map[string]bool{}
|
||||
var history []string
|
||||
st, err := a.evaluate(in, preset)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(w, "Yetano Solutions Guide\n%s\n%s (%s setup)\n\n", strings.Repeat("-", 40), st.Solution.Title, st.Mode)
|
||||
fmt.Fprintf(w, "Enter keeps the value in [brackets]. ? explains, m manual, a architecture, b back, q save and quit.\n\n")
|
||||
for {
|
||||
st, err = a.evaluate(in, preset)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var q *engine.QuestionState
|
||||
for i := range st.Questions {
|
||||
x := &st.Questions[i]
|
||||
if x.Visible && x.Asked && !done[x.ID] {
|
||||
q = x
|
||||
break
|
||||
}
|
||||
}
|
||||
if q == nil {
|
||||
break
|
||||
}
|
||||
step, total := 0, 0
|
||||
for _, x := range st.Questions {
|
||||
if x.Visible && x.Asked {
|
||||
total++
|
||||
if done[x.ID] || x.ID == q.ID {
|
||||
step++
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, "[%d/%d] %s\n", step, total, q.Title)
|
||||
if q.Help != "" {
|
||||
fmt.Fprintf(w, " %s\n", wrap(q.Help, 70, " "))
|
||||
}
|
||||
for i, o := range q.Options {
|
||||
mark := " "
|
||||
if !o.Enabled {
|
||||
mark = "x"
|
||||
}
|
||||
rec := ""
|
||||
if o.Recommended {
|
||||
rec = " (recommended)"
|
||||
}
|
||||
fmt.Fprintf(w, " %s %d. %s%s\n", mark, i+1, o.Title, rec)
|
||||
if !o.Enabled && o.Disabled != "" {
|
||||
fmt.Fprintf(w, " not available: %s\n", wrap(o.Disabled, 62, " "))
|
||||
}
|
||||
}
|
||||
def := ""
|
||||
if q.Value != nil {
|
||||
def = displayValue(q, q.Value)
|
||||
}
|
||||
prompt := "> "
|
||||
if def != "" {
|
||||
prompt = fmt.Sprintf("[%s] > ", def)
|
||||
}
|
||||
fmt.Fprint(w, prompt)
|
||||
line, err := a.readLine(r)
|
||||
if err != nil {
|
||||
fmt.Fprintln(w)
|
||||
return a.saveDraft(in, "input ended")
|
||||
}
|
||||
switch line {
|
||||
case "?":
|
||||
a.explain(q)
|
||||
continue
|
||||
case "m":
|
||||
a.showManual(q, st)
|
||||
continue
|
||||
case "a":
|
||||
fmt.Fprintf(w, "\n%s\n", engine.GraphText(st.Graph))
|
||||
continue
|
||||
case "b":
|
||||
if len(history) > 0 {
|
||||
last := history[len(history)-1]
|
||||
history = history[:len(history)-1]
|
||||
delete(done, last)
|
||||
}
|
||||
continue
|
||||
case "q":
|
||||
return a.saveDraft(in, "")
|
||||
case "":
|
||||
if q.Value == nil && q.Required {
|
||||
fmt.Fprintf(w, " an answer is needed\n")
|
||||
continue
|
||||
}
|
||||
if q.Value != nil {
|
||||
in.Spec.Parameters[q.ID] = q.Value
|
||||
}
|
||||
default:
|
||||
in.Spec.Parameters[q.ID] = line
|
||||
}
|
||||
st2, err := a.evaluate(in, preset)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if q2 := findQ(st2, q.ID); len(q2.Errors) > 0 {
|
||||
fmt.Fprintf(w, " %s\n", strings.Join(q2.Errors, "; "))
|
||||
delete(in.Spec.Parameters, q.ID)
|
||||
continue
|
||||
}
|
||||
for _, s := range st2.Stale {
|
||||
if s.Question == q.ID {
|
||||
fmt.Fprintf(w, " %s\n", s.Reason)
|
||||
delete(in.Spec.Parameters, q.ID)
|
||||
goto next
|
||||
}
|
||||
}
|
||||
done[q.ID] = true
|
||||
history = append(history, q.ID)
|
||||
fmt.Fprintln(w)
|
||||
next:
|
||||
}
|
||||
a.summary(st)
|
||||
for {
|
||||
fmt.Fprintf(w, "\nActions:\n 1. Show configuration\n 2. Show architecture\n 3. Show plan\n 4. Read related manual\n 5. Save solution\n 6. Export configuration (generate files)\n 7. Change an answer\n 8. Quit\n> ")
|
||||
line, err := a.readLine(r)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
switch line {
|
||||
case "1":
|
||||
for _, f := range st.Files {
|
||||
fmt.Fprintf(w, "--- %s\n%s\n", f.Path, f.Content)
|
||||
}
|
||||
case "2":
|
||||
fmt.Fprintf(w, "%s", engine.GraphText(st.Graph))
|
||||
case "3":
|
||||
for i, s := range st.Steps {
|
||||
fmt.Fprintf(w, "%3d. [%s] %s\n", i+1, s.Phase, s.Title)
|
||||
if s.Run != "" {
|
||||
fmt.Fprintf(w, " $ %s\n", s.Run)
|
||||
}
|
||||
}
|
||||
case "4":
|
||||
for _, rf := range st.References {
|
||||
if res, err := a.ix.Resolve(rf); err == nil {
|
||||
fmt.Fprintf(w, " %s\n", refLine(res))
|
||||
}
|
||||
}
|
||||
case "5":
|
||||
in.Kind = catalog.KindInstance
|
||||
if !st.Complete {
|
||||
in.Kind = catalog.KindSession
|
||||
}
|
||||
if err := a.store.SaveInstance(in); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(w, "saved %s (%s)\n", in.Metadata.Name, in.Kind)
|
||||
case "6":
|
||||
dir := output
|
||||
if dir == "" {
|
||||
fmt.Fprintf(w, "directory [./%s] > ", in.Metadata.Name)
|
||||
d, _ := a.readLine(r)
|
||||
dir = firstNonEmpty(d, "./"+in.Metadata.Name)
|
||||
}
|
||||
if err := a.writeOut(in, st, dir, force, false, false); err != nil {
|
||||
fmt.Fprintf(w, "error: %v\n", err)
|
||||
}
|
||||
case "7":
|
||||
fmt.Fprintf(w, "question id > ")
|
||||
id, _ := a.readLine(r)
|
||||
if _, ok := in.Spec.Parameters[id]; ok || findQ(st, id).Title != "" {
|
||||
delete(in.Spec.Parameters, id)
|
||||
return a.wizard(in, preset, output, force)
|
||||
}
|
||||
fmt.Fprintf(w, "no such question\n")
|
||||
case "8", "q", "":
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *app) saveDraft(in *engine.Instance, why string) error {
|
||||
in.Kind = catalog.KindSession
|
||||
if err := a.store.SaveInstance(in); err != nil {
|
||||
return err
|
||||
}
|
||||
a.note("saved the draft as %s; continue with '%s solution setup %s --answers <(%s solution instance export %s)'\n",
|
||||
in.Metadata.Name, a.env.Program, in.Spec.Solution.ID, a.env.Program, in.Metadata.Name)
|
||||
if why != "" {
|
||||
return fail(ExitUsage, "%s", why)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func displayValue(q *engine.QuestionState, v any) string {
|
||||
if l, ok := v.([]any); ok {
|
||||
var parts []string
|
||||
for _, x := range l {
|
||||
parts = append(parts, catalog.Scalar(x))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
s := catalog.Scalar(v)
|
||||
for i, o := range q.Options {
|
||||
if o.ID == s {
|
||||
return fmt.Sprintf("%d", i+1)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// explain is "Help me decide" (HELP-01/02).
|
||||
func (a *app) explain(q *engine.QuestionState) {
|
||||
w := a.env.Stdout
|
||||
if q.Decide != "" {
|
||||
fmt.Fprintf(w, "\n %s\n", wrap(q.Decide, 72, " "))
|
||||
}
|
||||
if q.Description != "" {
|
||||
fmt.Fprintf(w, "\n %s\n", wrap(q.Description, 72, " "))
|
||||
}
|
||||
for _, o := range q.Options {
|
||||
line := o.Title
|
||||
if o.Description != "" {
|
||||
line += ": " + o.Description
|
||||
}
|
||||
if o.Recommended && o.Reason != "" {
|
||||
line += " Recommended: " + o.Reason
|
||||
}
|
||||
if !o.Enabled {
|
||||
line += " Not available: " + o.Disabled
|
||||
}
|
||||
fmt.Fprintf(w, " - %s\n", wrap(line, 70, " "))
|
||||
}
|
||||
if q.Recommended != nil && q.Reason != "" {
|
||||
fmt.Fprintf(w, " Recommended: %v -- %s\n", q.Recommended, q.Reason)
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
|
||||
func (a *app) showManual(q *engine.QuestionState, st *engine.State) {
|
||||
w := a.env.Stdout
|
||||
refs := append([]string{}, q.References...)
|
||||
for _, o := range q.Options {
|
||||
refs = append(refs, o.References...)
|
||||
}
|
||||
refs = append(refs, st.References...)
|
||||
for _, r := range refs {
|
||||
if !strings.HasPrefix(r, "yetano:manual/") {
|
||||
continue
|
||||
}
|
||||
title, md, ok := a.ix.Excerpt(r, 30)
|
||||
res, _ := a.ix.Resolve(r)
|
||||
if !ok {
|
||||
fmt.Fprintf(w, "\n %s\n\n", refLine(res))
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "\n=== %s\n%s\n=== full text: %s\n\n", title, md, firstNonEmpty(res.CLI, res.File))
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, " no manual reference for this question\n")
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
"yetano.dev/yetano/core/solutions/engine"
|
||||
"yetano.dev/yetano/core/solutions/knowledge"
|
||||
"yetano.dev/yetano/core/solutions/ref"
|
||||
"yetano.dev/yetano/core/solutions/store"
|
||||
)
|
||||
|
||||
// multi is a repeatable flag.
|
||||
type multi []string
|
||||
|
||||
func (m *multi) String() string { return strings.Join(*m, ",") }
|
||||
func (m *multi) Set(s string) error { *m = append(*m, s); return nil }
|
||||
|
||||
func (a *app) solution(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return a.usage("")
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list", "ls":
|
||||
return a.list(rest, false)
|
||||
case "search":
|
||||
return a.searchCmd(rest, []string{ref.Solution, ref.Task, ref.Example})
|
||||
case "show":
|
||||
return a.show(rest, false)
|
||||
case "setup", "new":
|
||||
return a.setup(rest, false)
|
||||
case "state", "evaluate":
|
||||
return a.stateCmd(rest)
|
||||
case "generate":
|
||||
return a.generate(rest)
|
||||
case "validate":
|
||||
return a.validate(rest)
|
||||
case "plan":
|
||||
return a.plan(rest)
|
||||
case "doctor":
|
||||
return a.doctor(rest)
|
||||
case "config":
|
||||
return a.config(rest)
|
||||
case "architecture", "arch":
|
||||
return a.architecture(rest)
|
||||
case "handbook":
|
||||
return a.handbook(rest)
|
||||
case "package":
|
||||
return a.packageCmd(rest)
|
||||
case "instance", "instances":
|
||||
return a.instance(rest)
|
||||
case "preset", "presets":
|
||||
return a.preset(rest)
|
||||
case "catalog":
|
||||
return a.catalogCmd(rest)
|
||||
}
|
||||
return a.usage("solution " + sub)
|
||||
}
|
||||
|
||||
func (a *app) task(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return a.usage("")
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list", "ls":
|
||||
return a.list(rest, true)
|
||||
case "search":
|
||||
return a.searchCmd(rest, []string{ref.Task})
|
||||
case "show":
|
||||
return a.show(rest, true)
|
||||
case "run", "setup":
|
||||
return a.setup(rest, true)
|
||||
}
|
||||
return a.usage("task " + sub)
|
||||
}
|
||||
|
||||
// ---- list, show ------------------------------------------------------------
|
||||
|
||||
type listItem struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Title string `json:"title"`
|
||||
Summary string `json:"summary"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Status catalog.Support `json:"status"`
|
||||
Featured bool `json:"featured,omitempty"`
|
||||
TaskKind string `json:"taskKind,omitempty"`
|
||||
}
|
||||
|
||||
func (a *app) items(tasks bool) []listItem {
|
||||
m := a.cat.Solutions
|
||||
if tasks {
|
||||
m = a.cat.Tasks
|
||||
}
|
||||
var out []listItem
|
||||
for _, id := range catalog.SortedIDs(m) {
|
||||
s := m[id]
|
||||
e := a.ix.Entry(ref.For(map[bool]string{false: ref.Solution, true: ref.Task}[tasks], id))
|
||||
title, summary := s.Meta.Title, s.Meta.Summary
|
||||
if e != nil {
|
||||
title, summary = e.Title, e.Summary
|
||||
}
|
||||
st := s.Meta.Status
|
||||
if st == "" {
|
||||
st = catalog.Supported
|
||||
}
|
||||
out = append(out, listItem{ID: id, Kind: strings.ToLower(s.Kind), Title: a.tr(s.Meta.Translations, "title", title),
|
||||
Summary: a.tr(s.Meta.Translations, "summary", summary), Category: s.Meta.Category, Status: st, Featured: s.Meta.Featured, TaskKind: s.Spec.Kind})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *app) list(args []string, tasks bool) error {
|
||||
fs := a.flags("list")
|
||||
category := fs.String("category", "", "only this category")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
items := a.items(tasks)
|
||||
if *category != "" {
|
||||
var f []listItem
|
||||
for _, it := range items {
|
||||
if it.Category == *category {
|
||||
f = append(f, it)
|
||||
}
|
||||
}
|
||||
items = f
|
||||
}
|
||||
if a.jsonOut {
|
||||
if items == nil {
|
||||
items = []listItem{}
|
||||
}
|
||||
return a.printJSON(items)
|
||||
}
|
||||
for _, it := range items {
|
||||
mark := ""
|
||||
if it.Status != catalog.Supported {
|
||||
mark = " [" + string(it.Status) + "]"
|
||||
}
|
||||
a.say("%-22s %s%s\n%-22s %s\n", it.ID, it.Title, mark, "", wrap(it.Summary, 70, strings.Repeat(" ", 23)))
|
||||
}
|
||||
if len(items) == 0 {
|
||||
a.note("nothing found\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *app) lookup(id string, tasks bool) (*catalog.Solution, error) {
|
||||
s := a.cat.Lookup(id)
|
||||
if s == nil {
|
||||
var hint string
|
||||
if groups := a.ix.Search(id, knowledge.SearchOptions{Kinds: []string{ref.Solution, ref.Task}, Limit: 3}); len(groups) > 0 {
|
||||
hint = " -- did you mean " + strings.TrimPrefix(strings.TrimPrefix(groups[0].Hits[0].Ref, "yetano:solution/"), "yetano:task/") + "?"
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %s%s", engine.ErrNotFound, id, hint)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type showOut struct {
|
||||
listItem
|
||||
Goals []string `json:"goals,omitempty"`
|
||||
Scenarios []string `json:"scenarios,omitempty"`
|
||||
NotFor []string `json:"notFor,omitempty"`
|
||||
Outcome string `json:"outcome,omitempty"`
|
||||
Packages []string `json:"packages"`
|
||||
Capabilities catalog.CapSets `json:"capabilities"`
|
||||
Platforms []string `json:"platforms,omitempty"`
|
||||
Questions int `json:"questions"`
|
||||
Quick []string `json:"quickQuestions"`
|
||||
Examples []map[string]string `json:"examples"`
|
||||
References []knowledge.Resolution `json:"references"`
|
||||
Related []string `json:"related,omitempty"`
|
||||
Backlinks []string `json:"backlinks,omitempty"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
func (a *app) show(args []string, tasks bool) error {
|
||||
fs := a.flags("show")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s %s show <id>", a.env.Program, map[bool]string{false: "solution", true: "task"}[tasks])
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := a.lookup(fs.Arg(0), tasks)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var item listItem
|
||||
for _, it := range a.items(s.IsTask()) {
|
||||
if it.ID == s.Meta.ID {
|
||||
item = it
|
||||
}
|
||||
}
|
||||
o := showOut{listItem: item, Goals: s.Spec.Goals, Scenarios: s.Spec.Scenarios, NotFor: s.Spec.NotFor,
|
||||
Capabilities: s.Spec.Capabilities, Platforms: s.Spec.Platforms, Questions: len(s.Spec.Questions), Related: s.Spec.Related,
|
||||
Version: s.Meta.Version, Examples: []map[string]string{}}
|
||||
if bp := a.cat.BigPicture; bp != nil {
|
||||
if g, ok := bp.Stories[s.Spec.BigPicture]; ok {
|
||||
o.Outcome = g.Outcome
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, p := range s.Spec.Packages {
|
||||
if !seen[p.ID] {
|
||||
seen[p.ID] = true
|
||||
o.Packages = append(o.Packages, p.ID)
|
||||
}
|
||||
}
|
||||
for _, q := range s.Spec.Questions {
|
||||
if q.Level == "" || q.Level == catalog.LevelQuick {
|
||||
o.Quick = append(o.Quick, q.ID)
|
||||
}
|
||||
}
|
||||
for _, k := range catalog.SortedIDs(a.cat.Examples) {
|
||||
x := a.cat.Examples[k]
|
||||
if x.Spec.Solution == s.Meta.ID {
|
||||
o.Examples = append(o.Examples, map[string]string{"id": x.Meta.ID, "title": a.tr(x.Meta.Translations, "title", x.Meta.Title), "summary": x.Meta.Summary})
|
||||
}
|
||||
}
|
||||
for _, r := range s.Spec.References.All() {
|
||||
if res, err := a.ix.Resolve(r); err == nil {
|
||||
o.References = append(o.References, res)
|
||||
}
|
||||
}
|
||||
kind := ref.Solution
|
||||
if s.IsTask() {
|
||||
kind = ref.Task
|
||||
}
|
||||
o.Backlinks = a.ix.BacklinksOf(ref.For(kind, s.Meta.ID))
|
||||
if a.jsonOut {
|
||||
return a.printJSON(o)
|
||||
}
|
||||
a.say("%s (%s %s, %s)\n\n", o.Title, o.ID, o.Version, o.Status)
|
||||
a.say("%s\n", wrap(o.Summary, 76, ""))
|
||||
if o.Outcome != "" {
|
||||
a.say("\nResult: %s\n", wrap(o.Outcome, 76, " "))
|
||||
}
|
||||
section := func(title string, list []string) {
|
||||
if len(list) > 0 {
|
||||
a.say("\n%s\n", title)
|
||||
for _, l := range list {
|
||||
a.say(" - %s\n", wrap(l, 72, " "))
|
||||
}
|
||||
}
|
||||
}
|
||||
section("Goals", o.Goals)
|
||||
section("Good for", o.Scenarios)
|
||||
section("Not for", o.NotFor)
|
||||
a.say("\nPackages: %s\n", strings.Join(o.Packages, ", "))
|
||||
a.say("Needs: %s\n", strings.Join(o.Capabilities.Required, ", "))
|
||||
if len(o.Platforms) > 0 {
|
||||
a.say("Platforms: %s\n", strings.Join(o.Platforms, ", "))
|
||||
}
|
||||
a.say("Questions: %d (quick setup asks %d)\n", o.Questions, len(o.Quick))
|
||||
if len(o.Examples) > 0 {
|
||||
a.say("\nExamples\n")
|
||||
for _, x := range o.Examples {
|
||||
a.say(" %-16s %s\n", x["id"], x["title"])
|
||||
}
|
||||
}
|
||||
if len(o.References) > 0 {
|
||||
a.say("\nRead more\n")
|
||||
for _, r := range o.References {
|
||||
a.say(" %s\n", refLine(r))
|
||||
}
|
||||
}
|
||||
cmd := "solution setup"
|
||||
if s.IsTask() {
|
||||
cmd = "task run"
|
||||
}
|
||||
a.say("\nStart: %s %s %s [--quick|--guided|--advanced] [--example <id>]\n", a.env.Program, cmd, o.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func refLine(r knowledge.Resolution) string {
|
||||
where := r.Web
|
||||
if r.CLI != "" && (where == "" || r.Kind == ref.Manual) {
|
||||
where = r.CLI
|
||||
}
|
||||
title := r.Title
|
||||
if title == "" {
|
||||
title = r.Ref
|
||||
}
|
||||
if !r.Exists {
|
||||
title += " (missing)"
|
||||
}
|
||||
return fmt.Sprintf("%-40s %s", title, where)
|
||||
}
|
||||
|
||||
// ---- instances from files or the store ----------------------------------------
|
||||
|
||||
// instanceFrom reads --file, or a stored instance named by the first argument.
|
||||
func (a *app) instanceFrom(file string, fs *flag.FlagSet) (*engine.Instance, error) {
|
||||
if file != "" {
|
||||
var f *os.File
|
||||
var err error
|
||||
if file == "-" {
|
||||
b := bufio.NewReader(a.env.Stdin)
|
||||
in, err := engine.ReadInstance(b)
|
||||
if err != nil {
|
||||
return nil, fail(ExitUsage, "stdin: %v", err)
|
||||
}
|
||||
return in, nil
|
||||
}
|
||||
f, err = os.Open(file)
|
||||
if err != nil {
|
||||
return nil, fail(ExitNotFound, "%v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
in, err := engine.ReadInstance(f)
|
||||
if err != nil {
|
||||
return nil, fail(ExitUsage, "%s: %v", file, err)
|
||||
}
|
||||
return in, nil
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
return nil, fail(ExitUsage, "name a saved instance or pass --file <solution.yaml>")
|
||||
}
|
||||
return a.store.LoadInstance(fs.Arg(0))
|
||||
}
|
||||
|
||||
func (a *app) presetFor(in *engine.Instance, name string) (*engine.Preset, error) {
|
||||
if name == "" {
|
||||
name = in.Spec.Preset
|
||||
}
|
||||
if name == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if strings.HasSuffix(name, ".yaml") || strings.Contains(name, string(filepath.Separator)) {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return engine.ReadPreset(f)
|
||||
}
|
||||
return a.store.LoadPreset(name)
|
||||
}
|
||||
|
||||
func (a *app) evaluate(in *engine.Instance, preset *engine.Preset) (*engine.State, error) {
|
||||
if in.Spec.Locale == "" {
|
||||
in.Spec.Locale = a.locale
|
||||
}
|
||||
return a.eng.Evaluate(in, preset)
|
||||
}
|
||||
|
||||
// common flags of the commands that take an instance
|
||||
type instFlags struct {
|
||||
file *string
|
||||
preset *string
|
||||
}
|
||||
|
||||
func (a *app) instFlags(fs *flag.FlagSet) instFlags {
|
||||
return instFlags{
|
||||
file: fs.String("file", "", "solution.yaml (SolutionInstance or WizardSession); - for stdin"),
|
||||
preset: fs.String("preset", "", "preset name or file (default: the instance's)"),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *app) stateOf(fs *flag.FlagSet, f instFlags) (*engine.Instance, *engine.State, error) {
|
||||
if err := a.load(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
in, err := a.instanceFrom(*f.file, fs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
p, err := a.presetFor(in, *f.preset)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
st, err := a.evaluate(in, p)
|
||||
return in, st, err
|
||||
}
|
||||
|
||||
// stateCmd prints the full engine state: the shared client API as JSON
|
||||
// (API-01); GUI and web clients render exactly this.
|
||||
func (a *app) stateCmd(args []string) error {
|
||||
fs := a.flags("solution state")
|
||||
f := a.instFlags(fs)
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
a.jsonOut = true
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.printJSON(st)
|
||||
}
|
||||
|
||||
// ---- generate, validate, plan -------------------------------------------------
|
||||
|
||||
func (a *app) generate(args []string) error {
|
||||
fs := a.flags("solution generate")
|
||||
f := a.instFlags(fs)
|
||||
output := fs.String("output", "", "output directory (required)")
|
||||
force := fs.Bool("force", false, "overwrite files changed by hand")
|
||||
locked := fs.Bool("locked", false, "fail if the catalog changed the meaning since the last generation (solution.lock.yaml)")
|
||||
dry := fs.Bool("dry-run", false, "list the files, write nothing")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if *output == "" && !*dry {
|
||||
return fail(ExitUsage, "--output <dir> is required")
|
||||
}
|
||||
in, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.writeOut(in, st, *output, *force, *locked, *dry)
|
||||
}
|
||||
|
||||
func (a *app) writeOut(in *engine.Instance, st *engine.State, dir string, force, locked, dry bool) error {
|
||||
out, err := a.eng.Generate(st, in, a.ix, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dir != "" && !dry {
|
||||
if prev, err := engine.ReadLock(dir); err == nil && prev != nil {
|
||||
if drift := engine.LockDrift(prev, out.Lock); len(drift) > 0 {
|
||||
if locked {
|
||||
return fail(ExitConflict, "the catalog changed since the last generation: %s (run without --locked to accept)", strings.Join(drift, "; "))
|
||||
}
|
||||
a.note("note: since the last generation: %s\n", strings.Join(drift, "; "))
|
||||
}
|
||||
}
|
||||
if err := engine.Write(dir, out, force); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(map[string]any{"output": dir, "dryRun": dry, "files": out.Files, "complete": st.Complete, "messages": st.Messages})
|
||||
}
|
||||
verb := "wrote"
|
||||
if dry {
|
||||
verb = "would write"
|
||||
}
|
||||
a.note("%s %d files to %s\n", verb, len(out.Files), dir)
|
||||
for _, f := range out.Files {
|
||||
a.say(" %s\n", f.Path)
|
||||
}
|
||||
a.printMessages(st)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *app) printMessages(st *engine.State) {
|
||||
for _, m := range st.Messages {
|
||||
a.note("%-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 70, " "))
|
||||
}
|
||||
}
|
||||
|
||||
// validate: is the instance complete and valid; with --native also run
|
||||
// the programs' own validators on a generated directory.
|
||||
func (a *app) validate(args []string) error {
|
||||
fs := a.flags("solution validate")
|
||||
f := a.instFlags(fs)
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type qerr struct {
|
||||
Question string `json:"question"`
|
||||
Errors []string `json:"errors"`
|
||||
}
|
||||
var qerrs []qerr
|
||||
for _, q := range st.Questions {
|
||||
if len(q.Errors) > 0 {
|
||||
qerrs = append(qerrs, qerr{q.ID, q.Errors})
|
||||
}
|
||||
}
|
||||
if a.jsonOut {
|
||||
if err := a.printJSON(map[string]any{"complete": st.Complete, "missing": st.Progress.Missing, "errors": qerrs, "stale": st.Stale, "messages": st.Messages}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
for _, q := range qerrs {
|
||||
a.say("ERROR %s: %s\n", q.Question, strings.Join(q.Errors, "; "))
|
||||
}
|
||||
for _, m := range st.Progress.Missing {
|
||||
a.say("MISSING %s\n", m)
|
||||
}
|
||||
for _, s := range st.Stale {
|
||||
a.say("STALE %s=%v: %s\n", s.Question, s.Value, s.Reason)
|
||||
}
|
||||
a.printMessages(st)
|
||||
if st.Complete {
|
||||
a.say("valid: %s is complete\n", st.Solution.ID)
|
||||
}
|
||||
}
|
||||
if !st.Complete {
|
||||
return exitErr{ExitError, errors.New("")}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *app) plan(args []string) error {
|
||||
fs := a.flags("solution plan")
|
||||
f := a.instFlags(fs)
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := engine.PlanOf(st)
|
||||
if a.jsonOut {
|
||||
return a.printJSON(p)
|
||||
}
|
||||
a.say("Plan for %s (%s) -- nothing is executed by the guide.\n", firstNonEmpty(st.Instance, st.Solution.ID), p.Spec.Solution)
|
||||
phase := ""
|
||||
for i, s := range p.Spec.Steps {
|
||||
if s.Phase != phase {
|
||||
phase = s.Phase
|
||||
a.say("\n%s\n", strings.ToUpper(phase))
|
||||
}
|
||||
mark := " "
|
||||
if s.Mutating {
|
||||
mark = "*"
|
||||
}
|
||||
a.say("%3d.%s %s\n", i+1, mark, s.Title)
|
||||
if s.Run != "" {
|
||||
a.say(" $ %s\n", s.Run)
|
||||
}
|
||||
}
|
||||
a.say("\n* changes the system\n")
|
||||
if !st.Complete {
|
||||
a.printMessages(st)
|
||||
return fail(ExitUsage, "the solution is incomplete: %s", strings.Join(st.Progress.Missing, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func firstNonEmpty(a ...string) string {
|
||||
for _, s := range a {
|
||||
if s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---- config, architecture, handbook ------------------------------------------
|
||||
|
||||
func (a *app) config(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fail(ExitUsage, "usage: %s solution config show|explain ...", a.env.Program)
|
||||
}
|
||||
switch args[0] {
|
||||
case "show":
|
||||
fs := a.flags("solution config show")
|
||||
f := a.instFlags(fs)
|
||||
fs.Bool("effective", true, "show the effective, merged configuration (the default)")
|
||||
origins := fs.Bool("origins", false, "show where each value comes from")
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(st.Files)
|
||||
}
|
||||
for _, file := range st.Files {
|
||||
a.say("--- %s\n%s\n", file.Path, file.Content)
|
||||
if *origins {
|
||||
for _, k := range sortedKeys(file.Origins) {
|
||||
o := file.Origins[k]
|
||||
a.say(" %-40s %s %s\n", k, o.Source, strings.Join(o.Params, ","))
|
||||
}
|
||||
a.say("\n")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case "explain":
|
||||
fs := a.flags("solution config explain")
|
||||
f := a.instFlags(fs)
|
||||
if err := a.parse(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
// [instance] <file> <path>
|
||||
pos := fs.Args()
|
||||
var file, path string
|
||||
switch {
|
||||
case *f.file != "" && len(pos) == 2:
|
||||
file, path = pos[0], pos[1]
|
||||
case *f.file == "" && len(pos) == 3:
|
||||
file, path = pos[1], pos[2]
|
||||
default:
|
||||
return fail(ExitUsage, "usage: %s solution config explain <instance>|--file f <file> <path> (e.g. yamase/yamase.yaml tls.cert-file)", a.env.Program)
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ex := engine.Explain(st, file, path)
|
||||
if a.jsonOut {
|
||||
return a.printJSON(ex)
|
||||
}
|
||||
if !ex.Found {
|
||||
return fail(ExitNotFound, "%s: %s is not set by the guide (the program's built-in default applies)", ex.File, path)
|
||||
}
|
||||
a.say("%s %s\n set by %s (%s layer)\n", ex.File, path, ex.Origin.Source, ex.Origin.Layer)
|
||||
for _, p := range sortedKeys(ex.Answers) {
|
||||
a.say(" uses answer %s = %v (%s)\n", p, ex.Answers[p], ex.Origins[p])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return a.usage("solution config " + args[0])
|
||||
}
|
||||
|
||||
func (a *app) architecture(args []string) error {
|
||||
fs := a.flags("solution architecture")
|
||||
f := a.instFlags(fs)
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.jsonOut {
|
||||
return a.printJSON(st.Graph)
|
||||
}
|
||||
a.say("%s", engine.GraphText(st.Graph))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *app) handbook(args []string) error {
|
||||
fs := a.flags("solution handbook")
|
||||
f := a.instFlags(fs)
|
||||
output := fs.String("output", "", "directory to write the handbook to (default: print index)")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
_, st, err := a.stateOf(fs, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pages := a.eng.Handbook(st, a.ix)
|
||||
if *output == "" {
|
||||
for _, p := range pages {
|
||||
a.say("%s\n", p.Content)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, p := range pages {
|
||||
path := filepath.Join(*output, filepath.FromSlash(strings.TrimPrefix(p.Path, "handbook/")))
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, p.Content, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
a.note("wrote %d pages to %s\n", len(pages), *output)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *app) packageCmd(args []string) error {
|
||||
fs := a.flags("solution package")
|
||||
if err := a.parse(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return fail(ExitUsage, "usage: %s solution package <id>", a.env.Program)
|
||||
}
|
||||
p := a.cat.Packages[fs.Arg(0)]
|
||||
if p == nil {
|
||||
return fmt.Errorf("%w: package %s", engine.ErrNotFound, fs.Arg(0))
|
||||
}
|
||||
r := ref.For(ref.Package, p.Meta.ID)
|
||||
back := a.ix.BacklinksOf(r)
|
||||
if a.jsonOut {
|
||||
return a.printJSON(map[string]any{"package": p, "summary": a.eng.PackageSummary(p.Meta.ID), "usedBy": back})
|
||||
}
|
||||
a.say("%s -- %s\n\n", p.Meta.ID, wrap(a.eng.PackageSummary(p.Meta.ID), 70, " "))
|
||||
for _, m := range p.Spec.Modules {
|
||||
sup := ""
|
||||
if m.Support != "" && m.Support != catalog.Supported {
|
||||
sup = " [" + string(m.Support) + "]"
|
||||
}
|
||||
a.say(" %-14s %s%s\n", m.ID, m.Title, sup)
|
||||
if len(m.Provides) > 0 {
|
||||
a.say(" %-14s provides %s\n", "", strings.Join(m.Provides, ", "))
|
||||
}
|
||||
}
|
||||
if len(back) > 0 {
|
||||
a.say("\nWhat would you like to do with %s?\n", p.Meta.ID)
|
||||
for _, b := range back {
|
||||
if strings.HasPrefix(b, "yetano:solution/") || strings.HasPrefix(b, "yetano:task/") {
|
||||
res, _ := a.ix.Resolve(b)
|
||||
a.say(" %-30s %s\n", res.Title, res.CLI)
|
||||
}
|
||||
}
|
||||
}
|
||||
if res, err := a.ix.Resolve(ref.For(ref.Microsite, p.Meta.ID)); err == nil && res.Web != "" {
|
||||
a.say("\nMicrosite: %s\n", res.Web)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ = store.ErrNotFound
|
||||
@@ -0,0 +1,55 @@
|
||||
// Command yetano-solutions runs the Solutions Guide commands (CI of the
|
||||
// catalog, development). The guide is deliberately not part of yet, which
|
||||
// stays a general tool; the full program with TUI and GUI moves to its
|
||||
// own repository (docs/knowledge-solutions ADR-0006).
|
||||
//
|
||||
// yetano-solutions solution list --catalog assets/solutions
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"yetano.dev/yetano/core"
|
||||
"yetano.dev/yetano/core/paths"
|
||||
"yetano.dev/yetano/core/solutions/cli"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
// instances, sessions and presets are user data: core/paths' data
|
||||
// directory (nothing is created until something is saved)
|
||||
storeDir := os.Getenv("YETANO_SOLUTIONS_HOME")
|
||||
if storeDir == "" {
|
||||
if r, err := paths.For(core.Application{Name: "yetano-solutions", Kind: core.CLI}); err == nil {
|
||||
if d, err := r.DataDir(); err == nil {
|
||||
storeDir = d
|
||||
}
|
||||
}
|
||||
}
|
||||
os.Exit(cli.Run(ctx, os.Args[1:], cli.Env{
|
||||
Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr,
|
||||
Interactive: isTerminal(os.Stdin) && isTerminal(os.Stdout),
|
||||
Program: "yetano-solutions",
|
||||
StoreDir: storeDir,
|
||||
Version: version,
|
||||
}))
|
||||
}
|
||||
|
||||
// isTerminal: a character device that is not the null device (/dev/null
|
||||
// is a character device too, and must never start an interactive wizard).
|
||||
func isTerminal(f *os.File) bool {
|
||||
st, err := f.Stat()
|
||||
if err != nil || st.Mode()&os.ModeCharDevice == 0 {
|
||||
return false
|
||||
}
|
||||
if null, err := os.Stat(os.DevNull); err == nil && os.SameFile(st, null) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// The meta-repo's catalog, when this module is checked out inside it.
|
||||
func assetsCatalog(t *testing.T) *catalog.Catalog {
|
||||
t.Helper()
|
||||
dir, _ := filepath.Abs("../../../assets/solutions")
|
||||
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
|
||||
t.Skip("assets/solutions not present (module outside the meta-repo)")
|
||||
}
|
||||
c, err := catalog.Load(dir)
|
||||
if err != nil {
|
||||
for _, i := range c.Issues {
|
||||
t.Log(i)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func TestAssetsCatalog(t *testing.T) {
|
||||
c := assetsCatalog(t)
|
||||
for _, i := range c.Validate() {
|
||||
if i.Severity == "error" {
|
||||
t.Error(i)
|
||||
} else {
|
||||
t.Log(i)
|
||||
}
|
||||
}
|
||||
e := New(c)
|
||||
for _, key := range catalog.SortedIDs(c.Examples) {
|
||||
x := c.Examples[key]
|
||||
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
|
||||
in.Spec.Parameters = x.Spec.Parameters
|
||||
st, err := e.Evaluate(in, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", key, err)
|
||||
}
|
||||
if !st.Complete {
|
||||
t.Errorf("%s: not complete: %s", key, incompleteText(st))
|
||||
}
|
||||
for _, m := range st.Messages {
|
||||
t.Logf("%s: %s %s", key, m.Severity, m.Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// placeholder: ${name}, ${name[0]}, ${name.count}, ${name.join}; $${ is a literal "${".
|
||||
var placeholderRE = regexp.MustCompile(`\$\$\{|\$\{((?:instance|solution)\.[a-z]+|[A-Za-z_][A-Za-z0-9_]*)(?:\[(\d+)\]|\.(count|join))?\}`)
|
||||
|
||||
type genFile struct {
|
||||
path string
|
||||
pkg string
|
||||
root *yaml.Node // mapping
|
||||
origins map[string]Origin
|
||||
}
|
||||
|
||||
func (ev *evaluation) vars() map[string]any {
|
||||
v := map[string]any{}
|
||||
for k, a := range ev.answers {
|
||||
v[k] = a
|
||||
}
|
||||
v["instance.name"] = ev.in.Metadata.Name
|
||||
v["solution.id"] = ev.s.Meta.ID
|
||||
v["solution.version"] = ev.s.Meta.Version
|
||||
return v
|
||||
}
|
||||
|
||||
func (ev *evaluation) config() {
|
||||
files := map[string]*genFile{}
|
||||
var order []string
|
||||
get := func(path string) *genFile {
|
||||
f, ok := files[path]
|
||||
if !ok {
|
||||
pkg, _, _ := strings.Cut(path, "/")
|
||||
f = &genFile{path: path, pkg: pkg, root: &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}, origins: map[string]Origin{}}
|
||||
files[path] = f
|
||||
order = append(order, path)
|
||||
}
|
||||
return f
|
||||
}
|
||||
vars := ev.vars()
|
||||
applyFrag := func(fr catalog.Fragment, origin Origin) {
|
||||
pkg, _, _ := strings.Cut(fr.File, "/")
|
||||
if !ev.pkgSelected(pkg) {
|
||||
return
|
||||
}
|
||||
if fr.Module != "" {
|
||||
mp, mm := pkg, fr.Module
|
||||
if a, b, ok := strings.Cut(fr.Module, "/"); ok {
|
||||
mp, mm = a, b
|
||||
}
|
||||
if !ev.moduleEnabled(mp, mm) {
|
||||
return
|
||||
}
|
||||
}
|
||||
node := deepCopy(&fr.Set)
|
||||
params := map[string]bool{}
|
||||
if err := interpolate(node, vars, params); err != nil {
|
||||
ev.msg("error", "config", fmt.Sprintf("%s: %v", origin.Source, err), origin.Source)
|
||||
return
|
||||
}
|
||||
for p := range params {
|
||||
origin.Params = append(origin.Params, p)
|
||||
}
|
||||
sort.Strings(origin.Params)
|
||||
if node.Kind != yaml.MappingNode {
|
||||
ev.msg("error", "config", fmt.Sprintf("%s: fragment for %s is not a map", origin.Source, fr.File), origin.Source)
|
||||
return
|
||||
}
|
||||
f := get(fr.File)
|
||||
mergeMap(f.root, node, "", origin, f.origins)
|
||||
}
|
||||
// layer 2: profiles (base first), in package order
|
||||
ids := append([]string{}, ev.pkgSeen...)
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
p := ev.pkgs[id]
|
||||
if !p.Selected || p.Profile == "" {
|
||||
continue
|
||||
}
|
||||
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, prof := range chain {
|
||||
for _, fr := range prof.Spec.Config {
|
||||
applyFrag(fr, Origin{Layer: "profile", Source: "profile:" + prof.Key()})
|
||||
}
|
||||
}
|
||||
}
|
||||
// layer 3: the solution's fragments
|
||||
for i, fr := range ev.s.Spec.Config {
|
||||
if len(fr.When) > 0 && !fr.When.Holds(ev.env) {
|
||||
continue
|
||||
}
|
||||
id := fr.ID
|
||||
if id == "" {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
applyFrag(fr, Origin{Layer: "solution", Source: "solution:" + ev.s.Meta.ID + "#" + id})
|
||||
}
|
||||
// layer 6: explicit overrides
|
||||
for _, o := range ev.in.Spec.Overrides {
|
||||
if !catalog.SafeRelPath(o.File) || o.Path == "" {
|
||||
ev.msg("error", "override", fmt.Sprintf("override %s %s: bad file or path", o.File, o.Path), "override")
|
||||
continue
|
||||
}
|
||||
f, ok := files[o.File]
|
||||
if !ok {
|
||||
ev.msg("warning", "override", fmt.Sprintf("override for %s: the solution generates no such file", o.File), "override")
|
||||
continue
|
||||
}
|
||||
var val yaml.Node
|
||||
if err := val.Encode(o.Value); err != nil {
|
||||
ev.msg("error", "override", err.Error(), "override")
|
||||
continue
|
||||
}
|
||||
setPath(f.root, strings.Split(o.Path, "."), &val)
|
||||
f.origins[o.Path] = Origin{Layer: "override", Source: "override"}
|
||||
ev.msg("info", "override", fmt.Sprintf("%s: %s is set directly, not through a question", o.File, o.Path), "override")
|
||||
}
|
||||
sort.Strings(order)
|
||||
for _, path := range order {
|
||||
f := files[path]
|
||||
body, err := render(f.root, ev.s, path)
|
||||
if err != nil {
|
||||
ev.msg("error", "config", err.Error(), path)
|
||||
continue
|
||||
}
|
||||
ev.st.Files = append(ev.st.Files, FilePreview{Path: "config/" + path, Package: f.pkg, Content: body, Origins: f.origins})
|
||||
}
|
||||
}
|
||||
|
||||
func render(root *yaml.Node, s *catalog.Solution, path string) (string, error) {
|
||||
doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
|
||||
doc.HeadComment = fmt.Sprintf("Generated by the Yetano Solutions Guide from %s %s.\n"+
|
||||
"This is a native configuration file: edit it like any other. See\n"+
|
||||
"solution.lock.yaml before regenerating over hand edits.", s.Meta.ID, s.Meta.Version)
|
||||
var buf bytes.Buffer
|
||||
enc := yaml.NewEncoder(&buf)
|
||||
enc.SetIndent(2)
|
||||
if err := enc.Encode(doc); err != nil {
|
||||
return "", fmt.Errorf("%s: %v", path, err)
|
||||
}
|
||||
enc.Close()
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func deepCopy(n *yaml.Node) *yaml.Node {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
c := *n
|
||||
if c.Kind == yaml.MappingNode || c.Kind == yaml.SequenceNode {
|
||||
c.Style = 0 // generated files use block style, whatever the catalog wrote
|
||||
}
|
||||
c.Line, c.Column = 0, 0
|
||||
c.Content = make([]*yaml.Node, len(n.Content))
|
||||
for i, ch := range n.Content {
|
||||
c.Content[i] = deepCopy(ch)
|
||||
}
|
||||
if n.Kind == yaml.DocumentNode && len(c.Content) == 1 {
|
||||
return c.Content[0]
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
// interpolate replaces placeholders in scalars (ADR-0005).
|
||||
func interpolate(n *yaml.Node, vars map[string]any, used map[string]bool) error {
|
||||
switch n.Kind {
|
||||
case yaml.MappingNode:
|
||||
for i := 1; i < len(n.Content); i += 2 {
|
||||
if err := interpolate(n.Content[i], vars, used); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case yaml.SequenceNode:
|
||||
for _, ch := range n.Content {
|
||||
if err := interpolate(ch, vars, used); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case yaml.ScalarNode:
|
||||
if !strings.Contains(n.Value, "${") {
|
||||
return nil
|
||||
}
|
||||
whole := placeholderRE.FindStringSubmatchIndex(n.Value)
|
||||
if whole != nil && whole[0] == 0 && whole[1] == len(n.Value) && n.Value != "$${" {
|
||||
v, err := lookup(n.Value, vars, used)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var repl yaml.Node
|
||||
if err := repl.Encode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
repl.Style = 0
|
||||
*n = repl
|
||||
return nil
|
||||
}
|
||||
var firstErr error
|
||||
out := placeholderRE.ReplaceAllStringFunc(n.Value, func(m string) string {
|
||||
if m == "$${" {
|
||||
return "${"
|
||||
}
|
||||
v, err := lookup(m, vars, used)
|
||||
if err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
return text(v)
|
||||
})
|
||||
if firstErr != nil {
|
||||
return firstErr
|
||||
}
|
||||
n.Value = out
|
||||
n.Tag = "!!str"
|
||||
n.Style = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lookup(ph string, vars map[string]any, used map[string]bool) (any, error) {
|
||||
m := placeholderRE.FindStringSubmatch(ph)
|
||||
name := m[1]
|
||||
v, ok := vars[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("placeholder ${%s}: no answer for %q", name, name)
|
||||
}
|
||||
used[name] = true
|
||||
switch {
|
||||
case m[2] != "":
|
||||
i, _ := strconv.Atoi(m[2])
|
||||
l := listOf(v)
|
||||
if i >= len(l) {
|
||||
return nil, fmt.Errorf("placeholder %s: %q has only %d item(s)", ph, name, len(l))
|
||||
}
|
||||
return l[i], nil
|
||||
case m[3] == "count":
|
||||
return len(listOf(v)), nil
|
||||
case m[3] == "join":
|
||||
var parts []string
|
||||
for _, x := range listOf(v) {
|
||||
parts = append(parts, catalog.Scalar(x))
|
||||
}
|
||||
return strings.Join(parts, ","), nil
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func text(v any) string {
|
||||
if l, ok := v.([]any); ok {
|
||||
var parts []string
|
||||
for _, x := range l {
|
||||
parts = append(parts, catalog.Scalar(x))
|
||||
}
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
return catalog.Scalar(v)
|
||||
}
|
||||
|
||||
// mergeMap merges src into dst like core/config: maps key by key, lists
|
||||
// and scalars replace, null removes. Origins are recorded per path.
|
||||
func mergeMap(dst, src *yaml.Node, prefix string, origin Origin, origins map[string]Origin) {
|
||||
for i := 0; i+1 < len(src.Content); i += 2 {
|
||||
k, v := src.Content[i], src.Content[i+1]
|
||||
path := k.Value
|
||||
if prefix != "" {
|
||||
path = prefix + "." + k.Value
|
||||
}
|
||||
idx := -1
|
||||
for j := 0; j+1 < len(dst.Content); j += 2 {
|
||||
if dst.Content[j].Value == k.Value {
|
||||
idx = j
|
||||
break
|
||||
}
|
||||
}
|
||||
if v.Kind == yaml.ScalarNode && v.Tag == "!!null" {
|
||||
if idx >= 0 {
|
||||
dst.Content = append(dst.Content[:idx], dst.Content[idx+2:]...)
|
||||
}
|
||||
for p := range origins {
|
||||
if p == path || strings.HasPrefix(p, path+".") {
|
||||
delete(origins, p)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if idx >= 0 && v.Kind == yaml.MappingNode && dst.Content[idx+1].Kind == yaml.MappingNode {
|
||||
mergeMap(dst.Content[idx+1], v, path, origin, origins)
|
||||
continue
|
||||
}
|
||||
for p := range origins {
|
||||
if strings.HasPrefix(p, path+".") {
|
||||
delete(origins, p)
|
||||
}
|
||||
}
|
||||
if idx >= 0 {
|
||||
dst.Content[idx+1] = v
|
||||
} else {
|
||||
dst.Content = append(dst.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k.Value}, v)
|
||||
}
|
||||
recordLeaves(v, path, origin, origins)
|
||||
}
|
||||
}
|
||||
|
||||
func recordLeaves(v *yaml.Node, path string, origin Origin, origins map[string]Origin) {
|
||||
if v.Kind == yaml.MappingNode {
|
||||
for i := 0; i+1 < len(v.Content); i += 2 {
|
||||
recordLeaves(v.Content[i+1], path+"."+v.Content[i].Value, origin, origins)
|
||||
}
|
||||
return
|
||||
}
|
||||
origins[path] = origin
|
||||
}
|
||||
|
||||
func setPath(root *yaml.Node, keys []string, val *yaml.Node) {
|
||||
cur := root
|
||||
for i, k := range keys {
|
||||
idx := -1
|
||||
for j := 0; j+1 < len(cur.Content); j += 2 {
|
||||
if cur.Content[j].Value == k {
|
||||
idx = j
|
||||
}
|
||||
}
|
||||
if i == len(keys)-1 {
|
||||
if idx >= 0 {
|
||||
cur.Content[idx+1] = val
|
||||
} else {
|
||||
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, val)
|
||||
}
|
||||
return
|
||||
}
|
||||
if idx < 0 || cur.Content[idx+1].Kind != yaml.MappingNode {
|
||||
m := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
if idx >= 0 {
|
||||
cur.Content[idx+1] = m
|
||||
} else {
|
||||
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, m)
|
||||
}
|
||||
cur = m
|
||||
} else {
|
||||
cur = cur.Content[idx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explanation answers "where does this value come from?" (PROF-05).
|
||||
type Explanation struct {
|
||||
File string `json:"file"`
|
||||
Path string `json:"path"`
|
||||
Found bool `json:"found"`
|
||||
Origin Origin `json:"origin"`
|
||||
Answers map[string]any `json:"answers,omitempty"` // the answers it used, with their origin
|
||||
Origins map[string]string `json:"answerOrigins,omitempty"`
|
||||
}
|
||||
|
||||
// Explain finds the origin of a value in a generated file. file may omit
|
||||
// the "config/" prefix; path is dot separated.
|
||||
func Explain(st *State, file, path string) Explanation {
|
||||
file = strings.TrimPrefix(file, "config/")
|
||||
ex := Explanation{File: "config/" + file, Path: path}
|
||||
for _, f := range st.Files {
|
||||
if f.Path != "config/"+file {
|
||||
continue
|
||||
}
|
||||
p := path
|
||||
for p != "" {
|
||||
if o, ok := f.Origins[p]; ok {
|
||||
ex.Found, ex.Origin = true, o
|
||||
break
|
||||
}
|
||||
i := strings.LastIndex(p, ".")
|
||||
if i < 0 {
|
||||
break
|
||||
}
|
||||
p = p[:i]
|
||||
}
|
||||
}
|
||||
if ex.Found && len(ex.Origin.Params) > 0 {
|
||||
ex.Answers, ex.Origins = map[string]any{}, map[string]string{}
|
||||
for _, p := range ex.Origin.Params {
|
||||
if a, ok := st.Answers[p]; ok {
|
||||
ex.Answers[p] = a.Value
|
||||
ex.Origins[p] = a.Origin
|
||||
}
|
||||
}
|
||||
}
|
||||
return ex
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
func testCat(t *testing.T) *catalog.Catalog {
|
||||
t.Helper()
|
||||
c, err := catalog.Load("testdata/cat")
|
||||
if err != nil {
|
||||
for _, i := range c.Issues {
|
||||
t.Log(i)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, i := range c.Validate() {
|
||||
if i.Severity == "error" {
|
||||
t.Fatal(i)
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func eval(t *testing.T, e *Engine, mode catalog.Level, params map[string]any, p *Preset) *State {
|
||||
t.Helper()
|
||||
in := NewInstance("t1", e.Cat.Solutions["app-run"], mode)
|
||||
for k, v := range params {
|
||||
in.Spec.Parameters[k] = v
|
||||
}
|
||||
st, err := e.Evaluate(in, p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func pkg(st *State, id string) *PackageState {
|
||||
for i := range st.Packages {
|
||||
if st.Packages[i].ID == id {
|
||||
return &st.Packages[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func capOf(st *State, id string) *CapState {
|
||||
for i := range st.Capabilities {
|
||||
if st.Capabilities[i].ID == id {
|
||||
return &st.Capabilities[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func file(st *State, path string) string {
|
||||
for _, f := range st.Files {
|
||||
if f.Path == path {
|
||||
return f.Content
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func question(st *State, id string) QuestionState { return findQuestion(st, id) }
|
||||
|
||||
func findQuestion(st *State, id string) QuestionState {
|
||||
for _, q := range st.Questions {
|
||||
if q.ID == id {
|
||||
return q
|
||||
}
|
||||
}
|
||||
return QuestionState{}
|
||||
}
|
||||
|
||||
func hasMsg(st *State, sub string) bool {
|
||||
for _, m := range st.Messages {
|
||||
if strings.Contains(m.Text, sub) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestQuickDefaultPath(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
st := eval(t, e, catalog.LevelQuick, nil, nil)
|
||||
if st.Complete || len(st.Progress.Missing) != 1 || st.Progress.Missing[0] != "hosts" {
|
||||
t.Fatalf("want only hosts missing, got %v", st.Progress.Missing)
|
||||
}
|
||||
if st.Next != "hosts" {
|
||||
t.Errorf("next = %q", st.Next)
|
||||
}
|
||||
// quick asks size and hosts only; guided questions take their defaults
|
||||
var asked []string
|
||||
for _, q := range st.Questions {
|
||||
if q.Asked {
|
||||
asked = append(asked, q.ID)
|
||||
}
|
||||
}
|
||||
if strings.Join(asked, ",") != "size,hosts" {
|
||||
t.Errorf("asked %v", asked)
|
||||
}
|
||||
st = eval(t, e, catalog.LevelQuick, map[string]any{"hosts": "a.example.org, b.example.org"}, nil)
|
||||
if !st.Complete {
|
||||
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
|
||||
}
|
||||
if p := pkg(st, "app"); p == nil || !p.Selected || p.Profile != "base" {
|
||||
t.Fatalf("app: %+v", p)
|
||||
}
|
||||
if c := capOf(st, "auth.users"); c == nil || c.Provider != "app/users" {
|
||||
t.Errorf("auth.users provider: %+v", c)
|
||||
}
|
||||
if c := capOf(st, "backup.files"); c == nil || c.Status != StRecommended {
|
||||
t.Errorf("backup.files should be recommended: %+v", c)
|
||||
}
|
||||
if c := capOf(st, "feature.x"); c != nil && c.Status != StExcluded {
|
||||
t.Errorf("feature.x should be excluded or absent: %+v", c)
|
||||
}
|
||||
cfg := file(st, "config/app/app.yaml")
|
||||
for _, want := range []string{"hosts:\n - a.example.org\n - b.example.org", "owner: admin@a.example.org", "listen: :8080", "first: a.example.org", "n: 2", "max: 10"} {
|
||||
if !strings.Contains(cfg, want) {
|
||||
t.Errorf("config lacks %q:\n%s", want, cfg)
|
||||
}
|
||||
}
|
||||
if file(st, "config/bak/bak.yaml") != "" || file(st, "config/idp/idp.yaml") != "" {
|
||||
t.Error("files for packages that are not selected")
|
||||
}
|
||||
if len(st.Steps) != 3 { // 2 hosts + 1 program (server; extra is disabled)
|
||||
t.Errorf("steps: %+v", st.Steps)
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario B: local -> central identity and back (ACC-B, RULE-06).
|
||||
func TestIdentitySwitch(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
base := map[string]any{"hosts": []any{"a.example.org"}}
|
||||
st := eval(t, e, catalog.LevelGuided, base, nil)
|
||||
if pkg(st, "idp") != nil {
|
||||
t.Fatal("idp without central identity")
|
||||
}
|
||||
central := map[string]any{"hosts": []any{"a.example.org"}, "identity": "central"}
|
||||
st = eval(t, e, catalog.LevelGuided, central, nil)
|
||||
if !question(st, "realm").Visible || st.Complete {
|
||||
t.Fatal("realm must appear and be required")
|
||||
}
|
||||
central["realm"] = "corp"
|
||||
st = eval(t, e, catalog.LevelGuided, central, nil)
|
||||
if !st.Complete {
|
||||
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
|
||||
}
|
||||
if p := pkg(st, "idp"); p == nil || !p.Selected {
|
||||
t.Fatal("idp must be selected")
|
||||
}
|
||||
if c := capOf(st, "auth.sso"); c == nil || c.Provider != "idp/sso" {
|
||||
t.Fatalf("auth.sso must come from idp, not the unimplemented module: %+v", c)
|
||||
}
|
||||
if !strings.Contains(file(st, "config/app/app.yaml"), "realm: corp") || file(st, "config/idp/idp.yaml") == "" {
|
||||
t.Error("central identity config missing")
|
||||
}
|
||||
edge := false
|
||||
for _, ed := range st.Graph.Edges {
|
||||
edge = edge || (ed.From == "pkg:app" && ed.To == "pkg:idp" && ed.Type == "authenticatesVia")
|
||||
}
|
||||
if !edge {
|
||||
t.Error("confirmed Big Picture connection app -> idp missing from the graph")
|
||||
}
|
||||
// back to local: realm is stale, not in the config, idp gone
|
||||
central["identity"] = "local"
|
||||
st = eval(t, e, catalog.LevelGuided, central, nil)
|
||||
if pkg(st, "idp") != nil || strings.Contains(file(st, "config/app/app.yaml"), "realm") {
|
||||
t.Error("central leftovers after switching back")
|
||||
}
|
||||
if len(st.Stale) != 1 || st.Stale[0].Question != "realm" {
|
||||
t.Errorf("stale: %+v", st.Stale)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotImplementedOptionIsVisibleButNotSelectable(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
st := eval(t, e, catalog.LevelGuided, map[string]any{"hosts": []any{"a.example.org"}, "identity": "ghost"}, nil)
|
||||
q := question(st, "identity")
|
||||
var ghost OptionState
|
||||
for _, o := range q.Options {
|
||||
if o.ID == "ghost" {
|
||||
ghost = o
|
||||
}
|
||||
}
|
||||
if ghost.Enabled || ghost.Disabled != "not built" {
|
||||
t.Errorf("ghost option: %+v", ghost)
|
||||
}
|
||||
if len(st.Stale) != 1 || q.Value != "local" {
|
||||
t.Errorf("the unselectable answer must be stale and the default used: %+v %v", st.Stale, q.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModeSwitchKeepsAnswers(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
params := map[string]any{"hosts": []any{"a.example.org"}, "port": 9090}
|
||||
adv := eval(t, e, catalog.LevelAdvanced, params, nil)
|
||||
quick := eval(t, e, catalog.LevelQuick, params, nil)
|
||||
if file(adv, "config/app/app.yaml") != file(quick, "config/app/app.yaml") {
|
||||
t.Error("the mode must not change the result")
|
||||
}
|
||||
if !strings.Contains(file(quick, "config/app/app.yaml"), ":9090") {
|
||||
t.Error("an advanced answer is lost in quick mode")
|
||||
}
|
||||
if question(quick, "port").Asked {
|
||||
t.Error("quick mode asks an advanced question")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationAndSecrets(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
st := eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"not a host"}, "token": "hunter2"}, nil)
|
||||
if len(question(st, "hosts").Errors) == 0 {
|
||||
t.Error("an invalid host name is accepted")
|
||||
}
|
||||
if len(question(st, "token").Errors) == 0 {
|
||||
t.Error("a plain secret is accepted")
|
||||
}
|
||||
st = eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"a.example.org"}, "token": "secret://app/token"}, nil)
|
||||
if !st.Complete || !strings.Contains(file(st, "config/app/app.yaml"), "token: secret://app/token") {
|
||||
t.Errorf("secret reference not taken: %v", st.Messages)
|
||||
}
|
||||
for _, p := range e.Handbook(st, nil) {
|
||||
if strings.Contains(string(p.Content), "secret://app/token") && strings.HasSuffix(p.Path, "index.md") {
|
||||
t.Error("the handbook's decision table shows a secret reference")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario G: a preset answers everything but the instance-specific questions.
|
||||
func TestPreset(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelGuided)
|
||||
in.Spec.Parameters = map[string]any{"hosts": []any{"a.example.org"}, "size": "big", "backup": "mine", "token": "secret://x"}
|
||||
p := PresetFrom("mine", in, e.Cat.Solutions["app-run"])
|
||||
if _, ok := p.Spec.Parameters["hosts"]; ok {
|
||||
t.Error("an instance-specific answer in the preset")
|
||||
}
|
||||
if _, ok := p.Spec.Parameters["token"]; ok {
|
||||
t.Error("a secret in the preset")
|
||||
}
|
||||
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"new.example.org"}}, p)
|
||||
if !st.Complete || pkg(st, "app").Profile != "big" || st.Answers["size"].Origin != "preset:mine" {
|
||||
t.Fatalf("preset not applied: %+v %v", st.Answers["size"], st.Messages)
|
||||
}
|
||||
if question(st, "size").Asked {
|
||||
t.Error("a question the preset answered is asked again")
|
||||
}
|
||||
if !question(st, "hosts").Asked {
|
||||
t.Error("the instance-specific question must be asked")
|
||||
}
|
||||
if !hasMsg(st, "Big needs more memory") {
|
||||
t.Error("rule message missing")
|
||||
}
|
||||
if !strings.Contains(file(st, "config/app/extra.yaml"), "on: true") || !strings.Contains(file(st, "config/app/app.yaml"), "max: 100") {
|
||||
t.Error("profile inheritance (big extends base) not applied")
|
||||
}
|
||||
if c := capOf(st, "backup.files"); c == nil || c.Status != StExternal {
|
||||
t.Errorf("backup by own tool must be external: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplainAndOverride(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
|
||||
in.Spec.Overrides = []Override{{File: "app/app.yaml", Path: "limits.min", Value: 5}}
|
||||
st, err := e.Evaluate(in, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ex := Explain(st, "app/app.yaml", "owner")
|
||||
if !ex.Found || ex.Origin.Source != "solution:app-run#main" || ex.Origins["owner"] != "default" {
|
||||
t.Errorf("explain owner: %+v", ex)
|
||||
}
|
||||
if ex := Explain(st, "config/app/app.yaml", "limits.max"); ex.Origin.Source != "profile:app/base" {
|
||||
t.Errorf("explain limits.max: %+v", ex)
|
||||
}
|
||||
if ex := Explain(st, "app/app.yaml", "limits.min"); ex.Origin.Layer != "override" {
|
||||
t.Errorf("explain override: %+v", ex)
|
||||
}
|
||||
if !strings.Contains(file(st, "config/app/app.yaml"), "min: 5") {
|
||||
t.Error("override not applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeterministicAndJSON(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
p := map[string]any{"hosts": []any{"a.example.org", "b.example.org"}, "identity": "central", "realm": "r"}
|
||||
a, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
|
||||
for i := 0; i < 5; i++ {
|
||||
b, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
|
||||
if string(a) != string(b) {
|
||||
t.Fatal("evaluation is not deterministic")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateWriteAndProtect(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
|
||||
st, _ := e.Evaluate(in, nil)
|
||||
out, err := e.Generate(st, in, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if err := Write(dir, out, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// regenerating unchanged is fine
|
||||
if err := Write(dir, out, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a hand edit blocks regeneration (CONF-06)
|
||||
cfg := filepath.Join(dir, "config", "app", "app.yaml")
|
||||
if err := os.WriteFile(cfg, []byte("# mine\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Write(dir, out, false); !errors.Is(err, ErrModified) {
|
||||
t.Fatalf("hand edit overwritten: %v", err)
|
||||
}
|
||||
if err := Write(dir, out, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// an incomplete state does not generate
|
||||
in2 := NewInstance("t2", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||
st2, _ := e.Evaluate(in2, nil)
|
||||
if _, err := e.Generate(st2, in2, nil, false); !errors.Is(err, ErrIncomplete) {
|
||||
t.Errorf("incomplete generated: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockDrift(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
|
||||
st, _ := e.Evaluate(in, nil)
|
||||
out, _ := e.Generate(st, in, nil, false)
|
||||
out2, _ := e.Generate(st, in, nil, false)
|
||||
if d := LockDrift(out.Lock, out2.Lock); len(d) != 0 {
|
||||
t.Errorf("drift without change: %v", d)
|
||||
}
|
||||
changed := *out.Lock
|
||||
changed.Spec.Profiles = append([]Pinned{}, out.Lock.Spec.Profiles...)
|
||||
changed.Spec.Profiles[0].Hash = "x"
|
||||
if d := LockDrift(&changed, out2.Lock); len(d) != 1 || !strings.Contains(d[0], "profile app/base changed") {
|
||||
t.Errorf("profile change not detected: %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStepsChecksGraph(t *testing.T) {
|
||||
e := New(testCat(t))
|
||||
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"a.example.org"}, "size": "big"}, nil)
|
||||
if st.Steps[0].Phase != "install" || len(st.Steps) != 3 {
|
||||
t.Errorf("steps: %+v", st.Steps)
|
||||
}
|
||||
if st.Steps[0].Run != "yet install app-server" || st.Steps[1].Run != "yet install app-extra" {
|
||||
t.Errorf("module steps: %+v", st.Steps)
|
||||
}
|
||||
for _, c := range st.Checks {
|
||||
switch c.ID {
|
||||
case "port":
|
||||
if c.Status != CheckNotChecked || c.Params["port"] != "8080" {
|
||||
t.Errorf("port check: %+v", c)
|
||||
}
|
||||
case "bigonly":
|
||||
if c.Status != CheckNotChecked {
|
||||
t.Errorf("bigonly: %+v", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
found := false
|
||||
for _, n := range st.Graph.Nodes {
|
||||
found = found || n.Title == "Users of a.example.org"
|
||||
}
|
||||
if !found {
|
||||
t.Error("node title not interpolated")
|
||||
}
|
||||
if !strings.Contains(GraphText(st.Graph), "app-extra") {
|
||||
t.Error(GraphText(st.Graph))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConditionOrderIsEnforced(t *testing.T) {
|
||||
c := testCat(t)
|
||||
s := c.Solutions["app-run"]
|
||||
q, _ := s.Question("size")
|
||||
q.VisibleWhen = catalog.Cond{"hosts": map[string]any{"set": true}}
|
||||
defer func() { q.VisibleWhen = nil }()
|
||||
found := false
|
||||
for _, i := range c.Validate() {
|
||||
found = found || i.Code == "condition-order"
|
||||
}
|
||||
if !found {
|
||||
t.Error("a condition on a later question is not reported")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,998 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// GeneratorVersion is stamped into lock files; the program embedding the
|
||||
// engine may set it to its own version.
|
||||
var GeneratorVersion = "dev"
|
||||
|
||||
// ErrNotFound is returned for unknown solutions, tasks, examples.
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
// Engine evaluates instances against one catalog. It is safe for
|
||||
// concurrent use: Evaluate does not modify the catalog.
|
||||
type Engine struct {
|
||||
Cat *catalog.Catalog
|
||||
}
|
||||
|
||||
// New returns an engine for a validated catalog.
|
||||
func New(c *catalog.Catalog) *Engine { return &Engine{Cat: c} }
|
||||
|
||||
type evaluation struct {
|
||||
e *Engine
|
||||
s *catalog.Solution
|
||||
in *Instance
|
||||
preset *Preset
|
||||
st *State
|
||||
answers map[string]any
|
||||
env catalog.Env
|
||||
|
||||
reqPkg, recPkg, discPkg, conflPkg map[string][]string
|
||||
reqCap, recCap, discCap, exclCap, implCap map[string][]string
|
||||
extCap map[string]string
|
||||
exclMod, reqMod map[string][]string
|
||||
|
||||
pkgs map[string]*PackageState
|
||||
mods map[string]map[string]*ModuleState // pkg -> module -> state
|
||||
caps map[string]*CapState
|
||||
pkgSeen []string
|
||||
}
|
||||
|
||||
// Evaluate computes the full State of an instance (and an optional preset).
|
||||
func (e *Engine) Evaluate(in *Instance, preset *Preset) (*State, error) {
|
||||
s := e.Cat.Lookup(in.Spec.Solution.ID)
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("%w: solution or task %q", ErrNotFound, in.Spec.Solution.ID)
|
||||
}
|
||||
mode := in.Spec.Mode
|
||||
if mode == "" {
|
||||
mode = catalog.LevelQuick
|
||||
}
|
||||
loc := in.Spec.Locale
|
||||
if loc == "" {
|
||||
loc = "en"
|
||||
}
|
||||
st := &State{
|
||||
Solution: SolutionInfo{
|
||||
ID: s.Meta.ID, Kind: s.Kind, TaskKind: s.Spec.Kind, Version: s.Meta.Version,
|
||||
Title: e.title(s, loc), Summary: e.summary(s, loc), Status: statusOf(s.Meta.Status),
|
||||
Category: s.Meta.Category, BigPicture: s.Spec.BigPicture,
|
||||
},
|
||||
Instance: in.Metadata.Name, Mode: mode, Locale: loc, Platform: in.Spec.Platform,
|
||||
Answers: map[string]Answer{},
|
||||
Messages: []Message{}, Rules: []AppliedRule{}, Packages: []PackageState{},
|
||||
Capabilities: []CapState{}, Files: []FilePreview{}, Steps: []PlannedStep{},
|
||||
Checks: []CheckResult{}, References: []string{},
|
||||
}
|
||||
ev := &evaluation{
|
||||
e: e, s: s, in: in, preset: preset, st: st, answers: map[string]any{},
|
||||
reqPkg: map[string][]string{}, recPkg: map[string][]string{}, discPkg: map[string][]string{}, conflPkg: map[string][]string{},
|
||||
reqCap: map[string][]string{}, recCap: map[string][]string{}, discCap: map[string][]string{},
|
||||
exclCap: map[string][]string{}, implCap: map[string][]string{}, extCap: map[string]string{},
|
||||
exclMod: map[string][]string{}, reqMod: map[string][]string{},
|
||||
pkgs: map[string]*PackageState{}, mods: map[string]map[string]*ModuleState{}, caps: map[string]*CapState{},
|
||||
}
|
||||
ev.env = catalog.Env{Answers: ev.answers, Mode: mode, Platform: in.Spec.Platform}
|
||||
if in.Spec.Solution.Version != "" && in.Spec.Solution.Version != s.Meta.Version {
|
||||
ev.msg("warning", "version", fmt.Sprintf("these answers were made for %s %s; the catalog now has %s. Review the answers (LOCK-02).", s.Meta.ID, in.Spec.Solution.Version, s.Meta.Version), "")
|
||||
}
|
||||
if preset != nil && preset.Spec.Solution != "" && preset.Spec.Solution != s.Meta.ID {
|
||||
ev.msg("warning", "preset", fmt.Sprintf("preset %q is for %s, not %s; only matching answers are used", preset.Metadata.Name, preset.Spec.Solution, s.Meta.ID), "")
|
||||
}
|
||||
for k := range in.Spec.Parameters {
|
||||
if q, _ := s.Question(k); q == nil {
|
||||
ev.msg("warning", "unknown-parameter", fmt.Sprintf("parameter %q is not a question of %s and is ignored", k, s.Meta.ID), "")
|
||||
}
|
||||
}
|
||||
ev.questions()
|
||||
ev.effects()
|
||||
ev.packages()
|
||||
ev.capabilities()
|
||||
ev.finishModules()
|
||||
ev.config()
|
||||
ev.steps()
|
||||
ev.checks()
|
||||
ev.graph()
|
||||
ev.finish()
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func statusOf(s catalog.Support) catalog.Support {
|
||||
if s == "" {
|
||||
return catalog.Supported
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- text ----------------------------------------------------------------
|
||||
|
||||
// Tr returns the translation of field in loc, or base.
|
||||
func Tr(t catalog.Translations, loc, field, base string) string {
|
||||
if loc != "" && loc != "en" {
|
||||
if m, ok := t[loc]; ok {
|
||||
if v, ok := m[field]; ok && v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func (e *Engine) title(s *catalog.Solution, loc string) string {
|
||||
base := s.Meta.Title
|
||||
if base == "" && e.Cat.BigPicture != nil {
|
||||
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
|
||||
base = g.Title
|
||||
}
|
||||
}
|
||||
return Tr(s.Meta.Translations, loc, "title", base)
|
||||
}
|
||||
|
||||
func (e *Engine) summary(s *catalog.Solution, loc string) string {
|
||||
base := s.Meta.Summary
|
||||
if base == "" && e.Cat.BigPicture != nil {
|
||||
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
|
||||
base = g.Intent
|
||||
}
|
||||
}
|
||||
return Tr(s.Meta.Translations, loc, "summary", base)
|
||||
}
|
||||
|
||||
// PackageTitle and PackageSummary come from the Big Picture (ADR-0002).
|
||||
func (e *Engine) PackageSummary(id string) string {
|
||||
p := e.Cat.Packages[id]
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
if p.Meta.Summary != "" {
|
||||
return p.Meta.Summary
|
||||
}
|
||||
if e.Cat.BigPicture != nil {
|
||||
if bp, ok := e.Cat.BigPicture.Products[p.Spec.BigPicture]; ok {
|
||||
return bp.Summary
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (ev *evaluation) msg(sev, code, text, source string) {
|
||||
ev.st.Messages = append(ev.st.Messages, Message{Severity: sev, Code: code, Text: text, Source: source})
|
||||
}
|
||||
|
||||
func add(m map[string][]string, k, reason string) {
|
||||
for _, r := range m[k] {
|
||||
if r == reason {
|
||||
return
|
||||
}
|
||||
}
|
||||
m[k] = append(m[k], reason)
|
||||
}
|
||||
|
||||
// ---- questions -------------------------------------------------------------
|
||||
|
||||
func platformOK(list []string, p string) bool {
|
||||
if len(list) == 0 || p == "" {
|
||||
return true
|
||||
}
|
||||
for _, x := range list {
|
||||
if x == p {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (ev *evaluation) stale(q string, v any, reason string) {
|
||||
ev.st.Stale = append(ev.st.Stale, StaleAnswer{Question: q, Value: v, Reason: reason})
|
||||
}
|
||||
|
||||
func (ev *evaluation) questions() {
|
||||
s, st, loc := ev.s, ev.st, ev.st.Locale
|
||||
mode := st.Mode
|
||||
askedIdx := 0
|
||||
for i := range s.Spec.Questions {
|
||||
q := &s.Spec.Questions[i]
|
||||
qs := QuestionState{
|
||||
ID: q.ID, Type: q.Type, Item: q.Item, Group: q.Group, Level: levelOf(q.Level),
|
||||
Title: Tr(q.Translations, loc, "title", q.Title),
|
||||
Help: Tr(q.Translations, loc, "help", q.Help),
|
||||
Description: Tr(q.Translations, loc, "description", q.Description),
|
||||
Decide: Tr(q.Translations, loc, "decide", q.Decide),
|
||||
Placeholder: Tr(q.Translations, loc, "placeholder", q.Placeholder),
|
||||
Examples: q.Examples, InstanceSpecific: q.InstanceSpecific,
|
||||
Recommended: q.Recommended, Reason: Tr(q.Translations, loc, "reason", q.Reason),
|
||||
References: q.References,
|
||||
}
|
||||
explicit, hasExplicit := ev.in.Spec.Parameters[q.ID]
|
||||
qs.Visible = q.VisibleWhen.Holds(ev.env) && platformOK(q.Platforms, ev.in.Spec.Platform)
|
||||
if !qs.Visible {
|
||||
if hasExplicit {
|
||||
ev.stale(q.ID, explicit, "the question does not apply to the current answers")
|
||||
}
|
||||
st.Questions = append(st.Questions, qs)
|
||||
continue
|
||||
}
|
||||
qs.Required = q.Required || (len(q.RequiredWhen) > 0 && q.RequiredWhen.Holds(ev.env))
|
||||
|
||||
// options and their availability
|
||||
enabled := map[string]bool{}
|
||||
for _, o := range q.Options {
|
||||
os := OptionState{
|
||||
ID: o.ID, Title: Tr(o.Translations, loc, "title", o.Title),
|
||||
Description: Tr(o.Translations, loc, "description", o.Description),
|
||||
Recommended: o.Recommended, Reason: Tr(o.Translations, loc, "reason", o.Reason),
|
||||
Support: statusOf(o.Support), SupportNote: Tr(o.Translations, loc, "supportNote", o.SupportNote),
|
||||
References: o.References,
|
||||
}
|
||||
os.Enabled = o.Support.Selectable()
|
||||
if !os.Enabled {
|
||||
os.Disabled = os.SupportNote
|
||||
} else if len(o.EnabledWhen) > 0 && !o.EnabledWhen.Holds(ev.env) {
|
||||
os.Enabled = false
|
||||
os.Disabled = "not available with the answers given before"
|
||||
}
|
||||
enabled[o.ID] = os.Enabled
|
||||
for _, t := range []*catalog.Targets{o.Effects.Requires, o.Effects.Implies} {
|
||||
if t != nil {
|
||||
for _, p := range t.Packages {
|
||||
os.Adds = append(os.Adds, "package:"+p)
|
||||
}
|
||||
for _, c := range t.Capabilities {
|
||||
os.Adds = append(os.Adds, "capability:"+c)
|
||||
}
|
||||
}
|
||||
}
|
||||
qs.Options = append(qs.Options, os)
|
||||
}
|
||||
checkOpts := func(v any) string {
|
||||
if q.Type != "select" && q.Type != "multiselect" {
|
||||
return ""
|
||||
}
|
||||
for _, x := range listOf(v) {
|
||||
if !enabled[catalog.Scalar(x)] {
|
||||
for _, o := range qs.Options {
|
||||
if o.ID == catalog.Scalar(x) {
|
||||
return fmt.Sprintf("option %q is not available: %s", o.ID, o.Disabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// default (defaultWhen first match wins)
|
||||
def := q.Default
|
||||
for _, dw := range q.DefaultWhen {
|
||||
if dw.When.Holds(ev.env) {
|
||||
def = dw.Value
|
||||
break
|
||||
}
|
||||
}
|
||||
if ds, ok := def.(string); ok && strings.Contains(ds, "${") {
|
||||
// a default built from earlier answers (postmaster@${domains[0]})
|
||||
if x, err := expand(ds, ev.vars()); err == nil {
|
||||
def = strings.Trim(x, "'")
|
||||
} else {
|
||||
def = nil
|
||||
}
|
||||
}
|
||||
if def != nil {
|
||||
if n, err := Normalize(q, def); err == nil {
|
||||
def = n
|
||||
if bad := checkOpts(def); bad != "" {
|
||||
def = ev.fallbackOption(q, enabled)
|
||||
}
|
||||
} else {
|
||||
ev.msg("error", "default", fmt.Sprintf("question %s: default %v is invalid: %v", q.ID, def, err), "catalog")
|
||||
def = nil
|
||||
}
|
||||
}
|
||||
qs.Default = def
|
||||
|
||||
var val any
|
||||
origin := ""
|
||||
if hasExplicit {
|
||||
n, err := Normalize(q, explicit)
|
||||
switch {
|
||||
case err != nil:
|
||||
qs.Errors = append(qs.Errors, err.Error())
|
||||
case checkOpts(n) != "":
|
||||
ev.stale(q.ID, explicit, checkOpts(n))
|
||||
default:
|
||||
val, origin = n, "instance"
|
||||
}
|
||||
}
|
||||
if origin == "" && ev.preset != nil && !q.InstanceSpecific && q.Type != "secret" &&
|
||||
(ev.preset.Spec.Solution == "" || ev.preset.Spec.Solution == ev.s.Meta.ID) {
|
||||
if pv, ok := ev.preset.Spec.Parameters[q.ID]; ok {
|
||||
if n, err := Normalize(q, pv); err == nil && checkOpts(n) == "" {
|
||||
val, origin = n, "preset:"+ev.preset.Metadata.Name
|
||||
} else {
|
||||
ev.msg("warning", "preset", fmt.Sprintf("preset value for %s is not valid any more and is ignored", q.ID), "preset:"+ev.preset.Metadata.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if origin == "" && len(qs.Errors) == 0 && def != nil {
|
||||
val, origin = def, "default"
|
||||
}
|
||||
if val != nil && len(qs.Errors) == 0 {
|
||||
for _, vw := range q.ValidateWhen {
|
||||
if vw.When.Holds(ev.env) {
|
||||
var err error
|
||||
if l, isList := val.([]any); isList {
|
||||
err = checkCount(vw.Validation, len(l))
|
||||
} else {
|
||||
err = checkValue(vw.Validation, val)
|
||||
}
|
||||
if err != nil {
|
||||
qs.Errors = append(qs.Errors, err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
levelAsked := qs.Level.Rank() <= mode.Rank()
|
||||
missing := qs.Required && (!catalog.IsSet(val) || len(qs.Errors) > 0)
|
||||
qs.Asked = (levelAsked && !strings.HasPrefix(origin, "preset:")) || missing || len(qs.Errors) > 0
|
||||
if qs.Asked && q.InstanceSpecific {
|
||||
qs.Asked = true
|
||||
}
|
||||
if val != nil && len(qs.Errors) == 0 {
|
||||
ev.answers[q.ID] = val
|
||||
st.Answers[q.ID] = Answer{Value: val, Origin: origin}
|
||||
qs.Value, qs.Origin = val, origin
|
||||
}
|
||||
for j := range qs.Options {
|
||||
for _, x := range listOf(qs.Value) {
|
||||
if catalog.Scalar(x) == qs.Options[j].ID {
|
||||
qs.Options[j].Selected = true
|
||||
if sup := qs.Options[j].Support; sup == catalog.Experimental || sup == catalog.Untested || sup == catalog.Discouraged || sup == catalog.NeedsPrereq {
|
||||
ev.msg("warning", "support-"+string(sup), fmt.Sprintf("%s: %q is %s. %s", qs.Title, qs.Options[j].Title, sup, qs.Options[j].SupportNote), "question:"+q.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, w := range q.Warnings {
|
||||
if w.When.Holds(ev.env) {
|
||||
sev := w.Severity
|
||||
if sev == "" {
|
||||
sev = "warning"
|
||||
}
|
||||
m := Message{Severity: sev, Code: "question", Text: Tr(q.Translations, loc, "warning", w.Text), Source: "question:" + q.ID}
|
||||
qs.Warnings = append(qs.Warnings, m)
|
||||
st.Messages = append(st.Messages, m)
|
||||
}
|
||||
}
|
||||
if missing {
|
||||
st.Progress.Missing = append(st.Progress.Missing, q.ID)
|
||||
}
|
||||
if qs.Asked {
|
||||
st.Progress.Asked++
|
||||
askedIdx++
|
||||
if origin == "instance" {
|
||||
st.Progress.Answered++
|
||||
} else if st.Next == "" {
|
||||
st.Next = q.ID
|
||||
st.Progress.Step = askedIdx
|
||||
}
|
||||
}
|
||||
st.Questions = append(st.Questions, qs)
|
||||
}
|
||||
if st.Next == "" {
|
||||
st.Progress.Step = askedIdx
|
||||
}
|
||||
// what needs attention first: a missing or invalid answer
|
||||
idx := 0
|
||||
for _, q := range st.Questions {
|
||||
if q.Visible && q.Asked {
|
||||
idx++
|
||||
if len(q.Errors) > 0 || (q.Required && !catalog.IsSet(q.Value)) {
|
||||
st.Next, st.Progress.Step = q.ID, idx
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func levelOf(l catalog.Level) catalog.Level {
|
||||
if l == "" {
|
||||
return catalog.LevelQuick
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// fallbackOption: the recommended enabled option, else the first enabled.
|
||||
func (ev *evaluation) fallbackOption(q *catalog.Question, enabled map[string]bool) any {
|
||||
for _, o := range q.Options {
|
||||
if o.Recommended && enabled[o.ID] {
|
||||
return o.ID
|
||||
}
|
||||
}
|
||||
for _, o := range q.Options {
|
||||
if enabled[o.ID] {
|
||||
return o.ID
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- effects of options and rules ----------------------------------------
|
||||
|
||||
func (ev *evaluation) effects() {
|
||||
for i := range ev.s.Spec.Questions {
|
||||
q := &ev.s.Spec.Questions[i]
|
||||
v, ok := ev.answers[q.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, o := range q.Options {
|
||||
for _, x := range listOf(v) {
|
||||
if catalog.Scalar(x) == o.ID {
|
||||
ev.apply("option "+q.ID+"="+o.ID, "option", o.Effects, o.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, r := range ev.s.Spec.Rules {
|
||||
if !r.When.Holds(ev.env) {
|
||||
continue
|
||||
}
|
||||
ev.apply("rule "+r.ID, "rule", r.Effects, r.Reason)
|
||||
if r.Message != "" {
|
||||
sev := r.Severity
|
||||
if sev == "" {
|
||||
sev = "warning"
|
||||
}
|
||||
ev.msg(sev, "rule", r.Message, "rule:"+r.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ev *evaluation) apply(source, kind string, fx catalog.Effects, reason string) {
|
||||
var parts []string
|
||||
put := func(t *catalog.Targets, pk, cp map[string][]string, verb string) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
for _, p := range t.Packages {
|
||||
if pk != nil {
|
||||
add(pk, p, source)
|
||||
}
|
||||
parts = append(parts, verb+" package "+p)
|
||||
}
|
||||
for _, c := range t.Capabilities {
|
||||
if cp != nil {
|
||||
add(cp, c, source)
|
||||
}
|
||||
parts = append(parts, verb+" "+c)
|
||||
}
|
||||
for _, m := range t.Modules {
|
||||
if verb == "excludes" {
|
||||
add(ev.exclMod, m, source)
|
||||
} else if verb == "requires" || verb == "implies" {
|
||||
add(ev.reqMod, m, source)
|
||||
}
|
||||
parts = append(parts, verb+" module "+m)
|
||||
}
|
||||
for q, want := range t.Answers {
|
||||
parts = append(parts, fmt.Sprintf("%s %s=%v", verb, q, want))
|
||||
if verb == "excludes" || verb == "conflicts" {
|
||||
if have, ok := ev.answers[q]; ok && matchesAnswer(have, want) {
|
||||
ev.msg("error", "conflict", fmt.Sprintf("%s=%v cannot be combined with this choice (%s)", q, catalog.Scalar(want), source), source)
|
||||
}
|
||||
}
|
||||
if verb == "requires" {
|
||||
if have, ok := ev.answers[q]; !ok || !matchesAnswer(have, want) {
|
||||
ev.msg("error", "requires-answer", fmt.Sprintf("%s requires %s=%v", source, q, catalog.Scalar(want)), source)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
put(fx.Requires, ev.reqPkg, ev.reqCap, "requires")
|
||||
put(fx.Implies, ev.reqPkg, ev.implCap, "implies")
|
||||
put(fx.Excludes, nil, ev.exclCap, "excludes")
|
||||
put(fx.Conflicts, ev.conflPkg, ev.exclCap, "conflicts")
|
||||
put(fx.Recommends, ev.recPkg, ev.recCap, "recommends")
|
||||
put(fx.Discourages, ev.discPkg, ev.discCap, "discourages")
|
||||
for _, c := range fx.Provides {
|
||||
ev.extCap[c] = source
|
||||
parts = append(parts, "provides "+c+" (external)")
|
||||
}
|
||||
if len(parts) == 0 && kind == "option" {
|
||||
return
|
||||
}
|
||||
sort.Strings(parts)
|
||||
ev.st.Rules = append(ev.st.Rules, AppliedRule{ID: source, Source: kind, Effect: strings.Join(parts, "; "), Reason: reason})
|
||||
}
|
||||
|
||||
func matchesAnswer(have, want any) bool {
|
||||
for _, h := range listOf(have) {
|
||||
for _, w := range listOf(want) {
|
||||
if catalog.Equal(h, w) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ---- packages, capabilities, modules ---------------------------------------
|
||||
|
||||
func (ev *evaluation) pkg(id, status, reason string) *PackageState {
|
||||
p, ok := ev.pkgs[id]
|
||||
if !ok {
|
||||
cp := ev.e.Cat.Packages[id]
|
||||
title := id
|
||||
_ = cp
|
||||
p = &PackageState{ID: id, Title: title, Summary: ev.e.PackageSummary(id), Status: status, Reasons: []string{}}
|
||||
ev.pkgs[id] = p
|
||||
ev.pkgSeen = append(ev.pkgSeen, id)
|
||||
}
|
||||
if rank(status) > rank(p.Status) {
|
||||
p.Status = status
|
||||
}
|
||||
if status == StRequired || status == StSelected || status == StOptional {
|
||||
p.Selected = true
|
||||
}
|
||||
for _, r := range p.Reasons {
|
||||
if r == reason {
|
||||
return p
|
||||
}
|
||||
}
|
||||
if reason != "" {
|
||||
p.Reasons = append(p.Reasons, reason)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func rank(s string) int {
|
||||
switch s {
|
||||
case StRequired:
|
||||
return 4
|
||||
case StSelected:
|
||||
return 3
|
||||
case StOptional:
|
||||
return 2
|
||||
case StRecommended:
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (ev *evaluation) packages() {
|
||||
for _, pu := range ev.s.Spec.Packages {
|
||||
holds := len(pu.When) == 0 || pu.When.Holds(ev.env)
|
||||
if pu.Recommended {
|
||||
// a recommendation never selects a package
|
||||
if holds {
|
||||
ev.pkg(pu.ID, StRecommended, firstNonEmpty(pu.Reason, "recommended for this solution"))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !holds {
|
||||
continue
|
||||
}
|
||||
status := StRequired
|
||||
if pu.Role == "optional" {
|
||||
status = StOptional
|
||||
}
|
||||
p := ev.pkg(pu.ID, status, firstNonEmpty(pu.Reason, "part of this solution"))
|
||||
if pu.Profile != "" {
|
||||
p.Profile = pu.Profile
|
||||
}
|
||||
}
|
||||
for _, id := range catalog.SortedIDs(ev.reqPkg) {
|
||||
for _, r := range ev.reqPkg[id] {
|
||||
ev.pkg(id, StRequired, r)
|
||||
}
|
||||
}
|
||||
for _, id := range catalog.SortedIDs(ev.recPkg) {
|
||||
for _, r := range ev.recPkg[id] {
|
||||
ev.pkg(id, StRecommended, r)
|
||||
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: id, Reason: r, Source: r})
|
||||
}
|
||||
}
|
||||
// modules from profiles
|
||||
for _, id := range ev.pkgSeen {
|
||||
p := ev.pkgs[id]
|
||||
if !p.Selected {
|
||||
continue
|
||||
}
|
||||
ev.mods[id] = map[string]*ModuleState{}
|
||||
cp := ev.e.Cat.Packages[id]
|
||||
for _, m := range cp.Spec.Modules {
|
||||
ev.mods[id][m.ID] = &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
|
||||
}
|
||||
if p.Profile == "" {
|
||||
// no profile: every selectable module of the package is used
|
||||
for _, m := range cp.Spec.Modules {
|
||||
if m.Support.Selectable() {
|
||||
ms := ev.mods[id][m.ID]
|
||||
ms.Enabled = true
|
||||
ms.Reason = "package " + id
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
|
||||
if err != nil {
|
||||
ev.msg("error", "profile", err.Error(), "package:"+id)
|
||||
continue
|
||||
}
|
||||
for _, prof := range chain {
|
||||
for mid, state := range prof.Spec.Modules {
|
||||
if ms := ev.mods[id][mid]; ms != nil {
|
||||
ms.Enabled = state == "enabled"
|
||||
ms.Reason = "profile " + prof.Key()
|
||||
}
|
||||
}
|
||||
for _, r := range prof.Spec.Recommendations {
|
||||
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: r.Package, Capability: r.Capability, Reason: r.Reason, Source: "profile:" + prof.Key()})
|
||||
if r.Package != "" {
|
||||
ev.pkg(r.Package, StRecommended, r.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range catalog.SortedIDs(ev.reqMod) {
|
||||
pkg, mod, _ := strings.Cut(m, "/")
|
||||
ev.pkg(pkg, StRequired, ev.reqMod[m][0])
|
||||
ev.ensureMods(pkg)
|
||||
if ms := ev.mods[pkg][mod]; ms != nil {
|
||||
ms.Enabled = true
|
||||
ms.Reason = ev.reqMod[m][0]
|
||||
}
|
||||
}
|
||||
for _, m := range catalog.SortedIDs(ev.exclMod) {
|
||||
pkg, mod, _ := strings.Cut(m, "/")
|
||||
if ms := ev.mods[pkg][mod]; ms != nil {
|
||||
if _, needed := ev.reqMod[m]; needed {
|
||||
ev.msg("error", "module-conflict", fmt.Sprintf("module %s is both required and excluded (%s)", m, ev.exclMod[m][0]), ev.exclMod[m][0])
|
||||
continue
|
||||
}
|
||||
ms.Enabled = false
|
||||
ms.Reason = "excluded by " + ev.exclMod[m][0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ev *evaluation) ensureMods(pkg string) {
|
||||
if ev.mods[pkg] != nil {
|
||||
return
|
||||
}
|
||||
ev.mods[pkg] = map[string]*ModuleState{}
|
||||
cp := ev.e.Cat.Packages[pkg]
|
||||
if cp == nil {
|
||||
return
|
||||
}
|
||||
profile := ""
|
||||
if p := ev.pkgs[pkg]; p != nil {
|
||||
profile = p.Profile
|
||||
}
|
||||
for _, m := range cp.Spec.Modules {
|
||||
ms := &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
|
||||
if profile == "" && m.Support.Selectable() {
|
||||
ms.Enabled, ms.Reason = true, "package "+pkg
|
||||
}
|
||||
ev.mods[pkg][m.ID] = ms
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(a ...string) string {
|
||||
for _, s := range a {
|
||||
if s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (ev *evaluation) capTitle(id string) string {
|
||||
if c, ok := ev.e.Cat.Capabilities[id]; ok {
|
||||
return Tr(c.Translations, ev.st.Locale, "title", c.Title)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func (ev *evaluation) capState(id string) *CapState {
|
||||
c, ok := ev.caps[id]
|
||||
if !ok {
|
||||
c = &CapState{ID: id, Title: ev.capTitle(id), Reasons: []string{}}
|
||||
ev.caps[id] = c
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (ev *evaluation) capabilities() {
|
||||
type need struct{ id, reason string }
|
||||
var queue []need
|
||||
for _, c := range ev.s.Spec.Capabilities.Required {
|
||||
queue = append(queue, need{c, "required by the solution"})
|
||||
}
|
||||
for _, m := range []map[string][]string{ev.reqCap, ev.implCap} {
|
||||
for _, c := range catalog.SortedIDs(m) {
|
||||
queue = append(queue, need{c, m[c][0]})
|
||||
}
|
||||
}
|
||||
// requirements of modules the profiles enabled
|
||||
for _, pid := range ev.pkgSeen {
|
||||
cp := ev.e.Cat.Packages[pid]
|
||||
for _, m := range cp.Spec.Modules {
|
||||
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
|
||||
for _, r := range m.Requires {
|
||||
queue = append(queue, need{r, "needed by " + pid + "/" + m.ID})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
done := map[string]bool{}
|
||||
for steps := 0; len(queue) > 0 && steps < 10000; steps++ {
|
||||
n := queue[0]
|
||||
queue = queue[1:]
|
||||
cs := ev.capState(n.id)
|
||||
add2(&cs.Reasons, n.reason)
|
||||
if done[n.id] {
|
||||
continue
|
||||
}
|
||||
done[n.id] = true
|
||||
cs.Status = StRequired
|
||||
if src, ok := ev.exclCap[n.id]; ok {
|
||||
cs.Status = StConflicting
|
||||
ev.msg("error", "capability-conflict", fmt.Sprintf("%s is needed (%s) but excluded (%s)", n.id, n.reason, src[0]), src[0])
|
||||
continue
|
||||
}
|
||||
if src, ok := ev.extCap[n.id]; ok {
|
||||
cs.Status = StExternal
|
||||
cs.Provider = "external:" + src
|
||||
continue
|
||||
}
|
||||
var chosen *catalog.ModuleRef
|
||||
var alts []string
|
||||
providers := ev.e.Cat.ProvidersOf(n.id)
|
||||
// a module that already provides it wins, then a selected package
|
||||
pick := func(f func(catalog.ModuleRef) bool) {
|
||||
for i := range providers {
|
||||
if chosen == nil && providers[i].Support.Selectable() && f(providers[i]) {
|
||||
chosen = &providers[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
pick(func(r catalog.ModuleRef) bool {
|
||||
ms := ev.mods[r.Package][r.Module]
|
||||
return ms != nil && ms.Enabled
|
||||
})
|
||||
pick(func(r catalog.ModuleRef) bool { return ev.pkgs[r.Package] != nil && ev.pkgs[r.Package].Selected })
|
||||
pick(func(r catalog.ModuleRef) bool { return true })
|
||||
for _, pr := range providers {
|
||||
if chosen == nil || pr != *chosen {
|
||||
alts = append(alts, pr.String())
|
||||
}
|
||||
}
|
||||
if c, ok := ev.e.Cat.Capabilities[n.id]; ok {
|
||||
for _, x := range c.External {
|
||||
alts = append(alts, "external:"+x.ID)
|
||||
}
|
||||
for _, r := range c.Requires {
|
||||
queue = append(queue, need{r, "needed by " + n.id})
|
||||
}
|
||||
}
|
||||
cs.Alternatives = alts
|
||||
if chosen == nil {
|
||||
cs.Status = StMissing
|
||||
ev.msg("error", "capability-missing", fmt.Sprintf("no available provider for %s (%s)", n.id, n.reason), "")
|
||||
continue
|
||||
}
|
||||
cs.Provider = chosen.String()
|
||||
p := ev.pkg(chosen.Package, StRequired, "provides "+n.id)
|
||||
_ = p
|
||||
ev.ensureMods(chosen.Package)
|
||||
ms := ev.mods[chosen.Package][chosen.Module]
|
||||
if !ms.Enabled {
|
||||
if src, excluded := ev.exclMod[chosen.String()]; excluded {
|
||||
cs.Status = StConflicting
|
||||
ev.msg("error", "module-conflict", fmt.Sprintf("%s needs module %s, which is excluded (%s)", n.id, chosen, src[0]), src[0])
|
||||
continue
|
||||
}
|
||||
ms.Enabled = true
|
||||
ms.Reason = "provides " + n.id
|
||||
}
|
||||
cm := ev.e.Cat.Packages[chosen.Package].Module(chosen.Module)
|
||||
for _, r := range cm.Requires {
|
||||
queue = append(queue, need{r, "needed by " + chosen.String()})
|
||||
}
|
||||
}
|
||||
// capabilities provided as a side effect, recommended, optional, excluded
|
||||
for _, pid := range ev.pkgSeen {
|
||||
for _, m := range ev.e.Cat.Packages[pid].Spec.Modules {
|
||||
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
|
||||
for _, c := range m.Provides {
|
||||
if !ev.requiresMet(c) {
|
||||
continue // e.g. AI analysis without an AI server
|
||||
}
|
||||
cs := ev.capState(c)
|
||||
if cs.Status == "" {
|
||||
cs.Status = StSelected
|
||||
cs.Provider = pid + "/" + m.ID
|
||||
add2(&cs.Reasons, "provided by "+pid+"/"+m.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// capabilities the user's answers say exist outside Yetano
|
||||
for _, c := range catalog.SortedIDs(ev.extCap) {
|
||||
cs := ev.capState(c)
|
||||
if cs.Status == "" {
|
||||
cs.Status = StExternal
|
||||
cs.Provider = "external:" + ev.extCap[c]
|
||||
add2(&cs.Reasons, "provided outside Yetano ("+ev.extCap[c]+")")
|
||||
}
|
||||
}
|
||||
soft := func(list []string, m map[string][]string, status, why string) {
|
||||
ids := append([]string{}, list...)
|
||||
ids = append(ids, catalog.SortedIDs(m)...)
|
||||
for _, c := range ids {
|
||||
cs := ev.capState(c)
|
||||
if cs.Status != "" {
|
||||
continue
|
||||
}
|
||||
cs.Status = status
|
||||
r := why
|
||||
if rs, ok := m[c]; ok {
|
||||
r = rs[0]
|
||||
}
|
||||
add2(&cs.Reasons, r)
|
||||
for _, pr := range ev.e.Cat.ProvidersOf(c) {
|
||||
cs.Alternatives = append(cs.Alternatives, pr.String())
|
||||
}
|
||||
if status == StRecommended {
|
||||
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Capability: c, Reason: r, Source: r})
|
||||
}
|
||||
}
|
||||
}
|
||||
soft(ev.s.Spec.Capabilities.Recommended, ev.recCap, StRecommended, "recommended by the solution")
|
||||
soft(ev.s.Spec.Capabilities.Optional, nil, StOptional, "optional for this solution")
|
||||
for _, c := range catalog.SortedIDs(ev.exclCap) {
|
||||
cs := ev.capState(c)
|
||||
// required and excluded was reported above; a capability an enabled
|
||||
// module merely could provide is just not used
|
||||
if cs.Status == "" || cs.Status == StSelected {
|
||||
cs.Status = StExcluded
|
||||
cs.Provider = ""
|
||||
add2(&cs.Reasons, "excluded by "+ev.exclCap[c][0])
|
||||
}
|
||||
}
|
||||
// capability-level conflicts between provided capabilities
|
||||
for _, id := range catalog.SortedIDs(ev.caps) {
|
||||
cs := ev.caps[id]
|
||||
if c, ok := ev.e.Cat.Capabilities[id]; ok && provided(cs.Status) {
|
||||
for _, other := range c.Conflicts {
|
||||
if o, ok := ev.caps[other]; ok && provided(o.Status) && id < other {
|
||||
ev.msg("error", "capability-conflict", fmt.Sprintf("%s and %s cannot be combined", id, other), "capability:"+id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, c := range catalog.SortedIDs(ev.discCap) {
|
||||
if cs, ok := ev.caps[c]; ok && provided(cs.Status) {
|
||||
ev.msg("warning", "discouraged", fmt.Sprintf("%s is possible but not recommended here (%s)", c, ev.discCap[c][0]), ev.discCap[c][0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requiresMet: every capability c requires is required/provided already.
|
||||
func (ev *evaluation) requiresMet(c string) bool {
|
||||
cp, ok := ev.e.Cat.Capabilities[c]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
for _, r := range cp.Requires {
|
||||
if cs, ok := ev.caps[r]; !ok || !provided(cs.Status) {
|
||||
if _, ext := ev.extCap[r]; !ext {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func provided(s string) bool {
|
||||
return s == StRequired || s == StSelected || s == StExternal
|
||||
}
|
||||
|
||||
func add2(list *[]string, s string) {
|
||||
for _, x := range *list {
|
||||
if x == s {
|
||||
return
|
||||
}
|
||||
}
|
||||
*list = append(*list, s)
|
||||
}
|
||||
|
||||
func (ev *evaluation) finishModules() {
|
||||
for _, id := range catalog.SortedIDs(ev.conflPkg) {
|
||||
if p, ok := ev.pkgs[id]; ok && p.Selected {
|
||||
ev.msg("error", "package-conflict", fmt.Sprintf("package %s cannot be used with this choice (%s)", id, ev.conflPkg[id][0]), ev.conflPkg[id][0])
|
||||
}
|
||||
}
|
||||
for _, id := range catalog.SortedIDs(ev.discPkg) {
|
||||
if p, ok := ev.pkgs[id]; ok && p.Selected {
|
||||
ev.msg("warning", "discouraged", fmt.Sprintf("package %s is possible but not recommended here (%s)", id, ev.discPkg[id][0]), ev.discPkg[id][0])
|
||||
}
|
||||
}
|
||||
ids := append([]string{}, ev.pkgSeen...)
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
p := ev.pkgs[id]
|
||||
if p.Selected {
|
||||
cp := ev.e.Cat.Packages[id]
|
||||
for _, m := range cp.Spec.Modules {
|
||||
ms := ev.mods[id][m.ID]
|
||||
if ms == nil {
|
||||
continue
|
||||
}
|
||||
if ms.Enabled && (m.Support == catalog.Experimental || m.Support == catalog.Untested) {
|
||||
ev.msg("warning", "support-"+string(m.Support), fmt.Sprintf("module %s/%s is %s", id, m.ID, m.Support), "package:"+id)
|
||||
}
|
||||
p.Modules = append(p.Modules, *ms)
|
||||
}
|
||||
}
|
||||
ev.st.Packages = append(ev.st.Packages, *p)
|
||||
}
|
||||
for _, id := range catalog.SortedIDs(ev.caps) {
|
||||
ev.st.Capabilities = append(ev.st.Capabilities, *ev.caps[id])
|
||||
}
|
||||
}
|
||||
|
||||
// moduleEnabled reports whether pkg/module is enabled in this evaluation.
|
||||
func (ev *evaluation) moduleEnabled(pkg, mod string) bool {
|
||||
ms := ev.mods[pkg][mod]
|
||||
return ms != nil && ms.Enabled
|
||||
}
|
||||
|
||||
func (ev *evaluation) pkgSelected(id string) bool {
|
||||
p, ok := ev.pkgs[id]
|
||||
return ok && p.Selected
|
||||
}
|
||||
|
||||
func (ev *evaluation) finish() {
|
||||
st := ev.st
|
||||
refs := append([]string{}, ev.s.Spec.References.All()...)
|
||||
for _, q := range st.Questions {
|
||||
if q.Visible {
|
||||
refs = append(refs, q.References...)
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, r := range refs {
|
||||
if !seen[r] {
|
||||
seen[r] = true
|
||||
st.References = append(st.References, r)
|
||||
}
|
||||
}
|
||||
st.Related = ev.s.Spec.Related
|
||||
sort.SliceStable(st.Messages, func(i, j int) bool { return sevRank(st.Messages[i].Severity) > sevRank(st.Messages[j].Severity) })
|
||||
errs := 0
|
||||
for _, m := range st.Messages {
|
||||
if m.Severity == "error" {
|
||||
errs++
|
||||
}
|
||||
}
|
||||
st.Complete = len(st.Progress.Missing) == 0 && errs == 0
|
||||
}
|
||||
|
||||
func sevRank(s string) int {
|
||||
switch s {
|
||||
case "error":
|
||||
return 2
|
||||
case "warning":
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// Graph is the resolved architecture of a state (BP-03/BP-04). Node IDs:
|
||||
// "pkg:<id>", "mod:<pkg>/<module>", "cap:<id>", "ext:<id>" and the
|
||||
// solution's own node IDs ("n:<id>").
|
||||
type Graph struct {
|
||||
Nodes []GraphNode `json:"nodes"`
|
||||
Edges []GraphEdge `json:"edges"`
|
||||
}
|
||||
|
||||
// GraphNode is one node with its state (required, selected, ...).
|
||||
type GraphNode struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"` // package | module | capability | external | client | storage | network | identity | target | solution
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Parent string `json:"parent,omitempty"` // module -> package
|
||||
Ref string `json:"ref,omitempty"` // yetano: reference to open
|
||||
}
|
||||
|
||||
// GraphEdge is a typed relation (requires, provides, connectsTo, ...).
|
||||
type GraphEdge struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Type string `json:"type"`
|
||||
Label string `json:"label,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
func (ev *evaluation) graph() {
|
||||
g := Graph{Nodes: []GraphNode{}, Edges: []GraphEdge{}}
|
||||
have := map[string]bool{}
|
||||
node := func(n GraphNode) {
|
||||
if !have[n.ID] {
|
||||
have[n.ID] = true
|
||||
g.Nodes = append(g.Nodes, n)
|
||||
}
|
||||
}
|
||||
edge := func(e GraphEdge) { g.Edges = append(g.Edges, e) }
|
||||
solID := "sol:" + ev.s.Meta.ID
|
||||
node(GraphNode{ID: solID, Type: "solution", Title: ev.st.Solution.Title, Status: StSelected, Ref: "yetano:solution/" + ev.s.Meta.ID})
|
||||
for _, p := range ev.st.Packages {
|
||||
status := p.Status
|
||||
switch {
|
||||
case !p.Selected:
|
||||
status = StRecommended
|
||||
case status == StOptional:
|
||||
status = StSelected // an optional package the answers chose
|
||||
}
|
||||
pid := "pkg:" + p.ID
|
||||
node(GraphNode{ID: pid, Type: "package", Title: p.ID, Status: status, Ref: "yetano:package/" + p.ID})
|
||||
if p.Selected {
|
||||
edge(GraphEdge{From: solID, To: pid, Type: "requires", Status: status})
|
||||
} else {
|
||||
edge(GraphEdge{From: solID, To: pid, Type: "optional", Label: "recommended", Status: StRecommended})
|
||||
}
|
||||
for _, m := range p.Modules {
|
||||
st := StDisabled
|
||||
if m.Enabled {
|
||||
st = StSelected
|
||||
}
|
||||
if !m.Support.Selectable() {
|
||||
st = StUnsupported
|
||||
}
|
||||
if !m.Enabled {
|
||||
continue // disabled modules stay out of the picture; the package detail lists them
|
||||
}
|
||||
mid := "mod:" + p.ID + "/" + m.ID
|
||||
node(GraphNode{ID: mid, Type: "module", Title: firstNonEmpty(m.Program, m.ID), Status: st, Parent: pid, Ref: "yetano:module/" + p.ID + "/" + m.ID})
|
||||
}
|
||||
}
|
||||
for _, c := range ev.st.Capabilities {
|
||||
cid := "cap:" + c.ID
|
||||
node(GraphNode{ID: cid, Type: "capability", Title: c.Title, Status: c.Status, Ref: "yetano:capability/" + c.ID})
|
||||
switch {
|
||||
case strings.HasPrefix(c.Provider, "external:"):
|
||||
xid := "ext:" + c.ID
|
||||
node(GraphNode{ID: xid, Type: "external", Title: "existing " + c.Title, Status: StExternal})
|
||||
edge(GraphEdge{From: xid, To: cid, Type: "provides", Status: StExternal})
|
||||
case c.Provider != "":
|
||||
pkg, _, _ := strings.Cut(c.Provider, "/")
|
||||
from := "mod:" + c.Provider
|
||||
if !have[from] {
|
||||
from = "pkg:" + pkg
|
||||
}
|
||||
edge(GraphEdge{From: from, To: cid, Type: "provides", Status: c.Status})
|
||||
}
|
||||
if c.Status == StRecommended || c.Status == StOptional || c.Status == StMissing {
|
||||
for _, alt := range c.Alternatives {
|
||||
if strings.HasPrefix(alt, "external:") {
|
||||
continue
|
||||
}
|
||||
pkg, _, _ := strings.Cut(alt, "/")
|
||||
if !have["pkg:"+pkg] {
|
||||
node(GraphNode{ID: "pkg:" + pkg, Type: "package", Title: pkg, Status: StAlternative, Ref: "yetano:package/" + pkg})
|
||||
}
|
||||
edge(GraphEdge{From: "pkg:" + pkg, To: cid, Type: "alternativeTo", Status: StAlternative})
|
||||
}
|
||||
}
|
||||
if c.Status == StRequired || c.Status == StMissing || c.Status == StConflicting {
|
||||
edge(GraphEdge{From: solID, To: cid, Type: "requires", Status: c.Status})
|
||||
}
|
||||
}
|
||||
// not implemented options of visible questions: shown as unsupported alternatives
|
||||
for _, q := range ev.st.Questions {
|
||||
if !q.Visible {
|
||||
continue
|
||||
}
|
||||
for _, o := range q.Options {
|
||||
if o.Support.Selectable() {
|
||||
continue
|
||||
}
|
||||
for _, a := range o.Adds {
|
||||
if p, ok := strings.CutPrefix(a, "package:"); ok && !have["pkg:"+p] {
|
||||
node(GraphNode{ID: "pkg:" + p, Type: "package", Title: p, Status: StUnsupported, Ref: "yetano:package/" + p})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// solution-specific nodes and edges
|
||||
for _, n := range ev.s.Spec.Architecture.Nodes {
|
||||
if len(n.When) > 0 && !n.When.Holds(ev.env) {
|
||||
continue
|
||||
}
|
||||
st := StSelected
|
||||
if n.Type == "external" || n.Type == "client" {
|
||||
st = StExternal
|
||||
}
|
||||
title, err := expand(n.Title, ev.vars())
|
||||
if err != nil {
|
||||
title = n.Title
|
||||
}
|
||||
node(GraphNode{ID: "n:" + n.ID, Type: n.Type, Title: strings.Trim(title, "'"), Status: st})
|
||||
}
|
||||
resolve := func(id string) string {
|
||||
if strings.Contains(id, ":") {
|
||||
return id
|
||||
}
|
||||
return "n:" + id
|
||||
}
|
||||
for _, e := range ev.s.Spec.Architecture.Edges {
|
||||
if len(e.When) > 0 && !e.When.Holds(ev.env) {
|
||||
continue
|
||||
}
|
||||
from, to := resolve(e.From), resolve(e.To)
|
||||
if !have[from] || !have[to] || !inUse(g, from) || !inUse(g, to) {
|
||||
continue // an end that is not part of this resolution
|
||||
}
|
||||
edge(GraphEdge{From: from, To: to, Type: e.Type, Label: e.Label})
|
||||
}
|
||||
// confirmed Big Picture connections between selected packages
|
||||
if bp := ev.e.Cat.BigPicture; bp != nil {
|
||||
byProduct := map[string]string{}
|
||||
for _, p := range ev.st.Packages {
|
||||
if cp := ev.e.Cat.Packages[p.ID]; cp != nil && p.Selected {
|
||||
byProduct[cp.Spec.BigPicture] = "pkg:" + p.ID
|
||||
}
|
||||
}
|
||||
for _, c := range bp.Connections {
|
||||
f, okf := byProduct[c.From]
|
||||
t, okt := byProduct[c.To]
|
||||
if okf && okt && c.Review == "confirmed" {
|
||||
edge(GraphEdge{From: f, To: t, Type: c.Type, Label: c.Label})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(g.Edges, func(i, j int) bool {
|
||||
a, b := g.Edges[i], g.Edges[j]
|
||||
return fmt.Sprint(a.From, a.To, a.Type) < fmt.Sprint(b.From, b.To, b.Type)
|
||||
})
|
||||
ev.st.Graph = g
|
||||
}
|
||||
|
||||
// inUse: the node is part of the solution (not only an alternative).
|
||||
func inUse(g Graph, id string) bool {
|
||||
for _, n := range g.Nodes {
|
||||
if n.ID == id {
|
||||
switch n.Status {
|
||||
case StRequired, StSelected, StExternal:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GraphText renders a graph as indented text for the CLI (BP-06).
|
||||
func GraphText(g Graph) string {
|
||||
var b strings.Builder
|
||||
byID := map[string]GraphNode{}
|
||||
for _, n := range g.Nodes {
|
||||
byID[n.ID] = n
|
||||
}
|
||||
mark := func(status string) string {
|
||||
switch status {
|
||||
case StRequired, StSelected:
|
||||
return "+"
|
||||
case StRecommended, StOptional, StAlternative:
|
||||
return "?"
|
||||
case StExternal:
|
||||
return "~"
|
||||
case StMissing, StConflicting, StUnsupported:
|
||||
return "!"
|
||||
}
|
||||
return " "
|
||||
}
|
||||
for _, n := range g.Nodes {
|
||||
if n.Type != "package" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, "%s %s [%s]\n", mark(n.Status), n.Title, n.Status)
|
||||
for _, m := range g.Nodes {
|
||||
if m.Parent == n.ID {
|
||||
fmt.Fprintf(&b, " %s %s\n", mark(m.Status), m.Title)
|
||||
for _, e := range g.Edges {
|
||||
if e.From == m.ID && e.Type == "provides" {
|
||||
fmt.Fprintf(&b, " provides %s\n", byID[e.To].Title)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var other []string
|
||||
for _, n := range g.Nodes {
|
||||
switch n.Type {
|
||||
case "external", "client", "storage", "network", "identity", "target":
|
||||
other = append(other, fmt.Sprintf("%s %s (%s)", mark(n.Status), n.Title, n.Type))
|
||||
}
|
||||
}
|
||||
if len(other) > 0 {
|
||||
b.WriteString("around it:\n")
|
||||
for _, o := range other {
|
||||
fmt.Fprintf(&b, " %s\n", o)
|
||||
}
|
||||
}
|
||||
var rel []string
|
||||
for _, e := range g.Edges {
|
||||
f, t := byID[e.From], byID[e.To]
|
||||
if e.Type == "provides" || e.Type == "requires" || e.Type == "optional" || f.Type == "solution" {
|
||||
continue
|
||||
}
|
||||
label := e.Type
|
||||
if e.Label != "" {
|
||||
label += " (" + e.Label + ")"
|
||||
}
|
||||
rel = append(rel, fmt.Sprintf(" %s --%s--> %s", f.Title, label, t.Title))
|
||||
}
|
||||
if len(rel) > 0 {
|
||||
b.WriteString("connections:\n")
|
||||
b.WriteString(strings.Join(rel, "\n"))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString("legend: + used ? recommended/optional ~ external ! missing/unsupported\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
var _ = catalog.Supported
|
||||
@@ -0,0 +1,278 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// HandbookPage is one Markdown page of a solution handbook (HB-01).
|
||||
type HandbookPage struct {
|
||||
Path string
|
||||
Content []byte
|
||||
}
|
||||
|
||||
// Handbook composes the handbook of a state from the solution, the
|
||||
// decisions, the generated files and existing manual text (via mr). It
|
||||
// covers only what was chosen (HB-02) and never prints secret values
|
||||
// (HB-04): secret answers are references and are shown as such.
|
||||
func (e *Engine) Handbook(st *State, mr ManualReader) []HandbookPage {
|
||||
s := e.Cat.Lookup(st.Solution.ID)
|
||||
link := func(ref string) string {
|
||||
if mr != nil {
|
||||
if l := mr.Link(ref); l != "" {
|
||||
return l
|
||||
}
|
||||
}
|
||||
return "`" + ref + "`"
|
||||
}
|
||||
excerpt := func(b *strings.Builder, ref string) {
|
||||
if mr == nil {
|
||||
fmt.Fprintf(b, "- %s\n", link(ref))
|
||||
return
|
||||
}
|
||||
title, md, ok := mr.Excerpt(ref, 40)
|
||||
if !ok {
|
||||
fmt.Fprintf(b, "- %s\n", link(ref))
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(b, "> From the manual: **%s** (%s)\n>\n", title, link(ref))
|
||||
for _, line := range strings.Split(strings.TrimRight(md, "\n"), "\n") {
|
||||
fmt.Fprintf(b, "> %s\n", line)
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
var pages []HandbookPage
|
||||
page := func(name, title string, body func(b *strings.Builder)) {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "# %s\n\n", title)
|
||||
body(&b)
|
||||
pages = append(pages, HandbookPage{Path: "handbook/" + name, Content: []byte(b.String())})
|
||||
}
|
||||
selected := []PackageState{}
|
||||
for _, p := range st.Packages {
|
||||
if p.Selected {
|
||||
selected = append(selected, p)
|
||||
}
|
||||
}
|
||||
hasCap := func(prefix string) bool {
|
||||
for _, c := range st.Capabilities {
|
||||
if strings.HasPrefix(c.ID, prefix) && provided(c.Status) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
secretQ := map[string]bool{}
|
||||
for _, q := range s.Spec.Questions {
|
||||
if q.Type == "secret" {
|
||||
secretQ[q.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
page("index.md", "Handbook: "+firstNonEmpty(st.Instance, st.Solution.Title), func(b *strings.Builder) {
|
||||
fmt.Fprintf(b, "%s\n\n", st.Solution.Summary)
|
||||
fmt.Fprintf(b, "Solution `%s` %s, status **%s**.\n\n", st.Solution.ID, st.Solution.Version, st.Solution.Status)
|
||||
b.WriteString("1. [Your architecture](architecture.md)\n2. [Installation and configuration](installation.md)\n3. [Configuration reference](configuration.md)\n4. [Security](security.md)\n5. [Operations and maintenance](operations.md)\n")
|
||||
if hasCap("backup.") {
|
||||
b.WriteString("6. [Backup and restore](backup-restore.md)\n7. [Troubleshooting](troubleshooting.md)\n")
|
||||
} else {
|
||||
b.WriteString("6. [Troubleshooting](troubleshooting.md)\n")
|
||||
}
|
||||
b.WriteString("\n## Your decisions\n\n| Question | Answer | From |\n|---|---|---|\n")
|
||||
for _, q := range st.Questions {
|
||||
if !q.Visible || q.Value == nil {
|
||||
continue
|
||||
}
|
||||
val := answerText(q)
|
||||
if secretQ[q.ID] {
|
||||
val = "(secret reference)"
|
||||
}
|
||||
fmt.Fprintf(b, "| %s | %s | %s |\n", q.Title, val, q.Origin)
|
||||
}
|
||||
if len(st.Messages) > 0 {
|
||||
b.WriteString("\n## Notes and warnings\n\n")
|
||||
for _, m := range st.Messages {
|
||||
fmt.Fprintf(b, "- **%s**: %s\n", m.Severity, m.Text)
|
||||
}
|
||||
}
|
||||
})
|
||||
page("architecture.md", "Your architecture", func(b *strings.Builder) {
|
||||
b.WriteString("```text\n")
|
||||
b.WriteString(GraphText(st.Graph))
|
||||
b.WriteString("```\n\n## Packages\n\n")
|
||||
for _, p := range selected {
|
||||
fmt.Fprintf(b, "### %s\n\n%s\n\n", p.ID, p.Summary)
|
||||
if p.Profile != "" {
|
||||
fmt.Fprintf(b, "Profile: `%s`. ", p.Profile)
|
||||
}
|
||||
fmt.Fprintf(b, "Why: %s.\n\n", strings.Join(p.Reasons, "; "))
|
||||
var on []string
|
||||
for _, m := range p.Modules {
|
||||
if m.Enabled {
|
||||
on = append(on, fmt.Sprintf("`%s`", firstNonEmpty(m.Program, m.ID)))
|
||||
}
|
||||
}
|
||||
if len(on) > 0 {
|
||||
fmt.Fprintf(b, "Programs used: %s.\n\n", strings.Join(on, ", "))
|
||||
}
|
||||
}
|
||||
b.WriteString("## Capabilities\n\n| Capability | Status | Provided by |\n|---|---|---|\n")
|
||||
for _, c := range st.Capabilities {
|
||||
if c.Status == StExcluded {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, "| %s | %s | %s |\n", c.Title, c.Status, firstNonEmpty(c.Provider, "–"))
|
||||
}
|
||||
if st.Solution.BigPicture != "" {
|
||||
fmt.Fprintf(b, "\nIn the Big Picture: %s\n", link("yetano:bigpicture/"+st.Solution.BigPicture))
|
||||
}
|
||||
})
|
||||
page("installation.md", "Installation and configuration", func(b *strings.Builder) {
|
||||
b.WriteString("The guide has not changed any system. These are the steps, in order;\n" +
|
||||
"`deployment-plan.yaml` has the same list in machine-readable form.\n\n")
|
||||
phase := ""
|
||||
n := 0
|
||||
for _, sp := range st.Steps {
|
||||
if sp.Phase != phase {
|
||||
phase = sp.Phase
|
||||
fmt.Fprintf(b, "## %s\n\n", strings.ToUpper(phase[:1])+phase[1:])
|
||||
}
|
||||
n++
|
||||
fmt.Fprintf(b, "%d. %s\n", n, sp.Title)
|
||||
if sp.Run != "" {
|
||||
fmt.Fprintf(b, "\n ```sh\n %s\n ```\n", sp.Run)
|
||||
}
|
||||
if sp.Note != "" {
|
||||
fmt.Fprintf(b, "\n %s\n", sp.Note)
|
||||
}
|
||||
if sp.Reversible != nil && !*sp.Reversible {
|
||||
b.WriteString("\n **Cannot be undone automatically.**\n")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
})
|
||||
page("configuration.md", "Configuration reference", func(b *strings.Builder) {
|
||||
for _, f := range st.Files {
|
||||
fmt.Fprintf(b, "## `%s`\n\n```yaml\n%s```\n\n", f.Path, f.Content)
|
||||
keys := make([]string, 0, len(f.Origins))
|
||||
for k := range f.Origins {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
b.WriteString("| Setting | Comes from | Uses answers |\n|---|---|---|\n")
|
||||
for _, k := range keys {
|
||||
o := f.Origins[k]
|
||||
fmt.Fprintf(b, "| `%s` | %s | %s |\n", k, o.Source, strings.Join(o.Params, ", "))
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
for _, p := range selected {
|
||||
if cp := e.Cat.Packages[p.ID]; cp != nil {
|
||||
for _, m := range cp.Spec.Modules {
|
||||
if ms := findModule(p, m.ID); ms != nil && ms.Enabled && m.Manual != "" {
|
||||
fmt.Fprintf(b, "- Full option list of %s: %s\n", firstNonEmpty(m.Program, m.ID), link("yetano:manual/"+m.Manual+"/configuration"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
page("security.md", "Security", func(b *strings.Builder) {
|
||||
b.WriteString("Secrets are never written into these files: secret answers are\nreferences (`secret://…` resolved by yaseva, `env:`, `file:`).\n\n")
|
||||
for _, c := range st.Checks {
|
||||
if c.Status == CheckNotApplicable {
|
||||
continue
|
||||
}
|
||||
if c.Kind == "tls" || c.Kind == "dns" || strings.Contains(c.ID, "tls") || strings.Contains(c.ID, "relay") {
|
||||
fmt.Fprintf(b, "- **%s** (%s): %s", c.Title, c.Severity, c.Hint)
|
||||
if c.Run != "" {
|
||||
fmt.Fprintf(b, " Check: `%s`", c.Run)
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
}
|
||||
for _, r := range s.Spec.References.Manuals {
|
||||
if strings.Contains(r, "dkim") || strings.Contains(r, "tls") || strings.Contains(r, "security") {
|
||||
b.WriteString("\n")
|
||||
excerpt(b, r)
|
||||
}
|
||||
}
|
||||
})
|
||||
page("operations.md", "Operations and maintenance", func(b *strings.Builder) {
|
||||
for _, op := range s.Spec.Operations {
|
||||
fmt.Fprintf(b, "- %s\n", op)
|
||||
}
|
||||
b.WriteString("\n## Health checks\n\n")
|
||||
for _, p := range selected {
|
||||
if cp := e.Cat.Packages[p.ID]; cp != nil {
|
||||
for _, m := range cp.Spec.Modules {
|
||||
if ms := findModule(p, m.ID); ms != nil && ms.Enabled {
|
||||
for _, d := range m.Doctor {
|
||||
fmt.Fprintf(b, "- `%s`\n", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(st.Related) > 0 {
|
||||
b.WriteString("\n## Related tasks and solutions\n\n")
|
||||
for _, r := range st.Related {
|
||||
kind := "solution"
|
||||
if e.Cat.Tasks[r] != nil {
|
||||
kind = "task"
|
||||
}
|
||||
fmt.Fprintf(b, "- `yet %s show %s`\n", kind, r)
|
||||
}
|
||||
}
|
||||
})
|
||||
if hasCap("backup.") {
|
||||
page("backup-restore.md", "Backup and restore", func(b *strings.Builder) {
|
||||
for _, c := range st.Capabilities {
|
||||
if strings.HasPrefix(c.ID, "backup.") && provided(c.Status) {
|
||||
fmt.Fprintf(b, "- %s: %s\n", c.Title, c.Provider)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
page("troubleshooting.md", "Troubleshooting", func(b *strings.Builder) {
|
||||
b.WriteString("Run the health checks from [operations](operations.md) first: they name\nthe failing area and give a hint.\n\n## Manuals\n\n")
|
||||
refs := append([]string{}, st.References...)
|
||||
for _, r := range refs {
|
||||
if strings.HasPrefix(r, "yetano:manual/") {
|
||||
fmt.Fprintf(b, "- %s\n", link(r))
|
||||
}
|
||||
}
|
||||
})
|
||||
return pages
|
||||
}
|
||||
|
||||
func findModule(p PackageState, id string) *ModuleState {
|
||||
for i := range p.Modules {
|
||||
if p.Modules[i].ID == id {
|
||||
return &p.Modules[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func answerText(q QuestionState) string {
|
||||
if l, ok := q.Value.([]any); ok {
|
||||
var parts []string
|
||||
for _, x := range l {
|
||||
parts = append(parts, optTitle(q, catalog.Scalar(x)))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
return optTitle(q, catalog.Scalar(q.Value))
|
||||
}
|
||||
|
||||
func optTitle(q QuestionState, v string) string {
|
||||
for _, o := range q.Options {
|
||||
if o.ID == v {
|
||||
return o.Title
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Package engine is the Solutions Engine: it evaluates a solution's
|
||||
// questions and rules against a user's answers, resolves packages,
|
||||
// modules, capabilities and providers, generates native configuration
|
||||
// with the origin of every value, and builds the architecture graph,
|
||||
// the plan, the lock file and the handbook.
|
||||
//
|
||||
// The engine is pure: it reads a loaded catalog and values, and returns
|
||||
// values. It never touches the network, never runs a command and writes
|
||||
// files only in Write, into the directory it is given.
|
||||
package engine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// Instance is a user's answers for one solution: a draft wizard session
|
||||
// (kind WizardSession) or a saved solution instance (SolutionInstance).
|
||||
// It never contains plain-text secrets (secret answers are references).
|
||||
type Instance struct {
|
||||
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||
Kind string `yaml:"kind" json:"kind"`
|
||||
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
|
||||
Spec InstanceSpec `yaml:"spec" json:"spec"`
|
||||
}
|
||||
|
||||
// InstanceMeta names an instance.
|
||||
type InstanceMeta struct {
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
Created string `yaml:"created,omitempty" json:"created,omitempty"`
|
||||
Updated string `yaml:"updated,omitempty" json:"updated,omitempty"`
|
||||
Favorite bool `yaml:"favorite,omitempty" json:"favorite,omitempty"`
|
||||
Archived bool `yaml:"archived,omitempty" json:"archived,omitempty"`
|
||||
}
|
||||
|
||||
// InstanceSpec holds the decisions.
|
||||
type InstanceSpec struct {
|
||||
Solution SolutionPin `yaml:"solution" json:"solution"`
|
||||
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
|
||||
Preset string `yaml:"preset,omitempty" json:"preset,omitempty"`
|
||||
Locale string `yaml:"locale,omitempty" json:"locale,omitempty"`
|
||||
Platform string `yaml:"platform,omitempty" json:"platform,omitempty"`
|
||||
Target string `yaml:"target,omitempty" json:"target,omitempty"`
|
||||
Parameters map[string]any `yaml:"parameters" json:"parameters"`
|
||||
Overrides []Override `yaml:"overrides,omitempty" json:"overrides,omitempty"`
|
||||
// Cursor is the question a wizard session was at (sessions only).
|
||||
Cursor string `yaml:"cursor,omitempty" json:"cursor,omitempty"`
|
||||
}
|
||||
|
||||
// SolutionPin names the solution and the version the answers were made for.
|
||||
type SolutionPin struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||
}
|
||||
|
||||
// Override sets one value in a generated file directly (layer 6 of
|
||||
// ARCHITECTURE.md): path is dot-separated map keys.
|
||||
type Override struct {
|
||||
File string `yaml:"file" json:"file"`
|
||||
Path string `yaml:"path" json:"path"`
|
||||
Value any `yaml:"value" json:"value"`
|
||||
}
|
||||
|
||||
// Preset is a reusable set of answers (PRE-01). Instance-specific and
|
||||
// secret questions are never taken from a preset.
|
||||
type Preset struct {
|
||||
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||
Kind string `yaml:"kind" json:"kind"`
|
||||
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
|
||||
Spec PresetSpec `yaml:"spec" json:"spec"`
|
||||
}
|
||||
|
||||
// PresetSpec holds a preset's answers.
|
||||
type PresetSpec struct {
|
||||
Solution string `yaml:"solution,omitempty" json:"solution,omitempty"`
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
|
||||
Parameters map[string]any `yaml:"parameters" json:"parameters"`
|
||||
}
|
||||
|
||||
// NewInstance starts a session for a solution.
|
||||
func NewInstance(name string, s *catalog.Solution, mode catalog.Level) *Instance {
|
||||
if mode == "" {
|
||||
mode = catalog.LevelQuick
|
||||
}
|
||||
return &Instance{
|
||||
APIVersion: catalog.APIVersion, Kind: catalog.KindSession,
|
||||
Metadata: InstanceMeta{Name: name},
|
||||
Spec: InstanceSpec{
|
||||
Solution: SolutionPin{ID: s.Meta.ID, Version: s.Meta.Version},
|
||||
Mode: mode,
|
||||
Parameters: map[string]any{},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// MaxInstanceSize bounds instance and preset files.
|
||||
const MaxInstanceSize = 1 << 20
|
||||
|
||||
// ReadInstance decodes an instance or session (strict).
|
||||
func ReadInstance(r io.Reader) (*Instance, error) {
|
||||
var in Instance
|
||||
if err := strict(r, &in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if in.APIVersion != catalog.APIVersion {
|
||||
return nil, fmt.Errorf("apiVersion %q, want %q", in.APIVersion, catalog.APIVersion)
|
||||
}
|
||||
if in.Kind != catalog.KindInstance && in.Kind != catalog.KindSession {
|
||||
return nil, fmt.Errorf("kind %q, want %s or %s", in.Kind, catalog.KindInstance, catalog.KindSession)
|
||||
}
|
||||
if in.Spec.Parameters == nil {
|
||||
in.Spec.Parameters = map[string]any{}
|
||||
}
|
||||
return &in, nil
|
||||
}
|
||||
|
||||
// ReadPreset decodes a preset (strict).
|
||||
func ReadPreset(r io.Reader) (*Preset, error) {
|
||||
var p Preset
|
||||
if err := strict(r, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.APIVersion != catalog.APIVersion || p.Kind != catalog.KindPreset {
|
||||
return nil, fmt.Errorf("not a %s %s", catalog.APIVersion, catalog.KindPreset)
|
||||
}
|
||||
if p.Spec.Parameters == nil {
|
||||
p.Spec.Parameters = map[string]any{}
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func strict(r io.Reader, v any) error {
|
||||
b, err := io.ReadAll(io.LimitReader(r, MaxInstanceSize+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(b) > MaxInstanceSize {
|
||||
return fmt.Errorf("larger than %d bytes", MaxInstanceSize)
|
||||
}
|
||||
d := yaml.NewDecoder(bytes.NewReader(b))
|
||||
d.KnownFields(true)
|
||||
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Marshal renders any of the user files as YAML with sorted parameters.
|
||||
func Marshal(v any) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
enc := yaml.NewEncoder(&buf)
|
||||
enc.SetIndent(2)
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enc.Close()
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// PresetFrom derives a preset from an instance: all answers except
|
||||
// instance-specific and secret ones (PRE-02, PRE-04).
|
||||
func PresetFrom(name string, in *Instance, s *catalog.Solution) *Preset {
|
||||
p := &Preset{
|
||||
APIVersion: catalog.APIVersion, Kind: catalog.KindPreset,
|
||||
Metadata: InstanceMeta{Name: name},
|
||||
Spec: PresetSpec{Solution: s.Meta.ID, Version: s.Meta.Version, Mode: in.Spec.Mode, Parameters: map[string]any{}},
|
||||
}
|
||||
keys := make([]string, 0, len(in.Spec.Parameters))
|
||||
for k := range in.Spec.Parameters {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
q, _ := s.Question(k)
|
||||
if q == nil || q.InstanceSpecific || q.Type == "secret" {
|
||||
continue
|
||||
}
|
||||
p.Spec.Parameters[k] = in.Spec.Parameters[k]
|
||||
}
|
||||
return p
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// Lock pins what a generation was made from (LOCK-01). It has no
|
||||
// timestamps, so the same inputs give the same file.
|
||||
type Lock struct {
|
||||
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||
Kind string `yaml:"kind" json:"kind"`
|
||||
Spec LockSpec `yaml:"spec" json:"spec"`
|
||||
}
|
||||
|
||||
// LockSpec is the content of a lock.
|
||||
type LockSpec struct {
|
||||
Generator string `yaml:"generator" json:"generator"`
|
||||
Catalog Pinned `yaml:"catalog" json:"catalog"`
|
||||
Solution Pinned `yaml:"solution" json:"solution"`
|
||||
Profiles []Pinned `yaml:"profiles,omitempty" json:"profiles,omitempty"`
|
||||
Packages []Pinned `yaml:"packages,omitempty" json:"packages,omitempty"`
|
||||
Capability string `yaml:"capabilities" json:"capabilities"` // hash of the capability files
|
||||
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||
Answers string `yaml:"answers" json:"answers"`
|
||||
Files []FileHash `yaml:"files" json:"files"`
|
||||
}
|
||||
|
||||
// Pinned is an entity with version and content hash.
|
||||
type Pinned struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||
Hash string `yaml:"sha256" json:"sha256"`
|
||||
}
|
||||
|
||||
// FileHash is a generated file and its hash.
|
||||
type FileHash = catalog.FileHash
|
||||
|
||||
// OutFile is one file of a generated solution directory.
|
||||
type OutFile struct {
|
||||
Path string `json:"path"`
|
||||
Kind string `json:"kind"` // instance | lock | config | architecture | handbook | plan | readme
|
||||
Content []byte `json:"-"`
|
||||
}
|
||||
|
||||
// Output is everything Generate produces.
|
||||
type Output struct {
|
||||
Files []OutFile `json:"files"`
|
||||
Lock *Lock `json:"lock"`
|
||||
}
|
||||
|
||||
// ManualReader gives the handbook existing manual text (implemented by
|
||||
// package knowledge). It may be nil: the handbook then links instead.
|
||||
type ManualReader interface {
|
||||
// Excerpt returns the title and Markdown of a manual reference
|
||||
// (yetano:manual/...#section), shortened to at most maxLines lines.
|
||||
Excerpt(ref string, maxLines int) (title, markdown string, ok bool)
|
||||
// Link returns a human link for a reference (web URL or CLI command).
|
||||
Link(ref string) string
|
||||
}
|
||||
|
||||
// Generate renders all output files of a complete state. It refuses an
|
||||
// incomplete state unless allowIncomplete is set.
|
||||
func (e *Engine) Generate(st *State, in *Instance, mr ManualReader, allowIncomplete bool) (*Output, error) {
|
||||
if !st.Complete && !allowIncomplete {
|
||||
return nil, fmt.Errorf("%w: %s", ErrIncomplete, incompleteText(st))
|
||||
}
|
||||
s := e.Cat.Lookup(st.Solution.ID)
|
||||
out := &Output{}
|
||||
addf := func(path, kind string, b []byte) {
|
||||
out.Files = append(out.Files, OutFile{Path: path, Kind: kind, Content: b})
|
||||
}
|
||||
inst := *in
|
||||
inst.Kind = catalog.KindInstance
|
||||
inst.Spec.Solution.Version = s.Meta.Version
|
||||
inst.Spec.Cursor = ""
|
||||
b, err := Marshal(&inst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addf("solution.yaml", "instance", b)
|
||||
for _, f := range st.Files {
|
||||
addf(f.Path, "config", []byte(f.Content))
|
||||
}
|
||||
gj, _ := json.MarshalIndent(st.Graph, "", " ")
|
||||
addf("architecture/graph.json", "architecture", append(gj, '\n'))
|
||||
addf("architecture/graph.txt", "architecture", []byte(GraphText(st.Graph)))
|
||||
pb, err := Marshal(PlanOf(st))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addf("deployment-plan.yaml", "plan", pb)
|
||||
for _, h := range e.Handbook(st, mr) {
|
||||
addf(h.Path, "handbook", h.Content)
|
||||
}
|
||||
addf("README.md", "readme", []byte(readme(st)))
|
||||
sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].Path < out.Files[j].Path })
|
||||
for _, f := range out.Files {
|
||||
if !catalog.SafeRelPath(f.Path) {
|
||||
return nil, fmt.Errorf("refusing unsafe output path %q", f.Path)
|
||||
}
|
||||
}
|
||||
out.Lock = e.lock(st, s, in, out.Files)
|
||||
lb, err := Marshal(out.Lock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.Files = append(out.Files, OutFile{Path: "solution.lock.yaml", Kind: "lock", Content: lb})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ErrIncomplete: required answers are missing or errors remain.
|
||||
var ErrIncomplete = errors.New("the solution is not complete")
|
||||
|
||||
func incompleteText(st *State) string {
|
||||
var parts []string
|
||||
if len(st.Progress.Missing) > 0 {
|
||||
parts = append(parts, "missing: "+strings.Join(st.Progress.Missing, ", "))
|
||||
}
|
||||
for _, m := range st.Messages {
|
||||
if m.Severity == "error" {
|
||||
parts = append(parts, m.Text)
|
||||
}
|
||||
}
|
||||
for _, q := range st.Questions {
|
||||
for _, e := range q.Errors {
|
||||
parts = append(parts, q.ID+": "+e)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
func hashBytes(b []byte) string {
|
||||
h := sha256.Sum256(b)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func (e *Engine) lock(st *State, s *catalog.Solution, in *Instance, files []OutFile) *Lock {
|
||||
c := e.Cat
|
||||
l := &Lock{APIVersion: catalog.APIVersion, Kind: "SolutionLock"}
|
||||
l.Spec.Generator = GeneratorVersion
|
||||
l.Spec.Catalog = Pinned{ID: c.Meta.ID, Version: c.Meta.Version, Hash: c.Hash()}
|
||||
l.Spec.Solution = Pinned{ID: s.Meta.ID, Version: s.Meta.Version, Hash: s.Hash}
|
||||
for _, p := range st.Packages {
|
||||
if !p.Selected {
|
||||
continue
|
||||
}
|
||||
if cp := c.Packages[p.ID]; cp != nil {
|
||||
l.Spec.Packages = append(l.Spec.Packages, Pinned{ID: p.ID, Hash: cp.Hash})
|
||||
}
|
||||
if p.Profile != "" {
|
||||
chain, _ := c.ProfileChain(p.ID, p.Profile)
|
||||
for _, pr := range chain {
|
||||
l.Spec.Profiles = append(l.Spec.Profiles, Pinned{ID: pr.Key(), Hash: pr.Hash})
|
||||
}
|
||||
}
|
||||
}
|
||||
var capFiles, bpFiles []string
|
||||
for _, f := range c.Files {
|
||||
if strings.HasPrefix(f.Path, "bigpicture:") {
|
||||
bpFiles = append(bpFiles, f.Path+" "+f.Hash)
|
||||
} else if strings.HasPrefix(f.Path, "capabilities") {
|
||||
capFiles = append(capFiles, f.Path+" "+f.Hash)
|
||||
}
|
||||
}
|
||||
l.Spec.Capability = hashBytes([]byte(strings.Join(capFiles, "\n")))
|
||||
if len(bpFiles) > 0 {
|
||||
l.Spec.BigPicture = hashBytes([]byte(strings.Join(bpFiles, "\n")))
|
||||
}
|
||||
ab, _ := json.Marshal(in.Spec.Parameters) // map keys are sorted by encoding/json
|
||||
ob, _ := json.Marshal(in.Spec.Overrides)
|
||||
l.Spec.Answers = hashBytes(append(append(ab, '\n'), ob...))
|
||||
for _, f := range files {
|
||||
l.Spec.Files = append(l.Spec.Files, FileHash{Path: f.Path, Hash: hashBytes(f.Content)})
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// LockDrift lists what changed meaning between a previous lock and now
|
||||
// (LOCK-02/03): a changed solution, profile or package definition.
|
||||
func LockDrift(prev, cur *Lock) []string {
|
||||
var out []string
|
||||
if prev.Spec.Solution.Hash != cur.Spec.Solution.Hash {
|
||||
out = append(out, fmt.Sprintf("solution %s changed (%s -> %s)", cur.Spec.Solution.ID, prev.Spec.Solution.Version, cur.Spec.Solution.Version))
|
||||
}
|
||||
cmp := func(kind string, a, b []Pinned) {
|
||||
m := map[string]string{}
|
||||
for _, p := range a {
|
||||
m[p.ID] = p.Hash
|
||||
}
|
||||
for _, p := range b {
|
||||
if h, ok := m[p.ID]; !ok {
|
||||
out = append(out, fmt.Sprintf("%s %s is new", kind, p.ID))
|
||||
} else if h != p.Hash {
|
||||
out = append(out, fmt.Sprintf("%s %s changed", kind, p.ID))
|
||||
}
|
||||
delete(m, p.ID)
|
||||
}
|
||||
for id := range m {
|
||||
out = append(out, fmt.Sprintf("%s %s is no longer used", kind, id))
|
||||
}
|
||||
}
|
||||
cmp("profile", prev.Spec.Profiles, cur.Spec.Profiles)
|
||||
cmp("package", prev.Spec.Packages, cur.Spec.Packages)
|
||||
if prev.Spec.Capability != cur.Spec.Capability {
|
||||
out = append(out, "the capability catalog changed")
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// ReadLock reads dir/solution.lock.yaml; a missing file is (nil, nil).
|
||||
func ReadLock(dir string) (*Lock, error) {
|
||||
f, err := os.Open(filepath.Join(dir, "solution.lock.yaml"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
var l Lock
|
||||
if err := strict(f, &l); err != nil {
|
||||
return nil, fmt.Errorf("solution.lock.yaml: %w", err)
|
||||
}
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
// ErrModified: a file in the output directory was changed by hand.
|
||||
var ErrModified = errors.New("output directory has changes that would be overwritten")
|
||||
|
||||
// Write writes out into dir (CONF-05, CONF-06). Without force it refuses
|
||||
// to overwrite a file that differs from what the previous lock recorded
|
||||
// (a hand edit) or a file the previous generation did not write. Files of
|
||||
// the previous generation that are no longer produced are removed only
|
||||
// when they are unchanged.
|
||||
func Write(dir string, out *Output, force bool) error {
|
||||
prev, err := ReadLock(dir)
|
||||
if err != nil && !force {
|
||||
return err
|
||||
}
|
||||
known := map[string]string{}
|
||||
if prev != nil {
|
||||
for _, f := range prev.Spec.Files {
|
||||
known[f.Path] = f.Hash
|
||||
}
|
||||
known["solution.lock.yaml"] = "*"
|
||||
}
|
||||
var conflicts []string
|
||||
for _, f := range out.Files {
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
cur, err := os.ReadFile(p)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, isKnown := known[f.Path]
|
||||
switch {
|
||||
case h == "*":
|
||||
case !isKnown && hashBytes(cur) != hashBytes(f.Content):
|
||||
conflicts = append(conflicts, f.Path+" (not written by the guide)")
|
||||
case isKnown && hashBytes(cur) != h:
|
||||
conflicts = append(conflicts, f.Path+" (changed by hand)")
|
||||
}
|
||||
}
|
||||
if len(conflicts) > 0 && !force {
|
||||
return fmt.Errorf("%w: %s; use --force to overwrite", ErrModified, strings.Join(conflicts, ", "))
|
||||
}
|
||||
for _, f := range out.Files {
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, f.Content, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// stale files of the previous generation
|
||||
now := map[string]bool{}
|
||||
for _, f := range out.Files {
|
||||
now[f.Path] = true
|
||||
}
|
||||
if prev != nil {
|
||||
for _, f := range prev.Spec.Files {
|
||||
if now[f.Path] || !catalog.SafeRelPath(f.Path) {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
if cur, err := os.ReadFile(p); err == nil && hashBytes(cur) == f.Hash {
|
||||
os.Remove(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Plan is the deployment plan: what an operator (or a later apply) does,
|
||||
// in order. It is never executed by the engine (LIFE-01).
|
||||
type Plan struct {
|
||||
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||
Kind string `yaml:"kind" json:"kind"`
|
||||
Spec PlanSpec `yaml:"spec" json:"spec"`
|
||||
}
|
||||
|
||||
// PlanSpec lists files, steps and checks.
|
||||
type PlanSpec struct {
|
||||
Solution string `yaml:"solution" json:"solution"`
|
||||
Instance string `yaml:"instance" json:"instance"`
|
||||
Target string `yaml:"target" json:"target"`
|
||||
Apply string `yaml:"apply" json:"apply"`
|
||||
Packages []string `yaml:"packages" json:"packages"`
|
||||
Files []string `yaml:"files" json:"files"`
|
||||
Steps []PlannedStep `yaml:"steps" json:"steps"`
|
||||
Checks []PlanCheck `yaml:"checks" json:"checks"`
|
||||
}
|
||||
|
||||
// PlanCheck is a check to run after applying.
|
||||
type PlanCheck struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Run string `yaml:"run,omitempty" json:"run,omitempty"`
|
||||
}
|
||||
|
||||
// PlanOf builds the plan of a state.
|
||||
func PlanOf(st *State) *Plan {
|
||||
p := &Plan{APIVersion: catalog.APIVersion, Kind: "DeploymentPlan"}
|
||||
p.Spec.Solution = st.Solution.ID + " " + st.Solution.Version
|
||||
p.Spec.Instance = st.Instance
|
||||
p.Spec.Target = firstNonEmpty(st.Platform, "local")
|
||||
p.Spec.Apply = "manual: the guide does not apply plans yet; run the steps yourself (LIFE-01)"
|
||||
for _, pk := range st.Packages {
|
||||
if pk.Selected {
|
||||
p.Spec.Packages = append(p.Spec.Packages, pk.ID)
|
||||
}
|
||||
}
|
||||
for _, f := range st.Files {
|
||||
p.Spec.Files = append(p.Spec.Files, f.Path)
|
||||
}
|
||||
p.Spec.Steps = st.Steps
|
||||
if p.Spec.Steps == nil {
|
||||
p.Spec.Steps = []PlannedStep{}
|
||||
}
|
||||
for _, c := range st.Checks {
|
||||
if c.Status != CheckNotApplicable {
|
||||
p.Spec.Checks = append(p.Spec.Checks, PlanCheck{ID: c.ID, Title: c.Title, Run: c.Run})
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func readme(st *State) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "# %s\n\n", firstNonEmpty(st.Instance, st.Solution.Title))
|
||||
fmt.Fprintf(&b, "Solution: %s (`%s` %s), generated by the Yetano Solutions Guide.\n\n", st.Solution.Title, st.Solution.ID, st.Solution.Version)
|
||||
b.WriteString("| Path | Content |\n|---|---|\n")
|
||||
b.WriteString("| `solution.yaml` | your answers (SolutionInstance); regenerate with `yet solution generate --file solution.yaml --output .` |\n")
|
||||
b.WriteString("| `solution.lock.yaml` | what this was generated from (catalog, profiles, file hashes) |\n")
|
||||
b.WriteString("| `config/` | native configuration files, one directory per package |\n")
|
||||
b.WriteString("| `deployment-plan.yaml` | the steps to install, configure and check it (not executed by the guide) |\n")
|
||||
b.WriteString("| `architecture/` | the resolved architecture (`graph.json`, `graph.txt`) |\n")
|
||||
b.WriteString("| `handbook/` | your handbook: start with `handbook/index.md` |\n\n")
|
||||
b.WriteString("Nothing here has been installed or changed on any system.\n")
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// phases in plan order.
|
||||
var phaseOrder = map[string]int{"install": 0, "configure": 1, "data": 2, "dns": 3, "start": 4, "verify": 5}
|
||||
|
||||
func (ev *evaluation) steps() {
|
||||
vars := ev.vars()
|
||||
for _, s := range ev.s.Spec.Steps {
|
||||
if len(s.When) > 0 && !s.When.Holds(ev.env) {
|
||||
continue
|
||||
}
|
||||
if s.Package != "" && !ev.pkgSelected(s.Package) {
|
||||
continue
|
||||
}
|
||||
if s.Package != "" && s.Module != "" && s.ForEach != "$modules" && !ev.moduleEnabled(s.Package, s.Module) {
|
||||
continue
|
||||
}
|
||||
items := []any{nil}
|
||||
switch {
|
||||
case s.ForEach == "$modules":
|
||||
// every enabled module of the step's package that is a program
|
||||
items = nil
|
||||
if cp := ev.e.Cat.Packages[s.Package]; cp != nil {
|
||||
for _, m := range cp.Spec.Modules {
|
||||
if m.Program != "" && ev.moduleEnabled(s.Package, m.ID) && (s.Module == "" || m.Kind == s.Module) {
|
||||
items = append(items, m.Program)
|
||||
}
|
||||
}
|
||||
}
|
||||
case s.ForEach != "":
|
||||
items = listOf(ev.answers[s.ForEach])
|
||||
}
|
||||
for i, it := range items {
|
||||
v := vars
|
||||
if s.ForEach != "" {
|
||||
v = map[string]any{}
|
||||
for k, x := range vars {
|
||||
v[k] = x
|
||||
}
|
||||
v["item"] = it
|
||||
}
|
||||
run, err := expand(s.Run, v)
|
||||
if err != nil {
|
||||
ev.msg("error", "step", fmt.Sprintf("step %s: %v", s.ID, err), "step:"+s.ID)
|
||||
continue
|
||||
}
|
||||
title, _ := expand(s.Title, v)
|
||||
note, _ := expand(s.Note, v)
|
||||
id := s.ID
|
||||
if s.ForEach != "" {
|
||||
id = fmt.Sprintf("%s-%d", s.ID, i+1)
|
||||
}
|
||||
phase := s.Phase
|
||||
if phase == "" {
|
||||
phase = "configure"
|
||||
}
|
||||
ev.st.Steps = append(ev.st.Steps, PlannedStep{
|
||||
ID: id, Title: title, Phase: phase, Package: s.Package, Module: s.Module,
|
||||
Run: run, Note: note, Mutating: s.Mutating, Reversible: s.Reversible, References: s.References,
|
||||
})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(ev.st.Steps, func(i, j int) bool {
|
||||
return phaseOrder[ev.st.Steps[i].Phase] < phaseOrder[ev.st.Steps[j].Phase]
|
||||
})
|
||||
}
|
||||
|
||||
// expand fills placeholders into a text (steps, notes). Values are
|
||||
// inserted as text; steps are shown to the operator, never run.
|
||||
func expand(s string, vars map[string]any) (string, error) {
|
||||
if !strings.Contains(s, "${") {
|
||||
return s, nil
|
||||
}
|
||||
var firstErr error
|
||||
used := map[string]bool{}
|
||||
out := placeholderRE.ReplaceAllStringFunc(s, func(m string) string {
|
||||
if m == "$${" {
|
||||
return "${"
|
||||
}
|
||||
if strings.HasPrefix(m, "${item") {
|
||||
if it, ok := vars["item"]; ok {
|
||||
return catalog.Scalar(it)
|
||||
}
|
||||
}
|
||||
v, err := lookup(m, vars, used)
|
||||
if err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
return shellWord(text(v))
|
||||
})
|
||||
return out, firstErr
|
||||
}
|
||||
|
||||
// shellWord quotes a value for display in a command line if needed.
|
||||
func shellWord(s string) string {
|
||||
if s == "" {
|
||||
return "''"
|
||||
}
|
||||
for _, r := range s {
|
||||
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("@%+=:,./_-", r)) {
|
||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (ev *evaluation) checks() {
|
||||
vars := ev.vars()
|
||||
for _, c := range ev.s.Spec.Requirements {
|
||||
r := CheckResult{ID: c.ID, Title: c.Title, Kind: c.Kind, Severity: firstNonEmpty(c.Severity, "error"),
|
||||
Local: c.Local, Hint: c.Hint, References: c.References, Params: map[string]string{}}
|
||||
if len(c.When) > 0 && !c.When.Holds(ev.env) {
|
||||
r.Status = CheckNotApplicable
|
||||
ev.st.Checks = append(ev.st.Checks, r)
|
||||
continue
|
||||
}
|
||||
for k, v := range c.Params {
|
||||
x, err := expand(v, vars)
|
||||
if err != nil {
|
||||
x = v
|
||||
}
|
||||
r.Params[k] = strings.Trim(x, "'")
|
||||
}
|
||||
r.Run, _ = expand(c.Run, vars)
|
||||
// The engine itself never inspects a system: every check starts
|
||||
// as NOT_CHECKED; a doctor runner fills in results (DR-03).
|
||||
r.Status = CheckNotChecked
|
||||
ev.st.Checks = append(ev.st.Checks, r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// SEC-02: the catalog, the engine and the knowledge index never run a
|
||||
// program or open a network connection; the CLI may (doctor checks).
|
||||
// core/secretref links os/exec for resolving secret:// through yaseva;
|
||||
// the engine only uses its Validate, so os/exec is checked on the
|
||||
// packages' own imports, network packages on all dependencies.
|
||||
func TestNoExecOrNetwork(t *testing.T) {
|
||||
for _, pkg := range []string{"../catalog", "../engine", "../knowledge", "../ref"} {
|
||||
own, err := exec.Command("go", "list", "-f", "{{join .Imports \" \"}}", pkg).Output()
|
||||
if err != nil {
|
||||
t.Skip("go list not available")
|
||||
}
|
||||
for _, dep := range strings.Fields(string(own)) {
|
||||
if dep == "os/exec" || dep == "syscall" || dep == "plugin" || dep == "unsafe" {
|
||||
t.Errorf("%s imports %s", pkg, dep)
|
||||
}
|
||||
}
|
||||
all, _ := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", pkg).Output()
|
||||
for _, dep := range strings.Fields(string(all)) {
|
||||
switch dep {
|
||||
case "net/http", "net/rpc", "net/smtp", "crypto/tls":
|
||||
t.Errorf("%s depends on %s", pkg, dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package engine
|
||||
|
||||
import "yetano.dev/yetano/core/solutions/catalog"
|
||||
|
||||
// State is the complete result of evaluating an instance: everything a
|
||||
// client shows. Clients never compute visibility, options or resolution
|
||||
// themselves (API-02); they render a State.
|
||||
type State struct {
|
||||
Solution SolutionInfo `json:"solution"`
|
||||
Instance string `json:"instance"`
|
||||
Mode catalog.Level `json:"mode"`
|
||||
Locale string `json:"locale"`
|
||||
Platform string `json:"platform,omitempty"`
|
||||
Questions []QuestionState `json:"questions"`
|
||||
Next string `json:"next,omitempty"`
|
||||
Progress Progress `json:"progress"`
|
||||
Complete bool `json:"complete"`
|
||||
Answers map[string]Answer `json:"answers"`
|
||||
Stale []StaleAnswer `json:"stale,omitempty"`
|
||||
Packages []PackageState `json:"packages"`
|
||||
Capabilities []CapState `json:"capabilities"`
|
||||
Rules []AppliedRule `json:"rules"`
|
||||
Messages []Message `json:"messages"`
|
||||
Recommended []Recommendation `json:"recommendations,omitempty"`
|
||||
Files []FilePreview `json:"files"`
|
||||
Steps []PlannedStep `json:"steps"`
|
||||
Checks []CheckResult `json:"checks"`
|
||||
Graph Graph `json:"graph"`
|
||||
References []string `json:"references"`
|
||||
Related []string `json:"related,omitempty"`
|
||||
}
|
||||
|
||||
// SolutionInfo identifies the evaluated solution or task.
|
||||
type SolutionInfo struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
TaskKind string `json:"taskKind,omitempty"`
|
||||
Version string `json:"version"`
|
||||
Title string `json:"title"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Status catalog.Support `json:"status"`
|
||||
Category string `json:"category,omitempty"`
|
||||
BigPicture string `json:"bigpicture,omitempty"`
|
||||
}
|
||||
|
||||
// QuestionState is one question as the client shows it.
|
||||
type QuestionState struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Item string `json:"item,omitempty"`
|
||||
Group string `json:"group,omitempty"`
|
||||
Level catalog.Level `json:"level"`
|
||||
Title string `json:"title"`
|
||||
Help string `json:"help,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Decide string `json:"decide,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Examples []string `json:"examples,omitempty"`
|
||||
Visible bool `json:"visible"`
|
||||
Asked bool `json:"asked"` // shown in the current mode
|
||||
Required bool `json:"required"`
|
||||
InstanceSpecific bool `json:"instanceSpecific,omitempty"`
|
||||
Value any `json:"value,omitempty"`
|
||||
Origin string `json:"origin,omitempty"` // default | preset | instance | ""
|
||||
Default any `json:"default,omitempty"`
|
||||
Recommended any `json:"recommended,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Options []OptionState `json:"options,omitempty"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
Warnings []Message `json:"warnings,omitempty"`
|
||||
References []string `json:"references,omitempty"`
|
||||
}
|
||||
|
||||
// OptionState is one option with whether and why it can be chosen.
|
||||
type OptionState struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Recommended bool `json:"recommended,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Support catalog.Support `json:"support"`
|
||||
SupportNote string `json:"supportNote,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Disabled string `json:"disabledReason,omitempty"`
|
||||
Selected bool `json:"selected"`
|
||||
Adds []string `json:"adds,omitempty"` // packages/capabilities it brings in
|
||||
References []string `json:"references,omitempty"`
|
||||
}
|
||||
|
||||
// Progress counts asked questions.
|
||||
type Progress struct {
|
||||
Asked int `json:"asked"`
|
||||
Answered int `json:"answered"`
|
||||
Missing []string `json:"missing,omitempty"`
|
||||
Step int `json:"step"` // 1-based index of Next among asked questions
|
||||
}
|
||||
|
||||
// Answer is an effective answer and where it came from.
|
||||
type Answer struct {
|
||||
Value any `json:"value"`
|
||||
Origin string `json:"origin"`
|
||||
}
|
||||
|
||||
// StaleAnswer is an explicit answer that no longer counts (RULE-06).
|
||||
type StaleAnswer struct {
|
||||
Question string `json:"question"`
|
||||
Value any `json:"value"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// Status values of packages, modules and capabilities in a state and a graph (BP-04).
|
||||
const (
|
||||
StRequired = "required"
|
||||
StSelected = "selected"
|
||||
StRecommended = "recommended"
|
||||
StOptional = "optional"
|
||||
StExternal = "external"
|
||||
StAlternative = "alternative"
|
||||
StDisabled = "disabled"
|
||||
StUnsupported = "unsupported"
|
||||
StMissing = "missing"
|
||||
StConflicting = "conflicting"
|
||||
StExcluded = "excluded"
|
||||
)
|
||||
|
||||
// PackageState is a package in the resolved solution.
|
||||
type PackageState struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Profile string `json:"profile,omitempty"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Modules []ModuleState `json:"modules,omitempty"`
|
||||
Selected bool `json:"selected"`
|
||||
}
|
||||
|
||||
// ModuleState is a module of a selected package.
|
||||
type ModuleState struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Program string `json:"program,omitempty"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Support catalog.Support `json:"support,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// CapState is a capability in the resolved solution.
|
||||
type CapState struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Provider string `json:"provider,omitempty"` // pkg/module or external:<id>
|
||||
Alternatives []string `json:"alternatives,omitempty"`
|
||||
Reasons []string `json:"reasons"`
|
||||
}
|
||||
|
||||
// AppliedRule records a rule (or an option's effects) that fired.
|
||||
type AppliedRule struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"` // rule | option | package | capability
|
||||
Effect string `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// Message is a warning, error or note.
|
||||
type Message struct {
|
||||
Severity string `json:"severity"` // info | warning | error
|
||||
Code string `json:"code"`
|
||||
Text string `json:"text"`
|
||||
Source string `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
// Recommendation suggests an extension.
|
||||
type Recommendation struct {
|
||||
Package string `json:"package,omitempty"`
|
||||
Capability string `json:"capability,omitempty"`
|
||||
Reason string `json:"reason"`
|
||||
Source string `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
// FilePreview is one generated file.
|
||||
type FilePreview struct {
|
||||
Path string `json:"path"`
|
||||
Package string `json:"package"`
|
||||
Content string `json:"content"`
|
||||
Origins map[string]Origin `json:"origins"`
|
||||
}
|
||||
|
||||
// Origin says where a configuration value came from (PROF-05).
|
||||
type Origin struct {
|
||||
Layer string `json:"layer"` // profile | solution | override
|
||||
Source string `json:"source"` // profile:yamase/mailbox, solution:mail-server#tls, override
|
||||
Params []string `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
// PlannedStep is a setup step (never executed by the engine).
|
||||
type PlannedStep struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Phase string `json:"phase"`
|
||||
Package string `json:"package,omitempty"`
|
||||
Module string `json:"module,omitempty"`
|
||||
Run string `json:"run,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Mutating bool `json:"mutating"`
|
||||
Reversible *bool `json:"reversible,omitempty"`
|
||||
References []string `json:"references,omitempty"`
|
||||
}
|
||||
|
||||
// Check status values (DR-03).
|
||||
const (
|
||||
CheckPass = "PASS"
|
||||
CheckInfo = "INFO"
|
||||
CheckWarning = "WARNING"
|
||||
CheckError = "ERROR"
|
||||
CheckBlocked = "BLOCKED"
|
||||
CheckNotApplicable = "NOT_APPLICABLE"
|
||||
CheckNotChecked = "NOT_CHECKED"
|
||||
)
|
||||
|
||||
// CheckResult is a requirement/doctor check and its result.
|
||||
type CheckResult struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Kind string `json:"kind"`
|
||||
Severity string `json:"severity"`
|
||||
Local bool `json:"local"`
|
||||
Params map[string]string `json:"params,omitempty"`
|
||||
Run string `json:"run,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Note string `json:"note,omitempty"`
|
||||
References []string `json:"references,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
interfaces: []
|
||||
connections:
|
||||
- {id: connection.app-idp, from: product.app, to: product.idp, type: authenticatesVia, label: signs in through, scope: general, review: confirmed}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
title: Test Big Picture
|
||||
content: {topics: topics.yaml, products: products, stories: stories, connections: connections.yaml}
|
||||
@@ -0,0 +1,3 @@
|
||||
id: product.app
|
||||
name: app
|
||||
summary: The test application.
|
||||
@@ -0,0 +1,3 @@
|
||||
id: product.idp
|
||||
name: idp
|
||||
summary: An identity provider.
|
||||
@@ -0,0 +1,5 @@
|
||||
id: story.run-app
|
||||
title: Run the app
|
||||
intent: I want to run the app.
|
||||
outcome: The app runs.
|
||||
primaryTopic: topic.t
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
topics:
|
||||
- {id: topic.t, title: Testing, summary: Test topic}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Catalog
|
||||
metadata: {id: test, version: 1.0.0}
|
||||
spec:
|
||||
bigpicture: ../bp
|
||||
webBase: https://example.test/
|
||||
categories: [{id: t, topic: topic.t}]
|
||||
---
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Capabilities
|
||||
metadata: {id: caps}
|
||||
spec:
|
||||
capabilities:
|
||||
- {id: app.serve, title: Serve the app, requires: [auth.users]}
|
||||
- {id: auth.users, title: Users}
|
||||
- {id: auth.sso, title: Single sign-on}
|
||||
- {id: backup.files, title: Backups, external: [{id: tool, title: Your tool}]}
|
||||
- {id: feature.x, title: Feature X}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Package
|
||||
metadata: {id: app}
|
||||
spec:
|
||||
bigpicture: product.app
|
||||
sources: [test]
|
||||
modules:
|
||||
- {id: server, title: Server, program: app-server, kind: daemon, provides: [app.serve]}
|
||||
- {id: users, title: Local users, kind: library, provides: [auth.users], priority: 10}
|
||||
- {id: extra, title: Extra, program: app-extra, kind: daemon, provides: [feature.x]}
|
||||
- {id: ghost, title: Not built, support: not-implemented, provides: [auth.sso]}
|
||||
---
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Package
|
||||
metadata: {id: idp}
|
||||
spec:
|
||||
bigpicture: product.idp
|
||||
sources: [test]
|
||||
modules:
|
||||
- {id: sso, title: SSO, program: idp, kind: daemon, provides: [auth.sso, auth.users], priority: 1}
|
||||
---
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Package
|
||||
metadata: {id: bak, summary: Backups}
|
||||
spec:
|
||||
sources: [test]
|
||||
modules:
|
||||
- {id: b, title: Backup, program: bak, provides: [backup.files], support: experimental}
|
||||
---
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Profile
|
||||
metadata: {id: base, package: app}
|
||||
spec:
|
||||
modules: {server: enabled, users: enabled, extra: disabled}
|
||||
config:
|
||||
- file: app/app.yaml
|
||||
set: {log: info, listen: ":8080", limits: {max: 10, min: 1}}
|
||||
---
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Profile
|
||||
metadata: {id: big, package: app}
|
||||
spec:
|
||||
extends: base
|
||||
modules: {extra: enabled}
|
||||
config:
|
||||
- file: app/app.yaml
|
||||
set: {limits: {max: 100}}
|
||||
- {file: app/extra.yaml, module: extra, set: {on: true}}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
apiVersion: yetano.dev/v1
|
||||
kind: Solution
|
||||
metadata: {id: app-run, version: 1.0.0, category: t, status: supported}
|
||||
spec:
|
||||
bigpicture: story.run-app
|
||||
capabilities: {required: [app.serve], recommended: [backup.files]}
|
||||
packages:
|
||||
- {id: app, profile: base, role: core, when: {size: small}}
|
||||
- {id: app, profile: big, role: core, when: {size: big}}
|
||||
questions:
|
||||
- id: size
|
||||
type: select
|
||||
title: How big?
|
||||
default: small
|
||||
options:
|
||||
- {id: small, title: Small, recommended: true, reason: fits most}
|
||||
- {id: big, title: Big}
|
||||
- {id: hosts, type: list, item: hostname, title: Host names, required: true, instanceSpecific: true, validation: {minItems: 1}}
|
||||
- id: identity
|
||||
type: select
|
||||
title: Users?
|
||||
level: guided
|
||||
default: local
|
||||
options:
|
||||
- {id: local, title: Local}
|
||||
- {id: central, title: Central IdP, requires: {packages: [idp], capabilities: [auth.sso]}}
|
||||
- {id: ghost, title: Ghost, support: not-implemented, supportNote: not built}
|
||||
- {id: realm, type: string, title: Realm, visibleWhen: {identity: central}, required: true}
|
||||
- {id: token, type: secret, level: advanced, title: Token}
|
||||
- {id: owner, type: email, level: guided, title: Owner, default: "admin@${hosts[0]}"}
|
||||
- id: backup
|
||||
type: select
|
||||
title: Backup
|
||||
level: guided
|
||||
default: none
|
||||
options:
|
||||
- {id: none, title: None}
|
||||
- {id: mine, title: My tool, provides: [backup.files]}
|
||||
- {id: bak, title: bak, requires: {packages: [bak]}}
|
||||
- {id: port, type: port, level: advanced, title: Port, default: 8080}
|
||||
rules:
|
||||
- {id: big-warn, when: {size: big}, message: Big needs more memory., severity: warning}
|
||||
- {id: no-x-small, when: {size: small}, excludes: {capabilities: [feature.x]}}
|
||||
configuration:
|
||||
- id: main
|
||||
file: app/app.yaml
|
||||
set: {hosts: "${hosts}", owner: "${owner}", listen: ":${port}", first: "${hosts[0]}", n: "${hosts.count}"}
|
||||
- {id: sso, file: app/app.yaml, when: {identity: central}, set: {sso: {realm: "${realm}"}}}
|
||||
- {id: tok, file: app/app.yaml, when: {token: {set: true}}, set: {token: "${token}"}}
|
||||
- {id: idp, file: idp/idp.yaml, set: {realm: "${realm}"}, when: {identity: central}}
|
||||
- {id: never, file: bak/bak.yaml, set: {x: 1}}
|
||||
steps:
|
||||
- {id: add, title: "Add ${item}", forEach: hosts, run: "app add ${item}", phase: data, mutating: true}
|
||||
- {id: inst, title: "Install ${item}", package: app, forEach: $modules, run: "yet install ${item}", phase: install}
|
||||
requirements:
|
||||
- {id: port, title: Port free, kind: port, params: {port: "${port}"}, local: true}
|
||||
- {id: bigonly, title: Memory, kind: manual, when: {size: big}}
|
||||
architecture:
|
||||
nodes: [{id: users, type: client, title: "Users of ${hosts[0]}"}]
|
||||
edges: [{from: users, to: "mod:app/server", type: connectsTo}]
|
||||
@@ -0,0 +1,306 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"yetano.dev/yetano/core/secretref"
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
// MaxAnswerLen bounds a single text answer (SEC-03).
|
||||
const MaxAnswerLen = 64 << 10
|
||||
|
||||
var (
|
||||
hostnameRE = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
|
||||
emailRE = regexp.MustCompile(`^[^@\s]+@[^@\s]+$`)
|
||||
dateRE = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
|
||||
)
|
||||
|
||||
// TypeValidator checks and normalizes one scalar answer of a type. New
|
||||
// question types are added with RegisterType (WIZ-04).
|
||||
type TypeValidator func(v any) (any, error)
|
||||
|
||||
var extraTypes = map[string]TypeValidator{}
|
||||
|
||||
// RegisterType adds a question type. It must be called before catalogs
|
||||
// using the type are validated; built-in types cannot be replaced.
|
||||
func RegisterType(name string, fn TypeValidator) error {
|
||||
if catalog.QuestionTypes[name] {
|
||||
return fmt.Errorf("type %q is built in", name)
|
||||
}
|
||||
extraTypes[name] = fn
|
||||
catalog.QuestionTypes[name] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// Normalize converts an answer given as text (CLI --set, interactive
|
||||
// input) or as decoded YAML/JSON into the canonical value for the
|
||||
// question and validates it. It does not check option enablement.
|
||||
func Normalize(q *catalog.Question, v any) (any, error) {
|
||||
switch q.Type {
|
||||
case "multiselect", "list":
|
||||
items := listOf(v)
|
||||
out := make([]any, 0, len(items))
|
||||
seen := map[string]bool{}
|
||||
for _, it := range items {
|
||||
var n any
|
||||
var err error
|
||||
if q.Type == "multiselect" {
|
||||
n, err = optionValue(q, it)
|
||||
} else {
|
||||
n, err = scalar(q.Item, it)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k := catalog.Scalar(n)
|
||||
if seen[k] {
|
||||
continue
|
||||
}
|
||||
seen[k] = true
|
||||
out = append(out, n)
|
||||
}
|
||||
if err := checkCount(q.Validation, len(out)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
case "select":
|
||||
return optionValue(q, v)
|
||||
case "keyvalue":
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
s, isStr := v.(string)
|
||||
if !isStr {
|
||||
return nil, fmt.Errorf("want key=value pairs")
|
||||
}
|
||||
m = map[string]any{}
|
||||
for _, part := range splitList(s) {
|
||||
k, val, ok := strings.Cut(part, "=")
|
||||
if !ok || strings.TrimSpace(k) == "" {
|
||||
return nil, fmt.Errorf("%q: want key=value", part)
|
||||
}
|
||||
m[strings.TrimSpace(k)] = strings.TrimSpace(val)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
n, err := scalar(q.Type, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n, checkValue(q.Validation, n)
|
||||
}
|
||||
|
||||
func optionValue(q *catalog.Question, v any) (any, error) {
|
||||
s := strings.TrimSpace(catalog.Scalar(v))
|
||||
for _, o := range q.Options {
|
||||
if o.ID == s {
|
||||
return o.ID, nil
|
||||
}
|
||||
}
|
||||
// a number picks the n-th option (interactive CLI)
|
||||
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= len(q.Options) {
|
||||
return q.Options[n-1].ID, nil
|
||||
}
|
||||
ids := make([]string, len(q.Options))
|
||||
for i, o := range q.Options {
|
||||
ids[i] = o.ID
|
||||
}
|
||||
return nil, fmt.Errorf("%q is not one of %s", s, strings.Join(ids, ", "))
|
||||
}
|
||||
|
||||
func listOf(v any) []any {
|
||||
switch x := v.(type) {
|
||||
case []any:
|
||||
return x
|
||||
case []string:
|
||||
out := make([]any, len(x))
|
||||
for i, s := range x {
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
case string:
|
||||
var out []any
|
||||
for _, p := range splitList(x) {
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
case nil:
|
||||
return nil
|
||||
}
|
||||
return []any{v}
|
||||
}
|
||||
|
||||
func splitList(s string) []string {
|
||||
var out []string
|
||||
for _, p := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' || r == ';' }) {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// scalar validates one value of a scalar type.
|
||||
func scalar(typ string, v any) (any, error) {
|
||||
if fn, ok := extraTypes[typ]; ok {
|
||||
return fn(v)
|
||||
}
|
||||
if b, ok := v.(bool); ok && typ == "boolean" {
|
||||
return b, nil
|
||||
}
|
||||
s := strings.TrimSpace(catalog.Scalar(v))
|
||||
if len(s) > MaxAnswerLen || !utf8.ValidString(s) {
|
||||
return nil, fmt.Errorf("value too long or not UTF-8")
|
||||
}
|
||||
switch typ {
|
||||
case "boolean":
|
||||
switch strings.ToLower(s) {
|
||||
case "true", "yes", "y", "on", "1", "ja", "j":
|
||||
return true, nil
|
||||
case "false", "no", "n", "off", "0", "nein":
|
||||
return false, nil
|
||||
}
|
||||
return nil, fmt.Errorf("%q: want yes or no", s)
|
||||
case "integer":
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%q: want a whole number", s)
|
||||
}
|
||||
return int(n), nil
|
||||
case "decimal":
|
||||
f, err := strconv.ParseFloat(s, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%q: want a number", s)
|
||||
}
|
||||
return f, nil
|
||||
case "port":
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 1 || n > 65535 {
|
||||
return nil, fmt.Errorf("%q: want a port 1-65535", s)
|
||||
}
|
||||
return n, nil
|
||||
case "hostname", "domain":
|
||||
s = strings.ToLower(strings.TrimSuffix(s, "."))
|
||||
if !hostnameRE.MatchString(s) || len(s) > 253 {
|
||||
return nil, fmt.Errorf("%q: not a valid %s", s, typ)
|
||||
}
|
||||
if typ == "domain" && !strings.Contains(s, ".") {
|
||||
return nil, fmt.Errorf("%q: a domain needs a dot (example.org)", s)
|
||||
}
|
||||
return s, nil
|
||||
case "email":
|
||||
if !emailRE.MatchString(s) {
|
||||
return nil, fmt.Errorf("%q: not an e-mail address", s)
|
||||
}
|
||||
return s, nil
|
||||
case "ip":
|
||||
if net.ParseIP(s) == nil {
|
||||
return nil, fmt.Errorf("%q: not an IP address", s)
|
||||
}
|
||||
return s, nil
|
||||
case "cidr":
|
||||
if _, _, err := net.ParseCIDR(s); err != nil {
|
||||
if net.ParseIP(s) == nil {
|
||||
return nil, fmt.Errorf("%q: not a network (CIDR) or address", s)
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
case "url":
|
||||
u, err := url.Parse(s)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return nil, fmt.Errorf("%q: not a URL", s)
|
||||
}
|
||||
return s, nil
|
||||
case "duration":
|
||||
if _, err := time.ParseDuration(s); err != nil {
|
||||
return nil, fmt.Errorf("%q: want a duration like 30s, 5m, 4h", s)
|
||||
}
|
||||
return s, nil
|
||||
case "date":
|
||||
if !dateRE.MatchString(s) {
|
||||
return nil, fmt.Errorf("%q: want YYYY-MM-DD", s)
|
||||
}
|
||||
if _, err := time.Parse("2006-01-02", s); err != nil {
|
||||
return nil, fmt.Errorf("%q: not a date", s)
|
||||
}
|
||||
return s, nil
|
||||
case "path", "dir":
|
||||
if s == "" || strings.ContainsRune(s, 0) {
|
||||
return nil, fmt.Errorf("want a path")
|
||||
}
|
||||
return s, nil
|
||||
case "secret":
|
||||
// SEC-01/WIZ-07: only references, never the secret itself.
|
||||
if err := secretref.Validate(s); err != nil || s == "" {
|
||||
return nil, fmt.Errorf("give a reference (secret://name, env:VAR, file:path), never the secret itself")
|
||||
}
|
||||
return s, nil
|
||||
case "string", "text", "package", "profile", "capability", "provider", "target":
|
||||
return s, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown type %q", typ)
|
||||
}
|
||||
|
||||
func checkValue(val catalog.Validation, v any) error {
|
||||
msg := func(err string) error {
|
||||
if val.Message != "" {
|
||||
return fmt.Errorf("%s", val.Message)
|
||||
}
|
||||
return fmt.Errorf("%s", err)
|
||||
}
|
||||
if f, ok := v.(float64); ok {
|
||||
return checkRange(val, f, msg)
|
||||
}
|
||||
if n, ok := v.(int); ok {
|
||||
return checkRange(val, float64(n), msg)
|
||||
}
|
||||
if s, ok := v.(string); ok {
|
||||
if val.MinLength > 0 && len(s) < val.MinLength {
|
||||
return msg(fmt.Sprintf("at least %d characters", val.MinLength))
|
||||
}
|
||||
if val.MaxLength > 0 && len(s) > val.MaxLength {
|
||||
return msg(fmt.Sprintf("at most %d characters", val.MaxLength))
|
||||
}
|
||||
if val.Pattern != "" {
|
||||
re, err := regexp.Compile(val.Pattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bad pattern in catalog: %v", err)
|
||||
}
|
||||
if !re.MatchString(s) {
|
||||
return msg(fmt.Sprintf("%q does not match %s", s, val.Pattern))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkRange(val catalog.Validation, f float64, msg func(string) error) error {
|
||||
if val.Min != nil && f < *val.Min {
|
||||
return msg(fmt.Sprintf("at least %v", *val.Min))
|
||||
}
|
||||
if val.Max != nil && f > *val.Max {
|
||||
return msg(fmt.Sprintf("at most %v", *val.Max))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkCount(val catalog.Validation, n int) error {
|
||||
if val.MinItems > 0 && n < val.MinItems {
|
||||
if val.Message != "" {
|
||||
return fmt.Errorf("%s", val.Message)
|
||||
}
|
||||
return fmt.Errorf("at least %d item(s)", val.MinItems)
|
||||
}
|
||||
if val.MaxItems > 0 && n > val.MaxItems {
|
||||
return fmt.Errorf("at most %d item(s)", val.MaxItems)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestZZDump(t *testing.T) {
|
||||
if os.Getenv("DUMP") == "" {
|
||||
t.Skip()
|
||||
}
|
||||
c := assetsCatalog(t)
|
||||
e := New(c)
|
||||
x := c.Examples[os.Getenv("DUMP")]
|
||||
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
|
||||
in.Spec.Parameters = x.Spec.Parameters
|
||||
st, _ := e.Evaluate(in, nil)
|
||||
for _, f := range st.Files {
|
||||
t.Logf("=== %s\n%s", f.Path, f.Content)
|
||||
}
|
||||
for _, s := range st.Steps {
|
||||
t.Logf("step %s [%s] %s", s.Phase, s.Run, s.Title)
|
||||
}
|
||||
for _, p := range st.Packages {
|
||||
t.Logf("pkg %s %s %v", p.ID, p.Status, p.Reasons)
|
||||
}
|
||||
t.Log(GraphText(st.Graph))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
module yetano.dev/yetano/core/solutions
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1
|
||||
|
||||
require yetano.dev/yetano/core v0.12.2
|
||||
@@ -0,0 +1,6 @@
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
yetano.dev/yetano/core v0.12.2 h1:y8xkA1XjNTGiO9/JJRal5/IruoaqcE8aKJUYG8wVF6Q=
|
||||
yetano.dev/yetano/core v0.12.2/go.mod h1:T2TdFvZiHbYVgcRmRXk9NC82AYL8krGVxxtLyedWuJE=
|
||||
@@ -0,0 +1,34 @@
|
||||
package knowledge
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"yetano.dev/yetano/core/solutions/catalog"
|
||||
)
|
||||
|
||||
func assetsIndex(t *testing.T) *Index {
|
||||
t.Helper()
|
||||
dir, _ := filepath.Abs("../../../assets/solutions")
|
||||
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
|
||||
t.Skip("assets/solutions not present")
|
||||
}
|
||||
c, err := catalog.Load(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return Build(c)
|
||||
}
|
||||
|
||||
func TestAssetsLint(t *testing.T) {
|
||||
ix := assetsIndex(t)
|
||||
for _, i := range Lint(ix) {
|
||||
if i.Severity == "error" {
|
||||
t.Error(i)
|
||||
} else {
|
||||
t.Log(i)
|
||||
}
|
||||
}
|
||||
t.Logf("%d entries, %d manual topics, missing sources: %v", len(ix.Entries), len(ix.Topics), ix.Missing)
|
||||
}
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user