Compare commits
7
Commits
gui/v0.1.0
..
v0.8.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c11197bb37 | ||
|
|
5471863163 | ||
|
|
5288c4ce74 | ||
|
|
fa52990e3e | ||
|
|
185211e304 | ||
|
|
b7f7ba6b36 | ||
|
|
88d37410f7 |
No files matched your search
@@ -251,6 +251,13 @@ YAML tree, the templates and, via reflection on the program's struct,
|
|||||||
which keys exist. It started as `yamase-core/pkg/configcmd` and moved
|
which keys exist. It started as `yamase-core/pkg/configcmd` and moved
|
||||||
here unchanged in behavior when the other meta-repos needed it.
|
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
|
## core/gui: a nested module, not a package of this one
|
||||||
|
|
||||||
The WebView host needs cgo and Cocoa/WebKit on macOS and
|
The WebView host needs cgo and Cocoa/WebKit on macOS and
|
||||||
@@ -269,3 +276,13 @@ the same exception the root AGENTS.md makes for
|
|||||||
`paths/knownfolders_windows.go`. Everything above the window (`assets`,
|
`paths/knownfolders_windows.go`. Everything above the window (`assets`,
|
||||||
`document`, `bridge`) is platform-free and unit-tested on any host;
|
`document`, `bridge`) is platform-free and unit-tested on any host;
|
||||||
browser behavior is verified by the prototype's in-window selftest.
|
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.
|
||||||
@@ -13,10 +13,11 @@ every Yetano program offers (`core/manual`, `core/completion`,
|
|||||||
docs/program-conventions.md in the meta-repository), and secret
|
docs/program-conventions.md in the meta-repository), and secret
|
||||||
references in configuration (`core/secretref`).
|
references in configuration (`core/secretref`).
|
||||||
|
|
||||||
The native WebView GUI host is a **separate, nested module**,
|
Two **separate, nested modules** keep this module at its single
|
||||||
`yetano.dev/yetano/core/gui` (tags `gui/vX.Y.Z`), so this module keeps
|
dependency: the native WebView GUI host `yetano.dev/yetano/core/gui`
|
||||||
its single dependency and stays free of cgo -- see
|
(tags `gui/vX.Y.Z`, cgo, see [gui/README.md](gui/README.md)) and the
|
||||||
[gui/README.md](gui/README.md).
|
shared terminal-UI kernel `yetano.dev/yetano/core/tui` (tags
|
||||||
|
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)).
|
||||||
|
|
||||||
```text
|
```text
|
||||||
yetano.dev/yetano/core
|
yetano.dev/yetano/core
|
||||||
@@ -26,14 +27,17 @@ yetano.dev/yetano/core/manual
|
|||||||
yetano.dev/yetano/core/completion
|
yetano.dev/yetano/core/completion
|
||||||
yetano.dev/yetano/core/doctor
|
yetano.dev/yetano/core/doctor
|
||||||
yetano.dev/yetano/core/configcmd
|
yetano.dev/yetano/core/configcmd
|
||||||
|
yetano.dev/yetano/core/configfamily
|
||||||
yetano.dev/yetano/core/version
|
yetano.dev/yetano/core/version
|
||||||
yetano.dev/yetano/core/secretref
|
yetano.dev/yetano/core/secretref
|
||||||
|
yetano.dev/yetano/core/cobracmd (separate module)
|
||||||
|
|
||||||
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
|
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
|
||||||
yetano.dev/yetano/core/gui/assets
|
yetano.dev/yetano/core/gui/assets
|
||||||
yetano.dev/yetano/core/gui/document
|
yetano.dev/yetano/core/gui/document
|
||||||
yetano.dev/yetano/core/gui/bridge
|
yetano.dev/yetano/core/gui/bridge
|
||||||
yetano.dev/yetano/core/gui/window
|
yetano.dev/yetano/core/gui/window
|
||||||
|
yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z)
|
||||||
```
|
```
|
||||||
|
|
||||||
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||||
@@ -248,6 +252,27 @@ LOCALAPPDATA/APPDATA/PROGRAMDATA layering `core/paths` already resolves.
|
|||||||
layer can write `key: null` to intentionally unset a lower layer's
|
layer can write `key: null` to intentionally unset a lower layer's
|
||||||
value).
|
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
|
### Environment expansion
|
||||||
|
|
||||||
String values may reference `${VAR}` or `$VAR` (enabled by default,
|
String values may reference `${VAR}` or `$VAR` (enabled by default,
|
||||||
@@ -332,6 +357,69 @@ in the full template -- that is what keeps `config upgrade` useful.
|
|||||||
report options the program ignores. Taken over from
|
report options the program ignores. Taken over from
|
||||||
`yamase-core/pkg/configcmd`, which now wraps it.
|
`yamase-core/pkg/configcmd`, which now wraps it.
|
||||||
|
|
||||||
|
`config show [--json] [--show-secrets]` prints the configuration with
|
||||||
|
the file every value comes from (`Effective.Show`; secrets -- keys
|
||||||
|
`secrets`, `secret`, `token`, `password` -- are redacted unless
|
||||||
|
`--show-secrets`, references like `env:X` stay visible), and
|
||||||
|
`configcmd.Doctor(report, spec, explicit)` is the config part of a
|
||||||
|
`doctor` command (paths, layers, "config file found", unknown options).
|
||||||
|
|
||||||
|
A program whose configuration is merged from more than one file name
|
||||||
|
per directory -- a family-wide file, a section of it and a per-program
|
||||||
|
file, as in the yamase family -- sets `Spec.Layered`: `Layers` (what
|
||||||
|
`config path` lists), `Load` (merge, e.g. with `config.Merge`, into an
|
||||||
|
`Effective`), optionally `Unknown` (its own unknown-option rules),
|
||||||
|
`Validate(merged)` and `Used(key)`. `path`, `validate` and `show` then
|
||||||
|
work on all layers, unknown options become warnings (shared files carry
|
||||||
|
options of other programs), and `create`/`upgrade` keep working on the
|
||||||
|
program's own file. `KnownKey(schema, "a.b[0].c")` tells whether a
|
||||||
|
dotted key is an option of a config struct.
|
||||||
|
|
||||||
|
## core/configfamily: one file per program, an optional family file
|
||||||
|
|
||||||
|
`core/configfamily` is that layered setup ready-made, for a family of
|
||||||
|
programs that share one set of config directories (the yamase-* or
|
||||||
|
yaiam-* programs). Each program is responsible for its own file
|
||||||
|
(`<program>.yaml`); the family file (`<family>.yaml`) is optional and
|
||||||
|
holds, at its top level, what several programs share, plus one section
|
||||||
|
per program (`web:` for `yaiam-web`). Per tier -- system, then user,
|
||||||
|
then `--config` -- a program merges: family file top level, its section,
|
||||||
|
its own file. The working directory is never read.
|
||||||
|
|
||||||
|
```go
|
||||||
|
family := configfamily.Family{
|
||||||
|
Name: "yaiam", Programs: []string{"ctl", "web", "authd"},
|
||||||
|
Shared: config.Shared{}, SharedTemplate: config.SharedTemplate,
|
||||||
|
}
|
||||||
|
spec := configfamily.Spec{
|
||||||
|
Program: family.Service("yaiam-web"), Optional: true,
|
||||||
|
Minimal: webMinimal, Full: webFull, Schema: config.WebConfig{},
|
||||||
|
Validate: func(merged []byte) error { ... },
|
||||||
|
}
|
||||||
|
os.Exit(configfamily.Run(spec, configFlag, args, os.Stdout, os.Stderr))
|
||||||
|
```
|
||||||
|
|
||||||
|
`Load(program, explicit)` returns the merged layers (`Loaded.YAML()`
|
||||||
|
for the program's own parser, `Describe()` for log lines) or
|
||||||
|
`ErrNotFound`; `Loaded.Unknown(schema)` reports options no layer may
|
||||||
|
carry -- an option of `Family.Shared` is valid in every layer, other
|
||||||
|
programs' sections are not this program's business. `Run` adds `config
|
||||||
|
create --shared` (writes `Family.SharedTemplate`) to core/configcmd's
|
||||||
|
commands; `Doctor`, `LogLayers` and `WarnUnknown` are the doctor and
|
||||||
|
startup parts. Defaults that depend on more than the files (yamase's
|
||||||
|
data-dir and storage roles) stay with the family's own code.
|
||||||
|
|
||||||
|
## core/cobracmd: cobra programs (separate module)
|
||||||
|
|
||||||
|
`yetano.dev/yetano/core/cobracmd` (own `go.mod`, tags `cobracmd/vX.Y.Z`,
|
||||||
|
so the main module stays free of cobra) fixes the two places where cobra
|
||||||
|
behaves differently from the standard: `cobracmd.Completion(root)`
|
||||||
|
replaces cobra's default `completion` command with one that takes exactly
|
||||||
|
`bash|zsh|fish|powershell` (cobra's own exits 0 for `completion tcsh`),
|
||||||
|
and `os.Exit(cobracmd.Execute(root))` maps errors to the standard exit
|
||||||
|
codes -- 2 for usage errors (unknown command, flag or shell, wrong
|
||||||
|
argument count, or an error wrapped with `cobracmd.Usage`), 1 otherwise.
|
||||||
|
|
||||||
## core/version: "<program> version [--json]"
|
## core/version: "<program> version [--json]"
|
||||||
|
|
||||||
The values stay in each program's `internal/version` (stamped with
|
The values stay in each program's `internal/version` (stamped with
|
||||||
@@ -360,9 +448,9 @@ one-line form for log lines and web UI footers.
|
|||||||
|
|
||||||
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
||||||
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
||||||
force-moved to a different commit. The nested `gui` module has its own
|
force-moved to a different commit. The nested `gui` and `tui` modules
|
||||||
prefixed tags (`gui/v0.1.0`, ...); a change there needs no main-module
|
have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change
|
||||||
tag and vice versa.
|
there needs no main-module tag and vice versa.
|
||||||
|
|
||||||
## core/secretref
|
## core/secretref
|
||||||
|
|
||||||
@@ -397,3 +485,11 @@ streaming, abort and reload handling -- never a local HTTP listener or
|
|||||||
port. Packages `assets`, `document`, `bridge`, `window`; extracted from
|
port. Packages `assets`, `document`, `bridge`, `window`; extracted from
|
||||||
`prototypes/yetano-webview` (AP1). Details, invariants, measured platform
|
`prototypes/yetano-webview` (AP1). Details, invariants, measured platform
|
||||||
pitfalls and the yet-gui migration: [gui/README.md](gui/README.md).
|
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.
|
||||||
@@ -23,8 +23,9 @@ speculatively.
|
|||||||
`docs/install-store-and-profiles.md`).
|
`docs/install-store-and-profiles.md`).
|
||||||
- [x] `yaseva` was built on `core/paths`/`core/config` from the start.
|
- [x] `yaseva` was built on `core/paths`/`core/config` from the start.
|
||||||
- [x] The remaining applications across the `yetano`, `yak`, and
|
- [x] The remaining applications across the `yetano`, `yak`, and
|
||||||
`yamase` meta-repos were migrated on 2026-09-22; the record (and the
|
`yamase` meta-repos were migrated on 2026-09-22; the open
|
||||||
few open follow-ups) is the meta-repo's `TODO-pathchange.md`.
|
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
|
## Standard commands
|
||||||
|
|
||||||
@@ -39,6 +40,12 @@ speculatively.
|
|||||||
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
|
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
|
||||||
(steps in [gui/README.md](gui/README.md)).
|
(steps in [gui/README.md](gui/README.md)).
|
||||||
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
||||||
|
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
|
||||||
|
ListState, text helpers) as the nested module
|
||||||
|
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
|
||||||
|
- [ ] Move yet's and yavebu's `internal/tui` onto `core/tui` (steps in
|
||||||
|
[tui/README.md](tui/README.md)); yalsh menuconfig after an owner
|
||||||
|
decision on `yalsh.dev` -> `yetano.dev` imports.
|
||||||
|
|
||||||
## Platform tuning
|
## Platform tuning
|
||||||
|
|
||||||
|
|||||||
@@ -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=
|
||||||
@@ -97,7 +97,7 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
switch shell {
|
switch shell {
|
||||||
case "bash":
|
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)
|
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 {
|
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\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
|
||||||
|
|||||||
@@ -179,3 +179,9 @@ func (r *Resolver) Application() core.Application { return r.app }
|
|||||||
// Filename returns the configuration file name this Resolver searches
|
// Filename returns the configuration file name this Resolver searches
|
||||||
// for in every layer.
|
// for in every layer.
|
||||||
func (r *Resolver) Filename() string { return r.filename }
|
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 {
|
if base == nil {
|
||||||
base = map[string]any{}
|
base = map[string]any{}
|
||||||
}
|
}
|
||||||
for k, v := range over {
|
mergeTracked(base, over, "", "", nil)
|
||||||
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
|
|
||||||
}
|
|
||||||
return base
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
-6
@@ -6,6 +6,7 @@
|
|||||||
// <program> config validate
|
// <program> config validate
|
||||||
// <program> config upgrade [--write]
|
// <program> config upgrade [--write]
|
||||||
// <program> config path
|
// <program> config path
|
||||||
|
// <program> config show [--json] [--show-secrets]
|
||||||
//
|
//
|
||||||
// The command behaves the same in every program; what differs is only
|
// 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
|
// 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
|
// Exit codes: 0 success, 1 the command ran and found a problem (invalid
|
||||||
// configuration, no file found, refusing to overwrite), 2 usage error.
|
// 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
|
// The package does not depend on cobra: a cobra program wires Run into
|
||||||
// a command with flag parsing disabled, taking --config out of the
|
// a command with flag parsing disabled, taking --config out of the
|
||||||
// arguments itself, the same way it wires core/doctor.
|
// arguments itself, the same way it wires core/doctor.
|
||||||
@@ -79,8 +85,8 @@ type Spec struct {
|
|||||||
Filename string
|
Filename string
|
||||||
|
|
||||||
// Optional says the program also runs without a configuration file
|
// Optional says the program also runs without a configuration file
|
||||||
// (on built-in defaults): "validate" and "upgrade" then report that
|
// (on built-in defaults): "validate", "upgrade", "show" and Doctor
|
||||||
// no file exists instead of failing.
|
// then report that no file exists instead of failing.
|
||||||
Optional bool
|
Optional bool
|
||||||
|
|
||||||
// None says the program has no configuration at all; every
|
// None says the program has no configuration at all; every
|
||||||
@@ -113,6 +119,12 @@ type Spec struct {
|
|||||||
// Options are passed through to core/config; tests use them to
|
// Options are passed through to core/config; tests use them to
|
||||||
// inject a platform, environment, root and working directory.
|
// inject a platform, environment, root and working directory.
|
||||||
Options []coreconfig.Option
|
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 {
|
func (s Spec) filename() string {
|
||||||
@@ -131,7 +143,7 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
|||||||
}
|
}
|
||||||
sub, rest := args[0], args[1:]
|
sub, rest := args[0], args[1:]
|
||||||
switch sub {
|
switch sub {
|
||||||
case "create", "validate", "upgrade", "path":
|
case "create", "validate", "upgrade", "path", "show":
|
||||||
if s.None {
|
if s.None {
|
||||||
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
||||||
return ExitOK
|
return ExitOK
|
||||||
@@ -141,11 +153,25 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
|||||||
case "create":
|
case "create":
|
||||||
return s.create(explicit, rest, stdout, stderr)
|
return s.create(explicit, rest, stdout, stderr)
|
||||||
case "validate":
|
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)
|
return s.validate(explicit, rest, stdout, stderr)
|
||||||
case "upgrade":
|
case "upgrade":
|
||||||
return s.upgrade(explicit, rest, stdout, stderr)
|
return s.upgrade(explicit, rest, stdout, stderr)
|
||||||
case "path":
|
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)
|
return s.path(explicit, rest, stdout, stderr)
|
||||||
|
case "show":
|
||||||
|
return s.show(explicit, rest, stdout, stderr)
|
||||||
case "help", "-h", "-help", "--help":
|
case "help", "-h", "-help", "--help":
|
||||||
usage(s, stdout)
|
usage(s, stdout)
|
||||||
return ExitOK
|
return ExitOK
|
||||||
@@ -158,9 +184,13 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
|||||||
|
|
||||||
// Subcommands are the config subcommands, for a program's completion
|
// Subcommands are the config subcommands, for a program's completion
|
||||||
// tree and help text.
|
// 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) {
|
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>]
|
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
||||||
|
|
||||||
create [--minimal|--full] [--force] [--output <file>]
|
create [--minimal|--full] [--force] [--output <file>]
|
||||||
@@ -169,8 +199,11 @@ func usage(s Spec, w io.Writer) {
|
|||||||
upgrade [--write]
|
upgrade [--write]
|
||||||
show the options of "create --full" the file does not mention
|
show the options of "create --full" the file does not mention
|
||||||
yet, as commented blocks; --write adds them to the file
|
yet, as commented blocks; --write adds them to the file
|
||||||
path list the locations searched for %[2]s, highest priority first
|
path %[3]s
|
||||||
`, s.Name, s.filename())
|
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
|
// newFlagSet returns a flag set for one subcommand whose usage errors go
|
||||||
|
|||||||
@@ -0,0 +1,316 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
coreconfig "yetano.dev/yetano/core/config"
|
||||||
|
"yetano.dev/yetano/core/doctor"
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Layered describes a program whose configuration is merged from
|
||||||
|
// several inputs that are not one file name per directory -- e.g. a
|
||||||
|
// family-wide file, one section of it and a per-program file in every
|
||||||
|
// tier (the yamase family, yamase ADR-0074). With Spec.Layered set,
|
||||||
|
// "config path", "config validate" and "config show" work on all
|
||||||
|
// layers; "config create" and "config upgrade" keep working on the
|
||||||
|
// program's own file (Spec.Filename).
|
||||||
|
//
|
||||||
|
// Unknown options are warnings for a layered program, not problems:
|
||||||
|
// files shared between programs (of different versions) legitimately
|
||||||
|
// carry options one program does not read.
|
||||||
|
type Layered struct {
|
||||||
|
// Layers lists every input, highest priority first, whether it
|
||||||
|
// exists or not (for "config path" and doctor). explicit is the
|
||||||
|
// --config value.
|
||||||
|
Layers func(explicit string) ([]LayerInfo, error)
|
||||||
|
|
||||||
|
// Load merges the existing layers. With none at all it returns an
|
||||||
|
// error wrapping ErrNotFound.
|
||||||
|
Load func(explicit string) (*Effective, error)
|
||||||
|
|
||||||
|
// Unknown reports the unknown options of e's layers. nil: every
|
||||||
|
// existing layer's file is checked against Spec.Schema.
|
||||||
|
Unknown func(e *Effective) ([]UnknownKey, error)
|
||||||
|
|
||||||
|
// Validate parses and validates the merged configuration (YAML) the
|
||||||
|
// way the program does at startup, including files it names. For an
|
||||||
|
// Optional program without any file it gets nil (the defaults).
|
||||||
|
Validate func(merged []byte) error
|
||||||
|
|
||||||
|
// Used reports whether the program reads the option key, for "config
|
||||||
|
// show". nil: KnownKey(Spec.Schema, key).
|
||||||
|
Used func(key string) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// LayerInfo is one input of a layered configuration.
|
||||||
|
type LayerInfo struct {
|
||||||
|
// Name is how the layer is shown and recorded as an origin: the
|
||||||
|
// path, plus e.g. " [section]" for a part of a file.
|
||||||
|
Name string
|
||||||
|
// Path is the file that holds it.
|
||||||
|
Path string
|
||||||
|
// Source names the tier ("system-directory", "--config", ...).
|
||||||
|
Source string
|
||||||
|
// Exists reports whether the layer contributes anything.
|
||||||
|
Exists bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effective is a merged configuration: its layers, the merged mapping
|
||||||
|
// and the origin (LayerInfo.Name, or a default's name) of every leaf.
|
||||||
|
type Effective struct {
|
||||||
|
// Name is the program's name, for "config show"'s header.
|
||||||
|
Name string
|
||||||
|
// Layers are all layers, highest priority first.
|
||||||
|
Layers []LayerInfo
|
||||||
|
Merged map[string]any
|
||||||
|
Origins coreconfig.Origins
|
||||||
|
// Loader is the Layered loader's own value for this configuration
|
||||||
|
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
|
||||||
|
Loader any
|
||||||
|
}
|
||||||
|
|
||||||
|
// Used returns the layers that contributed, highest priority first.
|
||||||
|
func (e *Effective) Used() []LayerInfo {
|
||||||
|
var out []LayerInfo
|
||||||
|
for _, l := range e.Layers {
|
||||||
|
if l.Exists {
|
||||||
|
out = append(out, l)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Describe names the layers that contributed, lowest priority first
|
||||||
|
// ("a.yaml + b.yaml [section]"), for log lines and messages.
|
||||||
|
func (e *Effective) Describe() string {
|
||||||
|
used := e.Used()
|
||||||
|
names := make([]string, len(used))
|
||||||
|
for i, l := range used {
|
||||||
|
names[len(used)-1-i] = l.Name
|
||||||
|
}
|
||||||
|
return strings.Join(names, " + ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// YAML returns the merged configuration as YAML, for the program's own
|
||||||
|
// parser.
|
||||||
|
func (e *Effective) YAML() ([]byte, error) {
|
||||||
|
data, err := yaml.Marshal(e.Merged)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("config: marshal merged configuration: %w", err)
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// effective loads the configuration "config show" and Doctor report:
|
||||||
|
// Layered.Load, or else the single file Find selects as the only layer.
|
||||||
|
func (s Spec) effective(explicit string) (*Effective, error) {
|
||||||
|
if s.Layered != nil {
|
||||||
|
return s.Layered.Load(explicit)
|
||||||
|
}
|
||||||
|
file, err := s.Find(explicit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := coreconfig.ReadFile(file.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
merged, origins := coreconfig.Merge(coreconfig.Source{Name: file.Path, Data: data})
|
||||||
|
src := file.Source.String()
|
||||||
|
return &Effective{
|
||||||
|
Name: s.Name,
|
||||||
|
Layers: []LayerInfo{{Name: file.Path, Path: file.Path, Source: src, Exists: true}},
|
||||||
|
Merged: merged,
|
||||||
|
Origins: origins,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnknownIn returns the unknown options of e's layers: Layered.Unknown
|
||||||
|
// if set, else every existing layer's file against s.Schema.
|
||||||
|
func (s Spec) UnknownIn(e *Effective) ([]UnknownKey, error) {
|
||||||
|
if s.Layered != nil && s.Layered.Unknown != nil {
|
||||||
|
return s.Layered.Unknown(e)
|
||||||
|
}
|
||||||
|
if s.Schema == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var out []UnknownKey
|
||||||
|
for i := len(e.Layers) - 1; i >= 0; i-- {
|
||||||
|
l := e.Layers[i]
|
||||||
|
if !l.Exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
keys, err := UnknownKeysFile(l.Path, s.Schema)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
k.Layer = l.Name
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) layeredPath(explicit string, stdout, stderr io.Writer) int {
|
||||||
|
layers, err := s.Layered.Layers(explicit)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config path: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, l := range layers {
|
||||||
|
mark, state := " ", "missing"
|
||||||
|
if l.Exists {
|
||||||
|
mark, state, found = "*", "used", true
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s %s (%s, %s)\n", mark, l.Name, l.Source, state)
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- \"%s config create\" writes one\n", s.Name)
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) layeredValidate(explicit string, stdout, stderr io.Writer) int {
|
||||||
|
e, err := s.Layered.Load(explicit)
|
||||||
|
if err != nil && s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
|
||||||
|
if s.Layered.Validate != nil {
|
||||||
|
if err := s.Layered.Validate(nil); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s: no configuration file, and the built-in defaults are invalid: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults (\"%s config path\" lists the locations)\n", s.Name, s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
unknown, err := s.UnknownIn(e)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
for _, k := range unknown {
|
||||||
|
fmt.Fprintf(stdout, "warning: unknown option %s (%s, line %d), ignored -- the default applies\n", k.Key, k.Layer, k.Line)
|
||||||
|
}
|
||||||
|
if s.Layered.Validate != nil {
|
||||||
|
data, err := e.YAML()
|
||||||
|
if err == nil {
|
||||||
|
err = s.Layered.Validate(data)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config validate: %s: %v\n", s.Name, e.Describe(), err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s: valid\n", e.Describe())
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
fs := s.newFlagSet("show", stderr)
|
||||||
|
asJSON := fs.Bool("json", false, "print a JSON array of {key, value, source, used}")
|
||||||
|
secrets := fs.Bool("show-secrets", false, "print secret values instead of <redacted>")
|
||||||
|
if code := parse(fs, args); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
e, err := s.effective(explicit)
|
||||||
|
if err != nil {
|
||||||
|
if s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults\n", s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
used := s.usedFunc()
|
||||||
|
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// usedFunc is Layered.Used, else KnownKey against the schema (every key
|
||||||
|
// counts as used without one).
|
||||||
|
func (s Spec) usedFunc() func(string) bool {
|
||||||
|
if s.Layered != nil && s.Layered.Used != nil {
|
||||||
|
return s.Layered.Used
|
||||||
|
}
|
||||||
|
if s.Schema == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return func(key string) bool { return KnownKey(s.Schema, key) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Doctor records the program's core/paths locations and every
|
||||||
|
// configuration layer in r, checks that the configuration loads and has
|
||||||
|
// no unknown options, and returns it (nil when it does not load).
|
||||||
|
// Nothing is created. A layered program's unknown options are reported
|
||||||
|
// as a failed check like any program's: doctor is where an operator
|
||||||
|
// looks for them.
|
||||||
|
func Doctor(r *doctor.Report, s Spec, explicit string) *Effective {
|
||||||
|
r.AddPaths(s.App)
|
||||||
|
if s.Layered != nil {
|
||||||
|
layers, err := s.Layered.Layers(explicit)
|
||||||
|
if err != nil {
|
||||||
|
r.AddPath("config search", "", err)
|
||||||
|
}
|
||||||
|
for _, l := range layers {
|
||||||
|
name := "config search (" + l.Source + ")"
|
||||||
|
if l.Exists {
|
||||||
|
name = "config file (" + l.Source + ")"
|
||||||
|
}
|
||||||
|
r.AddPath(name, l.Name, nil)
|
||||||
|
}
|
||||||
|
} else if layers, err := s.Layers(explicit); err != nil {
|
||||||
|
r.AddPath("config search", "", err)
|
||||||
|
} else {
|
||||||
|
for _, l := range layers {
|
||||||
|
src := l.Source.String()
|
||||||
|
if l.Source == paths.APIOverride {
|
||||||
|
src = "--config"
|
||||||
|
}
|
||||||
|
r.AddPath("config search ("+src+")", l.Path, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e, err := s.effective(explicit)
|
||||||
|
if err != nil && s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
|
||||||
|
r.Check("config file found", true, "none, "+s.Name+" runs on its built-in defaults")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
note := err.Error()
|
||||||
|
if errors.Is(err, ErrNotFound) {
|
||||||
|
note = "none of the searched files exists; pass --config <file> or run \"" + s.Name + " config create\""
|
||||||
|
}
|
||||||
|
r.Check("config file found", false, note)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
r.Check("config file found", true, e.Describe())
|
||||||
|
if s.Schema != nil || (s.Layered != nil && s.Layered.Unknown != nil) {
|
||||||
|
unknown, err := s.UnknownIn(e)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
r.Check("config has no unknown options", false, err.Error())
|
||||||
|
case len(unknown) == 0:
|
||||||
|
r.Check("config has no unknown options", true, "")
|
||||||
|
default:
|
||||||
|
parts := make([]string, len(unknown))
|
||||||
|
for i, k := range unknown {
|
||||||
|
parts[i] = k.String()
|
||||||
|
}
|
||||||
|
r.Check("config has no unknown options", false, "ignored, the defaults apply: "+strings.Join(parts, ", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
coreconfig "yetano.dev/yetano/core/config"
|
||||||
|
"yetano.dev/yetano/core/doctor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestShowSingleFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
file := filepath.Join(root, "etc", "yamase", "yamase-test.yaml")
|
||||||
|
writeFile(t, file, minimalTemplate+"log-level: debug\nunread: 1\n")
|
||||||
|
code, out, errOut := run(t, s, "", "show")
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("show: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
`log-level: "debug"`,
|
||||||
|
"# " + file,
|
||||||
|
`root: "/var/lib/yamase/queue"`,
|
||||||
|
"unread: 1",
|
||||||
|
"not used by yamase-test",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("show output lacks %q:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
code, out, _ = run(t, s, "", "show", "--json")
|
||||||
|
var values []Value
|
||||||
|
if code != ExitOK || json.Unmarshal([]byte(out), &values) != nil || len(values) == 0 {
|
||||||
|
t.Errorf("show --json: exit %d, output %q", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeLayered serves two layers of one directory, as a family-wide file
|
||||||
|
// plus a program file.
|
||||||
|
func fakeLayered(dir string) *Layered {
|
||||||
|
shared := filepath.Join(dir, "family.yaml")
|
||||||
|
own := filepath.Join(dir, "own.yaml")
|
||||||
|
layers := func(string) ([]LayerInfo, error) {
|
||||||
|
return []LayerInfo{
|
||||||
|
{Name: own, Path: own, Source: "test", Exists: statOK(own)},
|
||||||
|
{Name: shared, Path: shared, Source: "test", Exists: statOK(shared)},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return &Layered{
|
||||||
|
Layers: layers,
|
||||||
|
Load: func(explicit string) (*Effective, error) {
|
||||||
|
ls, _ := layers(explicit)
|
||||||
|
var sources []coreconfig.Source
|
||||||
|
for i := len(ls) - 1; i >= 0; i-- {
|
||||||
|
if !ls[i].Exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := coreconfig.ReadFile(ls[i].Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sources = append(sources, coreconfig.Source{Name: ls[i].Name, Data: data})
|
||||||
|
}
|
||||||
|
if len(sources) == 0 {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
merged, origins := coreconfig.Merge(sources...)
|
||||||
|
return &Effective{Name: "yamase-test", Layers: ls, Merged: merged, Origins: origins}, nil
|
||||||
|
},
|
||||||
|
Validate: func(merged []byte) error {
|
||||||
|
var s schema
|
||||||
|
if err := yaml.Unmarshal(merged, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(s.Listen) == 0 {
|
||||||
|
return errNoListener
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type testErr string
|
||||||
|
|
||||||
|
func (e testErr) Error() string { return string(e) }
|
||||||
|
|
||||||
|
const errNoListener = testErr("listen: at least one listener is required")
|
||||||
|
|
||||||
|
func statOK(path string) bool { return statExistsForTest(path) }
|
||||||
|
|
||||||
|
func TestLayered(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
dir := filepath.Join(root, "cfg")
|
||||||
|
s := testSpec(root)
|
||||||
|
s.Layered = fakeLayered(dir)
|
||||||
|
|
||||||
|
if code, out, _ := run(t, s, "", "path"); code != ExitOK || !strings.Contains(out, "no configuration file found") {
|
||||||
|
t.Errorf("path without files: exit %d, %q", code, out)
|
||||||
|
}
|
||||||
|
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, ErrNotFound.Error()) {
|
||||||
|
t.Errorf("validate without files: exit %d, %q", code, errOut)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\nlisten:\n - address: \":25\"\n")
|
||||||
|
writeFile(t, filepath.Join(dir, "own.yaml"), "log-level: debug\nlog-levle: x\n")
|
||||||
|
|
||||||
|
code, out, _ := run(t, s, "", "path")
|
||||||
|
if code != ExitOK || strings.Count(out, "(test, used)") != 2 {
|
||||||
|
t.Errorf("path: exit %d, %q", code, out)
|
||||||
|
}
|
||||||
|
// Unknown options are warnings for a layered program.
|
||||||
|
code, out, errOut := run(t, s, "", "validate")
|
||||||
|
if code != ExitOK || !strings.Contains(out, "warning: unknown option log-levle ("+filepath.Join(dir, "own.yaml")+", line 2)") || !strings.Contains(out, ": valid") {
|
||||||
|
t.Errorf("validate: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
code, out, _ = run(t, s, "", "show")
|
||||||
|
if code != ExitOK || !strings.Contains(out, `log-level: "debug"`) || !strings.Contains(out, "# "+filepath.Join(dir, "family.yaml")) {
|
||||||
|
t.Errorf("show: exit %d:\n%s", code, out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "layers, lowest priority first: "+filepath.Join(dir, "family.yaml")+" + "+filepath.Join(dir, "own.yaml")) {
|
||||||
|
t.Errorf("show header:\n%s", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\n")
|
||||||
|
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "listen") {
|
||||||
|
t.Errorf("validate of an invalid merge: exit %d, %q", code, errOut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDoctor(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
r := doctor.Report{Program: "yamase-test"}
|
||||||
|
if e := Doctor(&r, s, ""); e != nil {
|
||||||
|
t.Error("Doctor without a file returned a configuration")
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-levle: x\n")
|
||||||
|
r = doctor.Report{Program: "yamase-test"}
|
||||||
|
e := Doctor(&r, s, "")
|
||||||
|
if e == nil {
|
||||||
|
t.Fatal("Doctor with a file returned nil")
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
r.Run([]string{"--json"}, &out, &out)
|
||||||
|
if !strings.Contains(out.String(), "log-levle (") || !strings.Contains(out.String(), "config file found") {
|
||||||
|
t.Errorf("doctor report = %s", out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValuesRedaction(t *testing.T) {
|
||||||
|
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
|
||||||
|
"srs": map[string]any{"secrets": []any{"plain", "env:X", "base64:abc"}},
|
||||||
|
"yaais": map[string]any{"token": "file:/run/t", "password": "hunter2"},
|
||||||
|
}})
|
||||||
|
e := &Effective{Name: "p", Merged: merged, Origins: origins}
|
||||||
|
got := map[string]any{}
|
||||||
|
for _, v := range e.Values(nil, false) {
|
||||||
|
got[v.Key] = v.Value
|
||||||
|
}
|
||||||
|
want := map[string]any{
|
||||||
|
"srs.secrets": []any{"<redacted>", "env:X", "<redacted>"},
|
||||||
|
"yaais.token": "file:/run/t",
|
||||||
|
"yaais.password": "<redacted>",
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Values = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type inlineBase struct {
|
||||||
|
Enabled bool `yaml:"enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKnownKey(t *testing.T) {
|
||||||
|
type cfg struct {
|
||||||
|
Throttle struct {
|
||||||
|
inlineBase `yaml:",inline"`
|
||||||
|
Window string `yaml:"window"`
|
||||||
|
} `yaml:"throttle"`
|
||||||
|
Listen []struct {
|
||||||
|
Address string `yaml:"address"`
|
||||||
|
} `yaml:"listen"`
|
||||||
|
Backends map[string]struct{ Root string } `yaml:"backends"`
|
||||||
|
Custom selfDecoding `yaml:"custom"`
|
||||||
|
}
|
||||||
|
for key, want := range map[string]bool{
|
||||||
|
"throttle.enabled": true,
|
||||||
|
"throttle.window": true,
|
||||||
|
"throttle.nope": false,
|
||||||
|
"listen[0].address": true,
|
||||||
|
"listen[].address": true,
|
||||||
|
"backends.any.root": true,
|
||||||
|
"backends.any.nope": false,
|
||||||
|
"custom.anything": true,
|
||||||
|
"missing": false,
|
||||||
|
} {
|
||||||
|
if got := KnownKey(cfg{}, key); got != want {
|
||||||
|
t.Errorf("KnownKey(%q) = %v, want %v", key, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func statExistsForTest(path string) bool {
|
||||||
|
_, err := os.Stat(path)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Value is one leaf of a merged configuration, as "config show" reports
|
||||||
|
// it.
|
||||||
|
type Value struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Value any `json:"value"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
// Used reports whether the program reads this option; an option in a
|
||||||
|
// shared file that only other programs read has Used false.
|
||||||
|
Used bool `json:"used"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultOrigin is the origin of a leaf no layer set (a value a loader
|
||||||
|
// filled in).
|
||||||
|
const DefaultOrigin = "default"
|
||||||
|
|
||||||
|
// Values returns every leaf of e, sorted by key, with its origin.
|
||||||
|
// used reports whether the program reads a key (nil: every key); a
|
||||||
|
// default it does not read is left out. Secret values (keys secrets,
|
||||||
|
// secret, token, password) are replaced by "<redacted>" unless
|
||||||
|
// showSecrets; a reference that only says where a secret is (env:,
|
||||||
|
// file:, secret://) is shown.
|
||||||
|
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
|
||||||
|
var out []Value
|
||||||
|
walkLeaves("", e.Merged, func(key string, v any) {
|
||||||
|
source := e.Origins[key]
|
||||||
|
if source == "" {
|
||||||
|
source = DefaultOrigin
|
||||||
|
}
|
||||||
|
u := used == nil || used(key)
|
||||||
|
if !u && source == DefaultOrigin {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !showSecrets && isSecretKey(key) {
|
||||||
|
v = redact(v)
|
||||||
|
}
|
||||||
|
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show writes the merged configuration: indented YAML with every
|
||||||
|
// value's origin as a comment, or with asJSON a JSON array of Values.
|
||||||
|
func (e *Effective) Show(w io.Writer, used func(string) bool, asJSON, showSecrets bool) error {
|
||||||
|
values := e.Values(used, showSecrets)
|
||||||
|
if asJSON {
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(values)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "# %s: effective configuration\n# layers, lowest priority first: %s\n", e.Name, e.Describe())
|
||||||
|
var printed []string // the parent path last printed, by depth
|
||||||
|
for _, v := range values {
|
||||||
|
parts := strings.Split(v.Key, ".")
|
||||||
|
for depth, name := range parts[:len(parts)-1] {
|
||||||
|
if depth < len(printed) && printed[depth] == name {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
printed = append(printed[:depth], name)
|
||||||
|
fmt.Fprintf(w, "%s%s:\n", strings.Repeat(" ", depth), name)
|
||||||
|
}
|
||||||
|
printed = printed[:len(parts)-1]
|
||||||
|
line := fmt.Sprintf("%s%s: %s", strings.Repeat(" ", len(parts)-1), parts[len(parts)-1], renderValue(v.Value))
|
||||||
|
note := v.Source
|
||||||
|
if !v.Used {
|
||||||
|
note += ", not used by " + e.Name
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "%s%s# %s\n", line, strings.Repeat(" ", max(44-len(line), 1)), note)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func walkLeaves(prefix string, m map[string]any, fn func(string, any)) {
|
||||||
|
keys := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
key := k
|
||||||
|
if prefix != "" {
|
||||||
|
key = prefix + "." + k
|
||||||
|
}
|
||||||
|
if sub, ok := m[k].(map[string]any); ok && len(sub) > 0 {
|
||||||
|
walkLeaves(key, sub, fn)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fn(key, m[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderValue formats a leaf as a single-line YAML value (JSON is a subset
|
||||||
|
// of YAML's flow style).
|
||||||
|
func renderValue(v any) string {
|
||||||
|
var b strings.Builder
|
||||||
|
enc := json.NewEncoder(&b)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
if err := enc.Encode(v); err != nil {
|
||||||
|
return fmt.Sprint(v)
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(b.String(), "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true, "password": true}
|
||||||
|
|
||||||
|
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
|
||||||
|
|
||||||
|
// redact replaces secret values, keeping references that only say where
|
||||||
|
// the secret is.
|
||||||
|
func redact(v any) any {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case string:
|
||||||
|
for _, ref := range []string{"env:", "file:", "secret://"} {
|
||||||
|
if strings.HasPrefix(x, ref) {
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "<redacted>"
|
||||||
|
case []any:
|
||||||
|
out := make([]any, len(x))
|
||||||
|
for i, e := range x {
|
||||||
|
out[i] = redact(e)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
return "<redacted>"
|
||||||
|
}
|
||||||
|
|
||||||
|
// listIndex matches the "[n]" (or "[]") of a list entry in a dotted key.
|
||||||
|
var listIndex = regexp.MustCompile(`\[\d*\]`)
|
||||||
|
|
||||||
|
// KnownKey reports whether the dotted option key ("storage.inbound.root",
|
||||||
|
// "listen[0].address") exists in schema (a configuration struct) by its
|
||||||
|
// yaml tags. A map accepts any key; a list, an interface or a type that
|
||||||
|
// decodes itself accepts everything below it; an embedded ",inline"
|
||||||
|
// struct contributes its fields.
|
||||||
|
func KnownKey(schema any, key string) bool {
|
||||||
|
if schema == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return knownPath(reflect.TypeOf(schema), strings.Split(listIndex.ReplaceAllString(key, ""), "."))
|
||||||
|
}
|
||||||
|
|
||||||
|
func knownPath(t reflect.Type, path []string) bool {
|
||||||
|
t = deref(t)
|
||||||
|
if len(path) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch t.Kind() {
|
||||||
|
case reflect.Struct:
|
||||||
|
ft, ok := fieldType(t, path[0])
|
||||||
|
return ok && knownPath(ft, path[1:])
|
||||||
|
case reflect.Map:
|
||||||
|
return knownPath(t.Elem(), path[1:])
|
||||||
|
case reflect.Interface, reflect.Slice, reflect.Array:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
+21
-1
@@ -19,9 +19,17 @@ type UnknownKey struct {
|
|||||||
// entries of a list are "listen[1].tls".
|
// entries of a list are "listen[1].tls".
|
||||||
Key string
|
Key string
|
||||||
Line int
|
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
|
// UnknownKeys lists the keys of raw that schema (the program's
|
||||||
// configuration struct, e.g. config.Config{}) has no field for, by its
|
// 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
|
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.
|
// UnknownKeysFile is UnknownKeys for the file at path.
|
||||||
func UnknownKeysFile(path string, schema any) ([]UnknownKey, error) {
|
func UnknownKeysFile(path string, schema any) ([]UnknownKey, error) {
|
||||||
raw, err := os.ReadFile(path)
|
raw, err := os.ReadFile(path)
|
||||||
|
|||||||
@@ -74,12 +74,12 @@ Ignored: x
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
want := []UnknownKey{
|
want := []UnknownKey{
|
||||||
{"log-levle", 2},
|
{Key: "log-levle", Line: 2},
|
||||||
{"listen[0].tsl", 5},
|
{Key: "listen[0].tsl", Line: 5},
|
||||||
{"storage.mailstore.rot", 9},
|
{Key: "storage.mailstore.rot", Line: 9},
|
||||||
{"backends.inbound.extra", 11},
|
{Key: "backends.inbound.extra", Line: 11},
|
||||||
{"throttle.enabeld", 15},
|
{Key: "throttle.enabeld", Line: 15},
|
||||||
{"Ignored", 18},
|
{Key: "Ignored", Line: 18},
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(got, want) {
|
if !reflect.DeepEqual(got, want) {
|
||||||
t.Fatalf("UnknownKeys =\n%v\nwant\n%v", 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)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# yetano.dev/yetano/core/tui
|
||||||
|
|
||||||
|
The shared kernel of the Yetano terminal UIs, on Charm v2
|
||||||
|
(`charm.land/lipgloss/v2`). It is the code that yet's TUI
|
||||||
|
(`yet/internal/tui`), yavebu's TUI (`yavebu/internal/tui`) and yalsh's
|
||||||
|
menuconfig (`yalsh/cli/internal/menuconfig`) each carried as a hand-kept
|
||||||
|
copy -- and that had already started to drift (yavebu's slate theme kept
|
||||||
|
two blue-tinted greys that render dark blue without truecolor; yet and
|
||||||
|
yavebu kept an older, truecolor-only `paint`).
|
||||||
|
|
||||||
|
```text
|
||||||
|
module yetano.dev/yetano/core/tui tags: tui/v0.1.0, ... go 1.25
|
||||||
|
```
|
||||||
|
|
||||||
|
A nested module of the core repository, like `core/gui`, so the main core
|
||||||
|
module stays free of Charm. Depends only on lipgloss v2 (and
|
||||||
|
`colorprofile` in tests); no bubbletea, no bubbles.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/tui@tui/v0.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| `Theme`, `ThemeByName(name)`, `ThemeNames`, `ValidTheme`, `NormalizeThemeName`, `NextThemeName` | the three themes `slate` (default), `dialog`, `midnight`; F2 cycles them |
|
||||||
|
| `Theme.Styles() Styles` | the 21 lipgloss styles (Root, Header, Info, Panel, PanelAlt, ListItem, ListSelected, Search, Footer, Key, Value, ...) |
|
||||||
|
| `Paint(block, fg, bg, width)` | re-grounds a pre-styled block on its area's colors after every SGR reset and pads each line (menuconfig's profile-aware version) |
|
||||||
|
| `Outer(style, w, h)` | sizes a style so the rendered block, border and padding included, is exactly w x h |
|
||||||
|
| `ListState{Filtered, Cursor, Scroll}` with `Rebuild`, `Move`, `ClampScroll`, `Index` | filtered list with cursor and scroll window |
|
||||||
|
| `Truncate`, `TruncateBlock`, `WrapStyled`, `KeyValue`, `FirstNonEmpty` | text helpers; `Truncate` counts runes, not cells (unchanged behavior) |
|
||||||
|
|
||||||
|
The values are byte-identical to yet's `theme.go` (= menuconfig's). The
|
||||||
|
exported names are the former unexported ones capitalized; `listState`
|
||||||
|
fields are exported (`filtered` -> `Filtered`, ...).
|
||||||
|
|
||||||
|
## Not in the kernel (yet)
|
||||||
|
|
||||||
|
- The app frame (`render()`: header, info bar, list + detail, search,
|
||||||
|
footer): yet, yavebu and menuconfig share the structure, not the code
|
||||||
|
(minimum sizes, width ratios, stacking differ). A `Frame` helper is the
|
||||||
|
natural next step once a third v2 program needs it.
|
||||||
|
- Menus/dialogs, task logs, terminal hand-over (`tea.Exec`), yet's
|
||||||
|
Markdown renderer and manual view: each exists in one program only.
|
||||||
|
- Standard screens for `manual`/`doctor`/`version`: only yet has a manual
|
||||||
|
view; it belongs here once a second program wants it (it would build on
|
||||||
|
the JSON form of `core/manual`).
|
||||||
|
- yamc (Charm v1, its own Midnight-Commander palette and layout) and yaki
|
||||||
|
(no TUI yet) are not consumers.
|
||||||
|
|
||||||
|
## Migration (per program, when it is next touched)
|
||||||
|
|
||||||
|
**yet** (`internal/tui`):
|
||||||
|
|
||||||
|
1. `go get yetano.dev/yetano/core/tui@tui/v0.1.0`.
|
||||||
|
2. Delete `theme.go` (keep the package comment elsewhere), `list.go`,
|
||||||
|
`paint`/`outer`/`truncate`/`truncateBlock`/`wrapStyled`/`keyValue`/
|
||||||
|
`firstNonEmpty` in `view.go`, `ThemeNames`/`ValidTheme` in `app.go`
|
||||||
|
(re-export `ThemeNames = coretui.ThemeNames` if the CLI uses it).
|
||||||
|
3. Rename call sites: `themeByName` -> `coretui.ThemeByName`,
|
||||||
|
`theme.styles()` -> `theme.Styles()`, `paint` -> `coretui.Paint`,
|
||||||
|
`listState` -> `coretui.ListState` (`.filtered/.cursor/.scroll` ->
|
||||||
|
`.Filtered/.Cursor/.Scroll`, methods capitalized), and so on.
|
||||||
|
4. Move `theme_test.go` away (it lives here now). `go test ./...`, then
|
||||||
|
look at `yet tui` in Apple Terminal (no truecolor) and a truecolor
|
||||||
|
terminal. `Paint` now emits lipgloss's own sequence, which Bubble Tea
|
||||||
|
downsamples -- the visible change is that slate stays grey on
|
||||||
|
256-color terminals.
|
||||||
|
|
||||||
|
**yavebu** (`internal/tui`): same steps for `theme.go`, `util.go`
|
||||||
|
(`listState`, `paint`, `outer`, `truncate*`, `wrapStyled`, `keyValue`,
|
||||||
|
`firstNonEmpty`) and `ThemeNames`/`ValidTheme` in `tui.go`. Intended
|
||||||
|
visible change: slate `Panel` `#2A2D33` -> `#2A2A2E` and `SelectedText`
|
||||||
|
`#202734` -> `#20242B` (the grey fix yet already has).
|
||||||
|
|
||||||
|
**yalsh menuconfig**: identical code; whether a `yalsh.dev` program
|
||||||
|
imports a `yetano.dev` module is an owner decision -- until then it stays
|
||||||
|
a copy.
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
module yetano.dev/yetano/core/tui
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
charm.land/lipgloss/v2 v2.0.6
|
||||||
|
github.com/charmbracelet/colorprofile v0.4.3
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
|
||||||
|
github.com/charmbracelet/x/ansi v0.11.8 // indirect
|
||||||
|
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||||
|
github.com/charmbracelet/x/termios v0.1.1 // indirect
|
||||||
|
github.com/charmbracelet/x/windows v0.2.2 // indirect
|
||||||
|
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||||
|
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.24 // indirect
|
||||||
|
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||||
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||||
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
)
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
||||||
|
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
|
||||||
|
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
|
||||||
|
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
|
||||||
|
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA=
|
||||||
|
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro=
|
||||||
|
github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ=
|
||||||
|
github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0=
|
||||||
|
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||||
|
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
||||||
|
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
|
||||||
|
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
|
||||||
|
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
|
||||||
|
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
|
||||||
|
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
|
||||||
|
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
|
||||||
|
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
|
||||||
|
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||||
|
github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=
|
||||||
|
github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||||
|
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||||
|
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||||
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||||
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||||
|
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||||
|
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||||
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
// ListState is the filtered/cursor/scroll state of a list view: Filtered
|
||||||
|
// holds indexes into the view's own item slice.
|
||||||
|
type ListState struct {
|
||||||
|
Filtered []int
|
||||||
|
Cursor int
|
||||||
|
Scroll int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuild filters the n items with match and keeps the cursor in range.
|
||||||
|
func (l *ListState) Rebuild(n int, match func(i int) bool) {
|
||||||
|
l.Filtered = l.Filtered[:0]
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
if match(i) {
|
||||||
|
l.Filtered = append(l.Filtered, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if l.Cursor >= len(l.Filtered) {
|
||||||
|
l.Cursor = max(0, len(l.Filtered)-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move moves the cursor by delta, clamped to the filtered items.
|
||||||
|
func (l *ListState) Move(delta int) {
|
||||||
|
l.Cursor += delta
|
||||||
|
if l.Cursor >= len(l.Filtered) {
|
||||||
|
l.Cursor = len(l.Filtered) - 1
|
||||||
|
}
|
||||||
|
if l.Cursor < 0 {
|
||||||
|
l.Cursor = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClampScroll scrolls so the cursor is visible in a window of rows lines.
|
||||||
|
func (l *ListState) ClampScroll(rows int) {
|
||||||
|
if l.Cursor < l.Scroll {
|
||||||
|
l.Scroll = l.Cursor
|
||||||
|
}
|
||||||
|
if l.Cursor >= l.Scroll+rows {
|
||||||
|
l.Scroll = l.Cursor - rows + 1
|
||||||
|
}
|
||||||
|
if l.Scroll < 0 {
|
||||||
|
l.Scroll = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Index is the item index under the cursor, or -1.
|
||||||
|
func (l ListState) Index() int {
|
||||||
|
if l.Cursor < 0 || l.Cursor >= len(l.Filtered) {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return l.Filtered[l.Cursor]
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"charm.land/lipgloss/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Paint grounds a pre-styled block on its area's colors: lipgloss ends
|
||||||
|
// every styled segment with a full SGR reset, which also drops the
|
||||||
|
// enclosing area's background and foreground, so the rest of that line
|
||||||
|
// (JoinVertical/Width padding, the gap between panels, unstyled borders,
|
||||||
|
// plain text after a styled label) would fall back to the terminal's own
|
||||||
|
// colors -- black background, and white or bold-yellow text that is
|
||||||
|
// unreadable on a light header. Paint re-applies fg/bg after every reset
|
||||||
|
// and pads each line to width with them. The sequence comes from lipgloss
|
||||||
|
// itself; Bubble Tea downsamples it to the terminal's color profile.
|
||||||
|
//
|
||||||
|
// This is menuconfig's version; yet's and yavebu's copies hard-coded a
|
||||||
|
// truecolor sequence instead.
|
||||||
|
func Paint(block string, fg, bg color.Color, width int) string {
|
||||||
|
set, _, _ := strings.Cut(lipgloss.NewStyle().Foreground(fg).Background(bg).Render("x"), "x")
|
||||||
|
lines := strings.Split(block, "\n")
|
||||||
|
for i, line := range lines {
|
||||||
|
if set != "" {
|
||||||
|
line = strings.ReplaceAll(line, "\x1b[0m", "\x1b[m")
|
||||||
|
line = strings.ReplaceAll(line, "\x1b[m", "\x1b[m"+set)
|
||||||
|
}
|
||||||
|
if pad := width - lipgloss.Width(line); pad > 0 {
|
||||||
|
line += strings.Repeat(" ", pad)
|
||||||
|
}
|
||||||
|
if set != "" {
|
||||||
|
line = set + line + "\x1b[m"
|
||||||
|
}
|
||||||
|
lines[i] = line
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outer sizes style so its rendered block, border and padding included,
|
||||||
|
// is exactly width x height cells (height 0: natural height).
|
||||||
|
func Outer(style lipgloss.Style, width, height int) lipgloss.Style {
|
||||||
|
style = style.Width(width).MaxWidth(width)
|
||||||
|
if height > 0 {
|
||||||
|
style = style.Height(height).MaxHeight(height)
|
||||||
|
}
|
||||||
|
return style
|
||||||
|
}
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"charm.land/lipgloss/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Truncate cuts text to width with a trailing "..." (width > 3).
|
||||||
|
// It counts runes, not terminal cells: wide (CJK, emoji) characters can
|
||||||
|
// still overflow -- the behavior the programs had; a cell-aware version
|
||||||
|
// would be a deliberate, tested change.
|
||||||
|
func Truncate(text string, width int) string {
|
||||||
|
if width <= 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
runes := []rune(text)
|
||||||
|
if len(runes) <= width {
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
if width <= 3 {
|
||||||
|
return string(runes[:width])
|
||||||
|
}
|
||||||
|
return string(runes[:width-3]) + "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
// TruncateBlock truncates every line of text to width.
|
||||||
|
func TruncateBlock(text string, width int) string {
|
||||||
|
lines := strings.Split(text, "\n")
|
||||||
|
for i, line := range lines {
|
||||||
|
lines[i] = Truncate(line, width)
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// WrapStyled wraps text to width and renders each line with style.
|
||||||
|
func WrapStyled(text string, width int, style lipgloss.Style) []string {
|
||||||
|
if strings.TrimSpace(text) == "" {
|
||||||
|
return []string{style.Render("")}
|
||||||
|
}
|
||||||
|
wrapped := lipgloss.NewStyle().Width(width).Render(text)
|
||||||
|
lines := strings.Split(wrapped, "\n")
|
||||||
|
for i, line := range lines {
|
||||||
|
lines[i] = style.Render(line)
|
||||||
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyValue returns a renderer for "key: value" lines of at most width
|
||||||
|
// cells, the value truncated.
|
||||||
|
func KeyValue(width int, styles Styles) func(k, v string) string {
|
||||||
|
return func(k, v string) string {
|
||||||
|
label := k + ": "
|
||||||
|
return styles.Key.Render(label) + styles.Value.Render(Truncate(v, width-lipgloss.Width(label)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirstNonEmpty returns the first non-empty value, or "".
|
||||||
|
func FirstNonEmpty(values ...string) string {
|
||||||
|
for _, v := range values {
|
||||||
|
if v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
+237
@@ -0,0 +1,237 @@
|
|||||||
|
// Package tui is the shared kernel of the Yetano terminal UIs (Charm v2):
|
||||||
|
// the three color themes and their lipgloss styles, the paint/outer layout
|
||||||
|
// helpers, the filtered list state and the text helpers that yet's TUI,
|
||||||
|
// yavebu's TUI and yalsh's menuconfig each carried as a hand-kept copy.
|
||||||
|
// It deliberately holds no app shell, menus or screens -- those still
|
||||||
|
// differ per program (see README.md).
|
||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
|
||||||
|
"charm.land/lipgloss/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Theme is one color scheme; every surface of a Yetano TUI takes its colors
|
||||||
|
// from these roles.
|
||||||
|
type Theme struct {
|
||||||
|
Name string
|
||||||
|
Background color.Color
|
||||||
|
Panel color.Color
|
||||||
|
PanelAlt color.Color
|
||||||
|
PanelBorder color.Color
|
||||||
|
Text color.Color
|
||||||
|
Muted color.Color
|
||||||
|
Accent color.Color
|
||||||
|
AccentText color.Color
|
||||||
|
Selected color.Color
|
||||||
|
SelectedText color.Color
|
||||||
|
Success color.Color
|
||||||
|
Warning color.Color
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styles are the lipgloss styles derived from a Theme.
|
||||||
|
type Styles struct {
|
||||||
|
Root lipgloss.Style
|
||||||
|
Header lipgloss.Style
|
||||||
|
HeaderTitle lipgloss.Style
|
||||||
|
HeaderMeta lipgloss.Style
|
||||||
|
Info lipgloss.Style
|
||||||
|
Panel lipgloss.Style
|
||||||
|
PanelAlt lipgloss.Style
|
||||||
|
PanelTitle lipgloss.Style
|
||||||
|
ListItem lipgloss.Style
|
||||||
|
ListEnabled lipgloss.Style
|
||||||
|
ListSelected lipgloss.Style
|
||||||
|
Search lipgloss.Style
|
||||||
|
SearchLabel lipgloss.Style
|
||||||
|
SearchInput lipgloss.Style
|
||||||
|
Footer lipgloss.Style
|
||||||
|
Key lipgloss.Style
|
||||||
|
Value lipgloss.Style
|
||||||
|
Text lipgloss.Style
|
||||||
|
Subtle lipgloss.Style
|
||||||
|
Warning lipgloss.Style
|
||||||
|
Empty lipgloss.Style
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeThemeName maps "" and "default" (and anything unknown) to
|
||||||
|
// "slate"; known names stay.
|
||||||
|
func NormalizeThemeName(name string) string {
|
||||||
|
switch name {
|
||||||
|
case "", "default":
|
||||||
|
return "slate"
|
||||||
|
case "slate", "dialog", "midnight":
|
||||||
|
return name
|
||||||
|
default:
|
||||||
|
return "slate"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NextThemeName is the theme after current in the cycle slate -> dialog ->
|
||||||
|
// midnight -> slate (the F2 key).
|
||||||
|
func NextThemeName(current string) string {
|
||||||
|
switch NormalizeThemeName(current) {
|
||||||
|
case "slate":
|
||||||
|
return "dialog"
|
||||||
|
case "dialog":
|
||||||
|
return "midnight"
|
||||||
|
default:
|
||||||
|
return "slate"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ThemeByName returns the named theme (see NormalizeThemeName).
|
||||||
|
func ThemeByName(name string) Theme {
|
||||||
|
switch NormalizeThemeName(name) {
|
||||||
|
case "dialog":
|
||||||
|
return Theme{
|
||||||
|
Name: "dialog",
|
||||||
|
Background: lipgloss.Color("#1B2D70"),
|
||||||
|
Panel: lipgloss.Color("#3552A5"),
|
||||||
|
PanelAlt: lipgloss.Color("#2E4A95"),
|
||||||
|
PanelBorder: lipgloss.Color("#AFC6FF"),
|
||||||
|
Text: lipgloss.Color("#F6F8FF"),
|
||||||
|
Muted: lipgloss.Color("#D9E2FF"),
|
||||||
|
Accent: lipgloss.Color("#EDF3FF"),
|
||||||
|
AccentText: lipgloss.Color("#12307A"),
|
||||||
|
Selected: lipgloss.Color("#FFF2A8"),
|
||||||
|
SelectedText: lipgloss.Color("#1B2450"),
|
||||||
|
Success: lipgloss.Color("#C2FFD1"),
|
||||||
|
Warning: lipgloss.Color("#FFE08A"),
|
||||||
|
}
|
||||||
|
case "midnight":
|
||||||
|
return Theme{
|
||||||
|
Name: "midnight",
|
||||||
|
Background: lipgloss.Color("#0B1020"),
|
||||||
|
Panel: lipgloss.Color("#102341"),
|
||||||
|
PanelAlt: lipgloss.Color("#17315A"),
|
||||||
|
PanelBorder: lipgloss.Color("#4C89C8"),
|
||||||
|
Text: lipgloss.Color("#EAF6FF"),
|
||||||
|
Muted: lipgloss.Color("#B6CEE4"),
|
||||||
|
Accent: lipgloss.Color("#FFD166"),
|
||||||
|
AccentText: lipgloss.Color("#12233C"),
|
||||||
|
Selected: lipgloss.Color("#64C7FF"),
|
||||||
|
SelectedText: lipgloss.Color("#0C1D33"),
|
||||||
|
Success: lipgloss.Color("#95E6B0"),
|
||||||
|
Warning: lipgloss.Color("#FFC857"),
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return Theme{
|
||||||
|
Name: "slate",
|
||||||
|
Background: lipgloss.Color("#1D1F24"),
|
||||||
|
Panel: lipgloss.Color("#2A2A2E"),
|
||||||
|
PanelAlt: lipgloss.Color("#343840"),
|
||||||
|
PanelBorder: lipgloss.Color("#6F7683"),
|
||||||
|
Text: lipgloss.Color("#F2F3F5"),
|
||||||
|
Muted: lipgloss.Color("#C5CAD3"),
|
||||||
|
Accent: lipgloss.Color("#BDC7D8"),
|
||||||
|
AccentText: lipgloss.Color("#1D232F"),
|
||||||
|
Selected: lipgloss.Color("#E7EDF7"),
|
||||||
|
SelectedText: lipgloss.Color("#20242B"),
|
||||||
|
Success: lipgloss.Color("#B5E48C"),
|
||||||
|
Warning: lipgloss.Color("#FFD27D"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styles derives the lipgloss styles of t.
|
||||||
|
func (t Theme) Styles() Styles {
|
||||||
|
return Styles{
|
||||||
|
Root: lipgloss.NewStyle().
|
||||||
|
Background(t.Background).
|
||||||
|
Foreground(t.Text).
|
||||||
|
Padding(1, 2),
|
||||||
|
Header: lipgloss.NewStyle().
|
||||||
|
Background(t.Accent).
|
||||||
|
Foreground(t.AccentText).
|
||||||
|
Bold(true).
|
||||||
|
Padding(0, 1),
|
||||||
|
HeaderTitle: lipgloss.NewStyle().
|
||||||
|
Background(t.Accent).
|
||||||
|
Foreground(t.AccentText).
|
||||||
|
Bold(true).
|
||||||
|
MarginRight(2),
|
||||||
|
HeaderMeta: lipgloss.NewStyle().
|
||||||
|
Background(t.Accent).
|
||||||
|
Foreground(t.AccentText),
|
||||||
|
Info: lipgloss.NewStyle().
|
||||||
|
Background(t.PanelAlt).
|
||||||
|
Foreground(t.Muted).
|
||||||
|
Padding(0, 1),
|
||||||
|
Panel: lipgloss.NewStyle().
|
||||||
|
Background(t.Panel).
|
||||||
|
Foreground(t.Text).
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(t.PanelBorder).
|
||||||
|
Padding(1, 1),
|
||||||
|
PanelAlt: lipgloss.NewStyle().
|
||||||
|
Background(t.PanelAlt).
|
||||||
|
Foreground(t.Text).
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(t.PanelBorder).
|
||||||
|
Padding(1, 1),
|
||||||
|
PanelTitle: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Accent).
|
||||||
|
Bold(true).
|
||||||
|
MarginBottom(1),
|
||||||
|
ListItem: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Text).
|
||||||
|
Padding(0, 1),
|
||||||
|
ListEnabled: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Success).
|
||||||
|
Padding(0, 1),
|
||||||
|
ListSelected: lipgloss.NewStyle().
|
||||||
|
Background(t.Selected).
|
||||||
|
Foreground(t.SelectedText).
|
||||||
|
Bold(true).
|
||||||
|
Padding(0, 1),
|
||||||
|
Search: lipgloss.NewStyle().
|
||||||
|
Background(t.Panel).
|
||||||
|
Foreground(t.Text).
|
||||||
|
Border(lipgloss.NormalBorder()).
|
||||||
|
BorderForeground(t.PanelBorder).
|
||||||
|
Padding(0, 1),
|
||||||
|
SearchLabel: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Accent).
|
||||||
|
Bold(true),
|
||||||
|
SearchInput: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Text),
|
||||||
|
Footer: lipgloss.NewStyle().
|
||||||
|
Background(t.PanelAlt).
|
||||||
|
Foreground(t.Muted).
|
||||||
|
Padding(0, 1),
|
||||||
|
Key: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Accent).
|
||||||
|
Bold(true),
|
||||||
|
Value: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Text),
|
||||||
|
Text: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Text),
|
||||||
|
Subtle: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Muted).
|
||||||
|
Bold(true),
|
||||||
|
Warning: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Warning).
|
||||||
|
Bold(true),
|
||||||
|
Empty: lipgloss.NewStyle().
|
||||||
|
Foreground(t.Muted).
|
||||||
|
Italic(true),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ThemeNames lists the accepted --theme values.
|
||||||
|
var ThemeNames = []string{"slate", "dialog", "midnight"}
|
||||||
|
|
||||||
|
// ValidTheme reports whether name is one of ThemeNames (or empty).
|
||||||
|
func ValidTheme(name string) bool {
|
||||||
|
if name == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, n := range ThemeNames {
|
||||||
|
if n == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"image/color"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"charm.land/lipgloss/v2"
|
||||||
|
"github.com/charmbracelet/colorprofile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSlateDarkColorsStayGreyWithoutTruecolor guards the slate theme's
|
||||||
|
// dark surfaces against a terminal without truecolor (no COLORTERM, e.g.
|
||||||
|
// Apple Terminal, ssh, tmux without Tc): bubbletea then downsamples every
|
||||||
|
// color to the 256-color palette, and a dark grey with a slight blue tint
|
||||||
|
// (#2A2D33 for Panel did) lands on index 17, #00005F -- painting the list
|
||||||
|
// panel and search bar dark blue. Each of these must map to a grey.
|
||||||
|
func TestSlateDarkColorsStayGreyWithoutTruecolor(t *testing.T) {
|
||||||
|
th := ThemeByName("slate")
|
||||||
|
for name, c := range map[string]color.Color{
|
||||||
|
"Background": th.Background,
|
||||||
|
"Panel": th.Panel,
|
||||||
|
"PanelAlt": th.PanelAlt,
|
||||||
|
"AccentText": th.AccentText,
|
||||||
|
"SelectedText": th.SelectedText,
|
||||||
|
} {
|
||||||
|
got := colorprofile.ANSI256.Convert(c)
|
||||||
|
r, g, b, _ := got.RGBA()
|
||||||
|
if r != g || g != b {
|
||||||
|
t.Errorf("slate %s converts to non-grey 256-color %v (#%02x%02x%02x)", name, got, r>>8, g>>8, b>>8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestThemeNames(t *testing.T) {
|
||||||
|
for in, want := range map[string]string{"": "slate", "default": "slate", "bogus": "slate", "dialog": "dialog", "midnight": "midnight"} {
|
||||||
|
if got := NormalizeThemeName(in); got != want {
|
||||||
|
t.Errorf("NormalizeThemeName(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
if got := ThemeByName(in).Name; got != want {
|
||||||
|
t.Errorf("ThemeByName(%q).Name = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name := "slate"
|
||||||
|
for i, want := range []string{"dialog", "midnight", "slate"} {
|
||||||
|
name = NextThemeName(name)
|
||||||
|
if name != want {
|
||||||
|
t.Fatalf("cycle step %d = %q, want %q", i, name, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, n := range append([]string{""}, ThemeNames...) {
|
||||||
|
if !ValidTheme(n) {
|
||||||
|
t.Errorf("ValidTheme(%q) = false", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ValidTheme("default") || ValidTheme("x") {
|
||||||
|
t.Error("ValidTheme accepts a name outside ThemeNames")
|
||||||
|
}
|
||||||
|
_ = ThemeByName("dialog").Styles() // must not panic
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListState(t *testing.T) {
|
||||||
|
var l ListState
|
||||||
|
if l.Index() != -1 {
|
||||||
|
t.Fatal("empty list must have Index -1")
|
||||||
|
}
|
||||||
|
l.Rebuild(10, func(i int) bool { return i%2 == 0 }) // 0 2 4 6 8
|
||||||
|
l.Move(3)
|
||||||
|
if l.Index() != 6 {
|
||||||
|
t.Fatalf("Index = %d, want 6", l.Index())
|
||||||
|
}
|
||||||
|
l.Move(100)
|
||||||
|
if l.Cursor != 4 || l.Index() != 8 {
|
||||||
|
t.Fatalf("Move past end: cursor %d index %d", l.Cursor, l.Index())
|
||||||
|
}
|
||||||
|
l.ClampScroll(2)
|
||||||
|
if l.Scroll != 3 {
|
||||||
|
t.Fatalf("Scroll = %d, want 3", l.Scroll)
|
||||||
|
}
|
||||||
|
l.Rebuild(10, func(i int) bool { return i < 4 }) // 0 1 2 3: cursor clamps
|
||||||
|
if l.Cursor != 3 {
|
||||||
|
t.Fatalf("Rebuild must clamp cursor, got %d", l.Cursor)
|
||||||
|
}
|
||||||
|
l.Move(-100)
|
||||||
|
l.ClampScroll(2)
|
||||||
|
if l.Cursor != 0 || l.Scroll != 0 {
|
||||||
|
t.Fatalf("cursor %d scroll %d", l.Cursor, l.Scroll)
|
||||||
|
}
|
||||||
|
l.Rebuild(3, func(int) bool { return false })
|
||||||
|
if l.Cursor != 0 || l.Index() != -1 {
|
||||||
|
t.Fatal("empty filter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTextHelpers(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
in string
|
||||||
|
w int
|
||||||
|
want string
|
||||||
|
}{{"hello", 10, "hello"}, {"hello world", 8, "hello..."}, {"hello", 2, "he"}, {"hello", 0, ""}, {"äöüäöü", 5, "äö..."}}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := Truncate(c.in, c.w); got != c.want {
|
||||||
|
t.Errorf("Truncate(%q,%d) = %q, want %q", c.in, c.w, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := TruncateBlock("abcdef\nxy", 5); got != "ab...\nxy" {
|
||||||
|
t.Errorf("TruncateBlock = %q", got)
|
||||||
|
}
|
||||||
|
if got := FirstNonEmpty("", "", "b", "c"); got != "b" {
|
||||||
|
t.Errorf("FirstNonEmpty = %q", got)
|
||||||
|
}
|
||||||
|
if got := WrapStyled("one two three", 7, lipgloss.NewStyle()); len(got) != 2 {
|
||||||
|
t.Errorf("WrapStyled = %q", got)
|
||||||
|
}
|
||||||
|
if got := WrapStyled(" ", 7, lipgloss.NewStyle()); len(got) != 1 {
|
||||||
|
t.Errorf("WrapStyled blank = %q", got)
|
||||||
|
}
|
||||||
|
kv := KeyValue(12, ThemeByName("slate").Styles())("name", "a-very-long-value")
|
||||||
|
if w := lipgloss.Width(kv); w > 12 {
|
||||||
|
t.Errorf("KeyValue width %d > 12: %q", w, kv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPaintReappliesColorsAndPads(t *testing.T) {
|
||||||
|
th := ThemeByName("slate")
|
||||||
|
set, _, _ := strings.Cut(lipgloss.NewStyle().Foreground(th.Text).Background(th.Background).Render("x"), "x")
|
||||||
|
if set == "" {
|
||||||
|
t.Skip("lipgloss rendered no color sequence")
|
||||||
|
}
|
||||||
|
got := Paint("a\x1b[0mb\nc", th.Text, th.Background, 4)
|
||||||
|
lines := strings.Split(got, "\n")
|
||||||
|
if len(lines) != 2 {
|
||||||
|
t.Fatalf("lines = %q", lines)
|
||||||
|
}
|
||||||
|
if want := set + "a\x1b[m" + set + "b \x1b[m"; lines[0] != want {
|
||||||
|
t.Errorf("line 0 = %q, want %q", lines[0], want)
|
||||||
|
}
|
||||||
|
if lipgloss.Width(lines[1]) != 4 {
|
||||||
|
t.Errorf("line 1 not padded to 4: %q", lines[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOuter(t *testing.T) {
|
||||||
|
s := Outer(lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 1), 20, 5)
|
||||||
|
out := s.Render("x")
|
||||||
|
if w, h := lipgloss.Width(out), lipgloss.Height(out); w != 20 || h != 5 {
|
||||||
|
t.Errorf("Outer block %dx%d, want 20x5", w, h)
|
||||||
|
}
|
||||||
|
if h := lipgloss.Height(Outer(lipgloss.NewStyle(), 10, 0).Render("a\nb\nc")); h != 3 {
|
||||||
|
t.Errorf("height 0 must keep natural height, got %d", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user