Author SHA1 Message Date
terminarandClaude Opus 5.5 764b6f36ea backup: archives with a checksummed manifest, rotation, safe restore
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 20:41:16 +01:00
terminarandClaude Opus 5.5 71b4dda990 License: proprietary (LicenseRef-Proprietary)
Owner decision 2026-11-01: all own Yetano code is proprietary. LICENSE
carries the notice, the README says so, and the Yetanofile declares
LicenseRef-Proprietary. Bundled third-party files keep their licenses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:43:31 +01:00
terminarandClaude Opus 5.5 3d286da90d doctor: optional per-check area and hint
Check gets Area and Hint, omitted from the JSON when empty; the table
only grows an AREA or HINT column when some check uses one, so existing
reports are unchanged. Report.Add records a check with all fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:35:54 +01:00
terminarandClaude Opus 5.5 131d82642c configcmd.OneOf for alternative fields; completion.Files for paths
UndocumentedKeys reported the unused alternatives of a struct like
SecretRef (env/file/value) as undocumented; a struct implementing the
marker configcmd.OneOf now counts as documented with one alternative,
and upgrade offers none of the others to a file that chose one.

completion.Tree gets the key completion.Files: that level completes
file and directory paths besides command names (bash, zsh, fish,
PowerShell), for programs started as "<program> [path]" like yamc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:40:45 +01:00
terminarandClaude Opus 5.5 83f4228e66 LICENSE: proprietary notice instead of MIT
The Yetano projects are closed source for now (owner, 2026-10-31); the
MIT license file did not match that. All rights reserved until the
license is decided.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:27:47 +01:00
terminarandClaude Opus 5.5 c11197bb37 configfamily: one config file per program plus an optional family file
The generic part of yamase-core/pkg/configfile (yamase ADR-0074): per
tier a program merges the family file's top level, its section of the
family file and its own <program>.yaml, then --config. Includes
unknown-option rules for shared files, the config command on top of
configcmd.Layered with "create --shared", and doctor/logging helpers.
yaiam is the first user; yamase can move onto it later.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:48:52 +01:00
21 changed files with 2144 additions and 26 deletions

No files matched your search

+7
View File
@@ -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
here unchanged in behavior when the other meta-repos needed it.
`configfamily` is the layered configuration of a program family (a
family file, a section of it and a per-program file in every tier) on
top of `configcmd.Layered`. It is the generic part of
`yamase-core/pkg/configfile` (yamase ADR-0074), taken over when yaiam
split into several programs; what is specific to one family -- yamase's
data-dir and storage-role defaults -- stays in that family's code.
## core/gui: a nested module, not a package of this one
The WebView host needs cgo and Cocoa/WebKit on macOS and
+13 -7
View File
@@ -1,9 +1,15 @@
MIT License
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
Copyright (c) 2026 yetano
This software and its documentation are proprietary
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
publish, distribute, sublicense or sell copies of this software, in whole
or in part, is granted without the prior written permission of the
copyright holder.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+80 -2
View File
@@ -27,8 +27,10 @@ yetano.dev/yetano/core/manual
yetano.dev/yetano/core/completion
yetano.dev/yetano/core/doctor
yetano.dev/yetano/core/configcmd
yetano.dev/yetano/core/configfamily
yetano.dev/yetano/core/version
yetano.dev/yetano/core/secretref
yetano.dev/yetano/core/backup
yetano.dev/yetano/core/cobracmd (separate module)
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
@@ -320,11 +322,18 @@ docs/program-conventions.md in the meta-repository):
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
PowerShell completion script generated from a static `completion.Tree`
of the program's commands.
of the program's commands. A level that also takes a path (a program
without subcommands, started as `<program> [path]`) adds the key
`completion.Files`; the script then completes files and directories
there besides the command names.
- `doctor.Report` collects the locations the program resolves
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
exit code (0 all good, 1 a check failed, 2 usage).
exit code (0 all good, 1 a check failed, 2 usage). A check may carry
an `area` (a group such as "config" or "services") and a `hint` (what
to do about it), recorded with `Add(doctor.Check{...})`; both are
omitted from the JSON when empty, and the table only gets an AREA or
HINT column when some check uses it (since v0.10.0).
## core/configcmd: "<program> config"
@@ -352,6 +361,10 @@ os.Exit(configcmd.Run(spec, configFlag, args, os.Stdout, os.Stderr))
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
config.Config{})` and expect nothing, so every option stays documented
in the full template -- that is what keeps `config upgrade` useful.
A struct whose fields are alternatives (a secret from `env`, `file` or
`value`) implements the marker `configcmd.OneOf` (`func (SecretRef)
ConfigOneOf() {}`): one alternative in the template documents it, and
`upgrade` offers none of the others to a file that already chose one.
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
report options the program ignores. Taken over from
`yamase-core/pkg/configcmd`, which now wraps it.
@@ -374,6 +387,40 @@ 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`,
@@ -440,6 +487,33 @@ plain values it accepted before checks `IsReference` and treats anything
else as a literal. Used by yavebu,
yacry and yadenes.
## core/backup: "<program> backup"
The archive behind `<program> backup create|list|verify|restore` (see
docs/program-conventions.md in the meta-repository). The program
chooses the content; `core/backup` writes, lists, rotates, verifies and
unpacks:
```go
w, err := backup.Create(dir, "yanks-registry", version.Version)
w.AddFile("registry.db", snapshot) // a consistent copy, not the live file
w.AddDir("state", dataDir, skipBlobs) // regular files below a directory
w.AddFile("config/yanks-registry.yaml", cfgPath)
a, err := w.Close() // atomic: complete or nothing
removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, nil)
m, err := backup.Verify(path) // every file against MANIFEST.json
m, err := backup.Extract(path, newDir) // verified first; only below newDir
```
`<program>-<UTC time>.tar.gz`, a gzip tar with `MANIFEST.json` last
(schema, program, version, time, each file's name, size, mode and
SHA-256). Archives and their directory are owner-only (0600/0700).
`Extract` never writes over anything and never outside its destination
(`..`, absolute names and links are rejected before a byte is written).
`Prune` keeps `Keep{Last, Daily, Weekly, Monthly}` (default 3/7/4/6); an
empty `Keep` removes nothing.
## core/gui (separate module)
`yetano.dev/yetano/core/gui` is the native WebView host for desktop
@@ -458,3 +532,7 @@ pitfalls and the yet-gui migration: [gui/README.md](gui/README.md).
`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`,
`ListState` and text helpers. No app shell or screens yet -- see
[tui/README.md](tui/README.md), which also has the migration steps.
## License
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE).
+8
View File
@@ -32,6 +32,14 @@ speculatively.
- [x] `manual` (v0.2.0), `completion`, `doctor` (v0.3.0), `secretref`
(v0.4.0), `configcmd` and `version` (v0.5.0) -- see
docs/program-conventions.md in the meta-repository.
- [x] `configcmd.OneOf`: `UndocumentedKeys` and `upgrade` know structs
whose fields are alternatives (SecretRef `env`/`file`/`value`);
`completion.Files` completes paths for programs without subcommands
(yamc) -- 2026-10-31.
- [x] `backup` (v0.11.0): archive format, rotation, verify, safe
extract for the optional `<program> backup` command -- 2026-11-05.
- [x] `doctor.Check` with optional `area` and `hint` (JSON and table,
omitted when empty), `Report.Add` -- 2026-11-01, for v0.10.0.
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
- [x] `core/gui`: the native WebView host from
+525
View File
@@ -0,0 +1,525 @@
// Package backup is the archive format and handling behind the optional
// "<program> backup create|list|verify|restore" commands of the Yetano
// program standard (docs/program-conventions.md in the yetano
// meta-repository). The program decides what goes in (a consistent
// database copy, its config, state files -- never what can be fetched
// again); this package writes, lists, rotates, checks and unpacks.
//
// w, err := backup.Create(dir, "yanks-registry", version.Version)
// w.AddFile("registry.db", snapshotPath)
// w.AddFile("config/yanks-registry.yaml", cfgPath)
// a, err := w.Close() // atomic: complete or nothing
// removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, time.Now())
//
// An archive is a gzip-compressed tar named
// "<program>-<UTC time>.tar.gz": the files, then MANIFEST.json (program,
// version, time, and every file's name, size, mode and SHA-256).
// Archives and their directory are only readable by the owner -- they
// hold password hashes and keys as often as not. Extract verifies an
// archive completely before it writes anything, and only ever writes
// below its destination.
package backup
import (
"archive/tar"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// Schema is the manifest version this package writes and reads.
const Schema = 1
// ManifestName is the archive's last entry.
const ManifestName = "MANIFEST.json"
// timeLayout is the UTC time in archive names; it sorts as text.
const timeLayout = "20060102T150405Z"
// Manifest describes an archive.
type Manifest struct {
Schema int `json:"schema"`
Program string `json:"program"`
Version string `json:"version,omitempty"`
CreatedAt time.Time `json:"created_at"`
Files []File `json:"files"`
}
// File is one archived file. Name is slash-separated and relative.
type File struct {
Name string `json:"name"`
Size int64 `json:"size"`
Mode uint32 `json:"mode"`
SHA256 string `json:"sha256"`
}
// Archive is a backup file in a directory.
type Archive struct {
Path string `json:"path"`
Program string `json:"program"`
CreatedAt time.Time `json:"created_at"`
Size int64 `json:"size"`
}
// ErrInvalid: the archive is damaged, incomplete or not a backup.
var ErrInvalid = errors.New("backup: invalid archive")
func invalid(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...))
}
var (
programRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
suffixRE = regexp.MustCompile(`^-[0-9]+$`)
)
// Writer builds an archive in a temporary file next to its final name.
type Writer struct {
dir, program string
m Manifest
f *os.File
gz *gzip.Writer
tw *tar.Writer
names map[string]bool
err error
}
// Create starts an archive of program in dir (created owner-only when
// missing).
func Create(dir, program, version string) (*Writer, error) {
if !programRE.MatchString(program) {
return nil, fmt.Errorf("backup: invalid program name %q", program)
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, fmt.Errorf("backup: %w", err)
}
f, err := os.CreateTemp(dir, "."+program+"-*.partial")
if err != nil {
return nil, fmt.Errorf("backup: %w", err)
}
if err := f.Chmod(0o600); err != nil {
f.Close()
os.Remove(f.Name())
return nil, fmt.Errorf("backup: %w", err)
}
gz := gzip.NewWriter(f)
return &Writer{dir: dir, program: program, f: f, gz: gz, tw: tar.NewWriter(gz), names: map[string]bool{},
m: Manifest{Schema: Schema, Program: program, Version: version, CreatedAt: time.Now().UTC().Truncate(time.Second), Files: []File{}}}, nil
}
// validName: relative, slash-separated, clean, inside the archive.
func validName(name string) bool {
return name != "" && name != "." && name != ManifestName && !strings.HasPrefix(name, "/") &&
!strings.Contains(name, `\`) && path.Clean(name) == name && name != ".." && !strings.HasPrefix(name, "../")
}
func (w *Writer) add(name string, mode fs.FileMode, size int64, mtime time.Time, r io.Reader) error {
if w.err != nil {
return w.err
}
if !validName(name) {
return fmt.Errorf("backup: invalid name %q", name)
}
if w.names[name] {
return fmt.Errorf("backup: %s added twice", name)
}
w.names[name] = true
perm := uint32(mode.Perm())
h := &tar.Header{Name: name, Mode: int64(perm), Size: size, ModTime: mtime, Typeflag: tar.TypeReg, Format: tar.FormatPAX}
if err := w.tw.WriteHeader(h); err != nil {
w.err = fmt.Errorf("backup: %s: %w", name, err)
return w.err
}
sum := sha256.New()
n, err := io.Copy(w.tw, io.TeeReader(r, sum))
if err == nil && n != size {
err = fmt.Errorf("changed while it was read (%d of %d bytes)", n, size)
}
if err != nil {
w.err = fmt.Errorf("backup: %s: %w", name, err)
return w.err
}
w.m.Files = append(w.m.Files, File{Name: name, Size: size, Mode: perm, SHA256: hex.EncodeToString(sum.Sum(nil))})
return nil
}
// AddFile archives the regular file src as name.
func (w *Writer) AddFile(name, src string) error {
f, err := os.Open(src)
if err != nil {
return fmt.Errorf("backup: %w", err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return fmt.Errorf("backup: %w", err)
}
if !fi.Mode().IsRegular() {
return fmt.Errorf("backup: %s is not a regular file", src)
}
return w.add(name, fi.Mode(), fi.Size(), fi.ModTime(), f)
}
// AddBytes archives data as name.
func (w *Writer) AddBytes(name string, data []byte, mode fs.FileMode) error {
return w.add(name, mode, int64(len(data)), w.m.CreatedAt, strings.NewReader(string(data)))
}
// AddDir archives the regular files below src as prefix/<relative
// path>, in a stable order. skip (may be nil) leaves out a file or, for
// a directory, everything below it; rel is slash-separated. Symbolic
// links and other special files are left out.
func (w *Writer) AddDir(prefix, src string, skip func(rel string, d fs.DirEntry) bool) error {
return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("backup: %w", err)
}
rel, err := filepath.Rel(src, p)
if err != nil {
return err
}
if rel == "." {
return nil
}
rel = filepath.ToSlash(rel)
if skip != nil && skip(rel, d) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if !d.Type().IsRegular() {
return nil
}
return w.AddFile(path.Join(prefix, rel), p)
})
}
// Close finishes the archive: the manifest, then an atomic rename to
// "<program>-<time>.tar.gz". After an error the archive is removed.
func (w *Writer) Close() (Archive, error) {
if w.err != nil {
w.Abort()
return Archive{}, w.err
}
b, err := json.MarshalIndent(w.m, "", " ")
if err == nil {
err = w.tw.WriteHeader(&tar.Header{Name: ManifestName, Mode: 0o600, Size: int64(len(b)), ModTime: w.m.CreatedAt,
Typeflag: tar.TypeReg, Format: tar.FormatPAX})
}
if err == nil {
_, err = w.tw.Write(b)
}
if err == nil {
err = w.tw.Close()
}
if err == nil {
err = w.gz.Close()
}
if err == nil {
err = w.f.Sync()
}
if cerr := w.f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(w.f.Name())
return Archive{}, fmt.Errorf("backup: %w", err)
}
final, err := freeName(w.dir, w.program, w.m.CreatedAt)
if err == nil {
err = os.Rename(w.f.Name(), final)
}
if err != nil {
os.Remove(w.f.Name())
return Archive{}, fmt.Errorf("backup: %w", err)
}
fi, err := os.Stat(final)
if err != nil {
return Archive{}, fmt.Errorf("backup: %w", err)
}
return Archive{Path: final, Program: w.program, CreatedAt: w.m.CreatedAt, Size: fi.Size()}, nil
}
// Abort drops an unfinished archive.
func (w *Writer) Abort() {
w.f.Close()
os.Remove(w.f.Name())
}
func freeName(dir, program string, t time.Time) (string, error) {
base := program + "-" + t.UTC().Format(timeLayout)
for i := 1; i < 100; i++ {
name := base + ".tar.gz"
if i > 1 {
name = fmt.Sprintf("%s-%d.tar.gz", base, i)
}
p := filepath.Join(dir, name)
if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) {
return p, nil
}
}
return "", fmt.Errorf("no free archive name for %s", base)
}
// parseName reads the time and the sequence number (1, or n of "-n")
// from an archive's file name.
func parseName(name, program string) (time.Time, int, bool) {
rest, ok := strings.CutPrefix(name, program+"-")
if !ok {
return time.Time{}, 0, false
}
rest, ok = strings.CutSuffix(rest, ".tar.gz")
if !ok || len(rest) < len(timeLayout) {
return time.Time{}, 0, false
}
stamp, suffix := rest[:len(timeLayout)], rest[len(timeLayout):]
seq := 1
if suffix != "" {
if !suffixRE.MatchString(suffix) {
return time.Time{}, 0, false
}
fmt.Sscanf(suffix[1:], "%d", &seq)
}
t, err := time.Parse(timeLayout, stamp)
return t, seq, err == nil
}
// List returns program's archives in dir, newest first. A missing dir
// is no archive.
func List(dir, program string) ([]Archive, error) {
entries, err := os.ReadDir(dir)
if errors.Is(err, os.ErrNotExist) {
return []Archive{}, nil
}
if err != nil {
return nil, fmt.Errorf("backup: %w", err)
}
out := []Archive{}
seq := map[string]int{}
for _, e := range entries {
t, n, ok := parseName(e.Name(), program)
if !ok || !e.Type().IsRegular() {
continue
}
fi, err := e.Info()
if err != nil {
continue
}
p := filepath.Join(dir, e.Name())
seq[p] = n
out = append(out, Archive{Path: p, Program: program, CreatedAt: t, Size: fi.Size()})
}
sort.SliceStable(out, func(i, j int) bool {
if !out[i].CreatedAt.Equal(out[j].CreatedAt) {
return out[i].CreatedAt.After(out[j].CreatedAt)
}
return seq[out[i].Path] > seq[out[j].Path]
})
return out, nil
}
// Keep says which archives Prune keeps: the Last newest, and the newest
// of each of the last Daily days, Weekly ISO weeks and Monthly months
// that have one (local time).
type Keep struct {
Last int `json:"last" yaml:"last"`
Daily int `json:"daily" yaml:"daily"`
Weekly int `json:"weekly" yaml:"weekly"`
Monthly int `json:"monthly" yaml:"monthly"`
}
// DefaultKeep: the 3 newest, a week of days, a month of weeks, half a
// year of months.
var DefaultKeep = Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}
// Prune removes program's archives in dir that keep does not hold and
// returns them. A Keep of all zeros removes nothing (a misconfiguration
// must not delete every backup).
func Prune(dir, program string, keep Keep, loc *time.Location) ([]Archive, error) {
if keep == (Keep{}) {
return []Archive{}, nil
}
if loc == nil {
loc = time.Local
}
all, err := List(dir, program)
if err != nil {
return nil, err
}
kept := map[string]bool{}
for i := 0; i < keep.Last && i < len(all); i++ {
kept[all[i].Path] = true
}
bucket := func(n int, key func(time.Time) string) {
seen := map[string]bool{}
for _, a := range all { // newest first: the first of a bucket is its newest
k := key(a.CreatedAt.In(loc))
if seen[k] {
continue
}
if len(seen) == n {
return
}
seen[k] = true
kept[a.Path] = true
}
}
bucket(keep.Daily, func(t time.Time) string { return t.Format("2006-01-02") })
bucket(keep.Weekly, func(t time.Time) string { y, w := t.ISOWeek(); return fmt.Sprintf("%d-%02d", y, w) })
bucket(keep.Monthly, func(t time.Time) string { return t.Format("2006-01") })
removed := []Archive{}
for _, a := range all {
if kept[a.Path] {
continue
}
if err := os.Remove(a.Path); err != nil {
return removed, fmt.Errorf("backup: %w", err)
}
removed = append(removed, a)
}
return removed, nil
}
// walk reads an archive, calling fn for every file entry with its
// content; it returns the manifest after checking that it lists exactly
// the files read, with their sizes and checksums.
func walk(archive string, fn func(h *tar.Header, r io.Reader) error) (Manifest, error) {
var m Manifest
f, err := os.Open(archive)
if err != nil {
return m, fmt.Errorf("backup: %w", err)
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return m, invalid("%s: %v", filepath.Base(archive), err)
}
tr := tar.NewReader(gz)
got := map[string]File{}
haveManifest := false
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return m, invalid("%s: %v", filepath.Base(archive), err)
}
if haveManifest {
return m, invalid("an entry after the manifest: %q", h.Name)
}
if h.Name == ManifestName {
b, err := io.ReadAll(io.LimitReader(tr, 64<<20))
if err != nil {
return m, invalid("manifest: %v", err)
}
if err := json.Unmarshal(b, &m); err != nil {
return m, invalid("manifest: %v", err)
}
haveManifest = true
continue
}
if h.Typeflag != tar.TypeReg || !validName(h.Name) {
return m, invalid("unexpected entry %q", h.Name)
}
if _, dup := got[h.Name]; dup {
return m, invalid("%q twice", h.Name)
}
sum := sha256.New()
r := io.TeeReader(tr, sum)
if fn != nil {
if err := fn(h, r); err != nil {
return m, err
}
}
if _, err := io.Copy(io.Discard, r); err != nil { // what fn did not read
return m, invalid("%s: %v", h.Name, err)
}
got[h.Name] = File{Name: h.Name, Size: h.Size, SHA256: hex.EncodeToString(sum.Sum(nil))}
}
if !haveManifest {
return m, invalid("no manifest: the archive is incomplete")
}
if m.Schema != Schema {
return m, invalid("manifest schema %d, this program reads %d", m.Schema, Schema)
}
if len(m.Files) != len(got) {
return m, invalid("the manifest lists %d files, the archive holds %d", len(m.Files), len(got))
}
for _, mf := range m.Files {
g, ok := got[mf.Name]
if !ok {
return m, invalid("%s is missing", mf.Name)
}
if g.Size != mf.Size || g.SHA256 != mf.SHA256 {
return m, invalid("%s does not match its checksum", mf.Name)
}
}
return m, nil
}
// Verify reads an archive completely and checks every file against the
// manifest.
func Verify(archive string) (Manifest, error) {
return walk(archive, nil)
}
// Extract verifies the archive, then unpacks it into dest, which must
// not exist yet (its parent must): nothing is ever written over, and
// nothing outside dest. On an error dest is removed again.
func Extract(archive, dest string) (Manifest, error) {
if _, err := Verify(archive); err != nil {
return Manifest{}, err
}
if _, err := os.Lstat(dest); err == nil {
return Manifest{}, fmt.Errorf("backup: %s exists; extract into a new directory", dest)
}
if err := os.Mkdir(dest, 0o700); err != nil {
return Manifest{}, fmt.Errorf("backup: %w", err)
}
m, err := walk(archive, func(h *tar.Header, r io.Reader) error {
target := filepath.Join(dest, filepath.FromSlash(h.Name))
if rel, err := filepath.Rel(dest, target); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return invalid("%q leaves the destination", h.Name)
}
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return fmt.Errorf("backup: %w", err)
}
f, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fs.FileMode(h.Mode).Perm()|0o200)
if err != nil {
return fmt.Errorf("backup: %w", err)
}
_, err = io.Copy(f, r)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Chmod(target, fs.FileMode(h.Mode).Perm())
}
if err == nil {
err = os.Chtimes(target, h.ModTime, h.ModTime)
}
if err != nil {
return fmt.Errorf("backup: %s: %w", h.Name, err)
}
return nil
})
if err != nil {
os.RemoveAll(dest)
return Manifest{}, err
}
return m, nil
}
+241
View File
@@ -0,0 +1,241 @@
package backup
import (
"archive/tar"
"compress/gzip"
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func write(t *testing.T, p, content string, mode fs.FileMode) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), mode); err != nil {
t.Fatal(err)
}
}
func makeArchive(t *testing.T, dir string) Archive {
t.Helper()
src := t.TempDir()
write(t, filepath.Join(src, "db"), "database", 0o600)
write(t, filepath.Join(src, "state", "users.json"), `{"u":1}`, 0o600)
write(t, filepath.Join(src, "state", "repos", "a", "tags", "latest"), "sha256:x", 0o644)
write(t, filepath.Join(src, "state", "blobs", "big"), "blob", 0o644)
w, err := Create(dir, "prog", "1.2.3")
if err != nil {
t.Fatal(err)
}
if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err != nil {
t.Fatal(err)
}
if err := w.AddDir("state", filepath.Join(src, "state"), func(rel string, d fs.DirEntry) bool { return rel == "blobs" }); err != nil {
t.Fatal(err)
}
if err := w.AddBytes("config/prog.yaml", []byte("listen: x\n"), 0o640); err != nil {
t.Fatal(err)
}
if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err == nil {
t.Error("the same name added twice")
}
w.err = nil // the duplicate is the test's own doing
a, err := w.Close()
if err != nil {
t.Fatal(err)
}
return a
}
func TestRoundTrip(t *testing.T) {
dir := filepath.Join(t.TempDir(), "backups")
a := makeArchive(t, dir)
if !strings.HasPrefix(filepath.Base(a.Path), "prog-") || !strings.HasSuffix(a.Path, ".tar.gz") {
t.Errorf("archive name %s", a.Path)
}
if runtime.GOOS != "windows" {
for p, want := range map[string]fs.FileMode{dir: 0o700, a.Path: 0o600} {
if fi, _ := os.Stat(p); fi.Mode().Perm() != want {
t.Errorf("%s mode %v, want %v", p, fi.Mode().Perm(), want)
}
}
}
if left, _ := filepath.Glob(filepath.Join(dir, ".*partial")); len(left) != 0 {
t.Errorf("temporary files left: %v", left)
}
m, err := Verify(a.Path)
if err != nil {
t.Fatal(err)
}
var names []string
for _, f := range m.Files {
names = append(names, f.Name)
}
if m.Program != "prog" || m.Version != "1.2.3" ||
strings.Join(names, ",") != "db/registry.db,state/repos/a/tags/latest,state/users.json,config/prog.yaml" {
t.Errorf("manifest = %+v", m)
}
dest := filepath.Join(t.TempDir(), "restore")
if _, err := Extract(a.Path, dest); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(filepath.Join(dest, "state", "users.json"))
if string(b) != `{"u":1}` {
t.Errorf("users.json = %q", b)
}
if _, err := os.Stat(filepath.Join(dest, "state", "blobs")); !errors.Is(err, os.ErrNotExist) {
t.Error("a skipped directory was archived")
}
if runtime.GOOS != "windows" {
if fi, _ := os.Stat(filepath.Join(dest, "config", "prog.yaml")); fi.Mode().Perm() != 0o640 {
t.Errorf("restored mode %v", fi.Mode().Perm())
}
}
if _, err := Extract(a.Path, dest); err == nil {
t.Error("extracted over an existing directory")
}
}
func TestDamagedArchives(t *testing.T) {
dir := t.TempDir()
a := makeArchive(t, dir)
raw, _ := os.ReadFile(a.Path)
// Cut off: no manifest, or not even a complete gzip stream.
cut := filepath.Join(dir, "cut.tar.gz")
write(t, cut, string(raw[:len(raw)/2]), 0o600)
if _, err := Verify(cut); !errors.Is(err, ErrInvalid) {
t.Errorf("truncated archive: %v", err)
}
// A file whose content does not match the manifest.
tampered := filepath.Join(dir, "tampered.tar.gz")
writeTar(t, tampered, []entry{{"db/registry.db", "other!!!"}, {ManifestName, manifestFor(t, a.Path)}})
if _, err := Verify(tampered); !errors.Is(err, ErrInvalid) {
t.Errorf("tampered archive: %v", err)
}
// Names that leave the destination are refused before anything is
// written.
for _, name := range []string{"../evil", "/etc/evil", "a/../../evil", `a\..\evil`} {
evil := filepath.Join(dir, "evil.tar.gz")
writeTar(t, evil, []entry{{name, "x"}, {ManifestName, `{"schema":1,"program":"prog","files":[]}`}})
dest := filepath.Join(t.TempDir(), "d")
if _, err := Extract(evil, dest); !errors.Is(err, ErrInvalid) {
t.Errorf("%q: %v", name, err)
}
if _, err := os.Stat(dest); !errors.Is(err, os.ErrNotExist) {
t.Errorf("%q: destination created", name)
}
}
}
type entry struct{ name, content string }
func writeTar(t *testing.T, p string, entries []entry) {
t.Helper()
f, err := os.Create(p)
if err != nil {
t.Fatal(err)
}
gz := gzip.NewWriter(f)
tw := tar.NewWriter(gz)
for _, e := range entries {
tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o600, Size: int64(len(e.content)), Typeflag: tar.TypeReg})
tw.Write([]byte(e.content))
}
tw.Close()
gz.Close()
f.Close()
}
// manifestFor is a manifest that lists only db/registry.db as in a.
func manifestFor(t *testing.T, archive string) string {
m, err := Verify(archive)
if err != nil {
t.Fatal(err)
}
return `{"schema":1,"program":"prog","files":[{"name":"db/registry.db","size":8,"mode":384,"sha256":"` + m.Files[0].SHA256 + `"}]}`
}
func TestListAndPrune(t *testing.T) {
dir := t.TempDir()
loc := time.UTC
start := time.Date(2026, 1, 1, 3, 0, 0, 0, loc)
// One archive a day for 200 days, two on the last day.
for d := 0; d < 200; d++ {
ts := start.AddDate(0, 0, d)
write(t, filepath.Join(dir, "prog-"+ts.Format(timeLayout)+".tar.gz"), "x", 0o600)
}
last := start.AddDate(0, 0, 199)
write(t, filepath.Join(dir, "prog-"+last.Format(timeLayout)+"-2.tar.gz"), "x", 0o600)
write(t, filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz"), "x", 0o600)
write(t, filepath.Join(dir, "prog-notatime.tar.gz"), "x", 0o600)
all, err := List(dir, "prog")
if err != nil {
t.Fatal(err)
}
if len(all) != 201 || !strings.HasSuffix(all[0].Path, "-2.tar.gz") {
t.Fatalf("list = %d, first %s", len(all), all[0].Path)
}
if none, _ := List(filepath.Join(dir, "missing"), "prog"); len(none) != 0 {
t.Error("a missing directory lists archives")
}
if removed, _ := Prune(dir, "prog", Keep{}, loc); len(removed) != 0 {
t.Error("an empty Keep removed archives")
}
removed, err := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc)
if err != nil {
t.Fatal(err)
}
kept, _ := List(dir, "prog")
if len(kept)+len(removed) != 201 {
t.Fatalf("kept %d + removed %d", len(kept), len(removed))
}
// 3 newest (2 of them on the last day) + 6 more days; weekly and
// monthly add the older ones: at most 3+7+4+6, at least 7+6.
if len(kept) < 13 || len(kept) > 20 {
t.Errorf("kept %d archives", len(kept))
}
months := map[string]bool{}
for _, a := range kept {
months[a.CreatedAt.Format("2006-01")] = true
}
if len(months) != 6 {
t.Errorf("months kept: %v", months)
}
if _, err := os.Stat(filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz")); err != nil {
t.Error("another program's archive was removed")
}
// Pruning again changes nothing.
if again, _ := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc); len(again) != 0 {
t.Errorf("second prune removed %d", len(again))
}
}
func TestCreateRejectsBadInput(t *testing.T) {
if _, err := Create(t.TempDir(), "../x", ""); err == nil {
t.Error("program name with a path")
}
w, err := Create(t.TempDir(), "prog", "")
if err != nil {
t.Fatal(err)
}
defer w.Abort()
for _, n := range []string{"", "/abs", "../up", "a/./b", ManifestName} {
if err := w.AddBytes(n, nil, 0o600); err == nil {
t.Errorf("name %q accepted", n)
}
}
}
+30
View File
@@ -94,7 +94,13 @@ func IsUsage(err error) bool {
// 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:
@@ -106,6 +112,30 @@ func Execute(root *cobra.Command) int {
}
}
// 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
+7
View File
@@ -15,6 +15,9 @@ func newRoot() *cobra.Command {
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
}
@@ -43,6 +46,10 @@ func TestExitCodes(t *testing.T) {
{[]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)
+59 -7
View File
@@ -5,7 +5,12 @@
//
// The scripts are deliberately simple, word-based completion of command
// and subcommand names (not flag-aware): they join the words typed so far
// into a prefix and look up what may follow it.
// into a prefix and look up what may follow it. A level that also takes a
// file or directory path (a program without subcommands that is started
// as "<program> [path]") adds the Files key; the shell then completes
// paths there too:
//
// var tree = completion.Tree{completion.Files: nil, "manual": nil, ...}
//
// var tree = completion.Tree{
// "serve": nil,
@@ -41,6 +46,10 @@ func Leaf(names ...string) Tree {
return t
}
// Files is a Tree key, not a command: the level it is in also completes
// file and directory paths. Its value is ignored.
const Files = "<files>"
// Shells are the supported shells, in the order help texts list them.
var Shells = []string{"bash", "zsh", "fish", "powershell"}
@@ -53,6 +62,7 @@ var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`)
type entry struct {
prefix string
words []string
files bool // paths complete here too (Files)
}
func flatten(tree Tree) ([]entry, error) {
@@ -60,14 +70,19 @@ func flatten(tree Tree) ([]entry, error) {
var walk func(prefix string, t Tree) error
walk = func(prefix string, t Tree) error {
names := make([]string, 0, len(t))
files := false
for n := range t {
if n == Files {
files = true
continue
}
if !safeWord.MatchString(n) {
return fmt.Errorf("completion: command name %q is not a plain word", n)
}
names = append(names, n)
}
sort.Strings(names)
out = append(out, entry{prefix, names})
out = append(out, entry{prefix, names, files})
for _, n := range names {
if sub := t[n]; len(sub) > 0 {
p := n
@@ -84,6 +99,15 @@ func flatten(tree Tree) ([]entry, error) {
return out, walk("", tree)
}
func anyFiles(entries []entry) bool {
for _, e := range entries {
if e.files {
return true
}
}
return false
}
// Script returns the completion script for shell.
func Script(program, shell string, tree Tree) (string, error) {
if !safeWord.MatchString(program) {
@@ -100,16 +124,30 @@ func Script(program, shell string, tree Tree) (string, error) {
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
for _, e := range entries {
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\"))", e.prefix, strings.Join(e.words, " "))
if e.files {
// One path per line, so names with spaces stay whole;
// compopt (bash 4+) adds the trailing "/" and quoting.
b.WriteString("\n local IFS=$'\\n'; COMPREPLY+=($(compgen -f -- \"$cur\")); compopt -o filenames 2>/dev/null")
}
b.WriteString("; return ;;\n")
}
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
case "zsh":
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\"\n local -a completions\n case \"$prefix\" in\n", fn)
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\" files=0\n local -a completions\n case \"$prefix\" in\n", fn)
for _, e := range entries {
fmt.Fprintf(&b, " %q) completions=(%s) ;;\n", e.prefix, strings.Join(e.words, " "))
f := ""
if e.files {
f = "; files=1"
}
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n")
fmt.Fprintf(&b, " %q) completions=(%s)%s ;;\n", e.prefix, strings.Join(e.words, " "), f)
}
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n")
if anyFiles(entries) {
b.WriteString(" (( files )) && _files\n")
}
b.WriteString("}\n")
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
case "fish":
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
@@ -125,6 +163,9 @@ func Script(program, shell string, tree Tree) (string, error) {
quoted[i] = fmt.Sprintf("%q", w)
}
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
if e.files {
b.WriteString(" __fish_complete_path (commandline -ct)\n")
}
}
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
case "powershell":
@@ -143,7 +184,18 @@ func Script(program, shell string, tree Tree) (string, error) {
}
b.WriteString(" default { @() }\n }\n")
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n")
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n")
var filePrefixes []string
for _, e := range entries {
if e.files {
filePrefixes = append(filePrefixes, "'"+e.prefix+"'")
}
}
if len(filePrefixes) > 0 {
fmt.Fprintf(&b, " if (@(%s) -contains $prefix) {\n", strings.Join(filePrefixes, ", "))
b.WriteString(" [System.Management.Automation.CompletionCompleters]::CompleteFilename($wordToComplete)\n }\n")
}
b.WriteString("}\n")
default:
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
}
+66
View File
@@ -2,7 +2,10 @@ package completion
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
)
@@ -48,3 +51,66 @@ func TestBashCompletes(t *testing.T) {
t.Fatalf("bash completion: %v %q", err, out)
}
}
// A program without subcommands takes a path as its first argument.
var pathTree = Tree{
Files: nil,
"manual": nil,
"config": Leaf("path"),
"completion": Leaf(Shells...),
}
func TestScriptsWithFiles(t *testing.T) {
want := map[string]string{
"bash": "compgen -f",
"zsh": "_files",
"fish": "__fish_complete_path",
"powershell": "CompleteFilename",
}
for _, shell := range Shells {
s, err := Script("tool", shell, pathTree)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(s, want[shell]) {
t.Errorf("%s script lacks path completion %q", shell, want[shell])
}
if strings.Contains(s, Files) {
t.Errorf("%s script offers the marker %q as a word", shell, Files)
}
// Without the marker no level completes paths.
s, _ = Script("tool", shell, tree)
if strings.Contains(s, want[shell]) {
t.Errorf("%s script completes paths without Files", shell)
}
}
}
// TestBashCompletesPaths runs the generated bash function in a directory
// with a file whose name has a space, when bash is there.
func TestBashCompletesPaths(t *testing.T) {
if _, err := exec.LookPath("bash"); err != nil {
t.Skip("no bash")
}
dir := t.TempDir()
for _, name := range []string{"my notes.txt", "manuscript"} {
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o600); err != nil {
t.Fatal(err)
}
}
s, _ := Script("tool", "bash", pathTree)
for cword, want := range map[string]string{
"m": "manual|manuscript|my notes.txt", // command names and paths
"config p": "path", // a level without Files: no paths
} {
words := strings.Fields("tool " + cword)
script := s + "\nCOMP_WORDS=(" + strings.Join(words, " ") + "); COMP_CWORD=" +
strconv.Itoa(len(words)-1) + "; _tool_complete; printf '%s\\n' \"${COMPREPLY[@]}\" | sort | paste -sd '|' -"
cmd := exec.Command("bash", "-c", script)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil || strings.TrimSpace(string(out)) != want {
t.Errorf("bash completion of %q: %v %q, want %q", cword, err, out, want)
}
}
}
+2 -2
View File
@@ -85,8 +85,8 @@ type Spec struct {
Filename string
// Optional says the program also runs without a configuration file
// (on built-in defaults): "validate" and "upgrade" then report that
// no file exists instead of failing.
// (on built-in defaults): "validate", "upgrade", "show" and Doctor
// then report that no file exists instead of failing.
Optional bool
// None says the program has no configuration at all; every
+71
View File
@@ -427,3 +427,74 @@ func TestFilenameAndFind(t *testing.T) {
t.Fatalf("Find: %v, %v", l.Path, err)
}
}
type secretRef struct {
Env string `yaml:"env,omitempty"`
File string `yaml:"file,omitempty"`
Value string `yaml:"value,omitempty"`
}
func (secretRef) ConfigOneOf() {}
type oneOfSchema struct {
Auth struct {
Type string `yaml:"type"`
Token secretRef `yaml:"token"`
Email *secretRef `yaml:"email"`
} `yaml:"auth"`
}
const oneOfTemplate = `auth:
type: bearer
# exactly one of env, file or value
token:
env: TOKEN
email:
file: /run/secrets/email
`
func TestUndocumentedKeysOneOf(t *testing.T) {
got, err := UndocumentedKeys(oneOfTemplate, oneOfSchema{})
if err != nil {
t.Fatal(err)
}
if len(got) != 0 {
t.Errorf("UndocumentedKeys(one alternative set) = %v, want none", got)
}
// No alternative in the template: every one is undocumented.
got, _ = UndocumentedKeys("auth:\n type: bearer\n token: {}\n email:\n env: E\n", oneOfSchema{})
if want := "auth.token.env auth.token.file auth.token.value"; strings.Join(got, " ") != want {
t.Errorf("UndocumentedKeys(empty token) = %v, want %s", got, want)
}
// A struct without the marker still needs every field.
type plain struct {
Token struct {
Env string `yaml:"env"`
File string `yaml:"file"`
} `yaml:"token"`
}
got, _ = UndocumentedKeys("token:\n env: X\n", plain{})
if want := "token.file"; strings.Join(got, " ") != want {
t.Errorf("UndocumentedKeys(plain) = %v, want %s", got, want)
}
}
func TestMissingOneOfOffersNoOtherAlternative(t *testing.T) {
file := "auth:\n type: bearer\n token:\n file: /run/secrets/token\n email:\n value: me@example.org\n"
got, err := Missing([]byte(file), []byte(oneOfTemplate), oneOfSchema{})
if err != nil {
t.Fatal(err)
}
if len(got) != 0 {
t.Errorf("Missing() = %v, want nothing (each secret has its alternative)", got)
}
// Without the schema the template's alternative is offered as before.
got, _ = Missing([]byte(file), []byte(oneOfTemplate), nil)
var keys []string
for _, a := range got {
keys = append(keys, a.Key)
}
if want := "auth.token.env auth.email.file"; strings.Join(keys, " ") != want {
t.Errorf("Missing(no schema) = %v, want %s", keys, want)
}
}
+16 -1
View File
@@ -39,7 +39,8 @@ type Layered struct {
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.
// 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
@@ -179,6 +180,16 @@ func (s Spec) layeredPath(explicit string, stdout, stderr io.Writer) int {
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
@@ -273,6 +284,10 @@ func Doctor(r *doctor.Report, s Spec, explicit string) *Effective {
}
}
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) {
+35 -4
View File
@@ -82,6 +82,9 @@ func docMapping(doc *yaml.Node) *yaml.Node {
// of file).
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
var out []Addition
// A file that chose one alternative of a OneOf struct gets none of
// the template's others offered.
chosen := isOneOf(t) && len(fmap.Content) > 0
for i := 0; i+1 < len(tmap.Content); i += 2 {
tkey, tval := tmap.Content[i], tmap.Content[i+1]
sub := append(append([]string(nil), path...), tkey.Value)
@@ -105,7 +108,7 @@ func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent,
}
continue
}
if mentioned(lines, from, to, childIndent, tkey.Value) {
if chosen || mentioned(lines, from, to, childIndent, tkey.Value) {
continue
}
out = append(out, Addition{
@@ -226,12 +229,36 @@ func Apply(raw []byte, adds []Addition) []byte {
return []byte(out)
}
// OneOf marks a configuration struct whose fields are alternatives, of
// which a file sets exactly one -- a secret taken from env, file or
// value, say. The method itself does nothing; implementing it is the
// marker:
//
// func (SecretRef) ConfigOneOf() {}
//
// UndocumentedKeys then accepts a template that sets one alternative
// (and explains the others in comments), and Missing offers none of the
// others to a file that already chose one.
type OneOf interface{ ConfigOneOf() }
var oneOfType = reflect.TypeOf((*OneOf)(nil)).Elem()
// isOneOf reports whether t (or a pointer to it) implements OneOf.
func isOneOf(t reflect.Type) bool {
if t == nil {
return false
}
t = deref(t)
return t.Implements(oneOfType) || reflect.PointerTo(t).Implements(oneOfType)
}
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
// value, e.g. config.Config{}) that the template does not contain --
// neither as a key nor, for a list of structs, in the list's first
// item. A program's tests call it with its full template so that a new
// option cannot be added without documenting it, which is what keeps
// "config upgrade" useful.
// item. A struct implementing OneOf counts as documented when the
// template sets any one of its fields. A program's tests call it with
// its full template so that a new option cannot be added without
// documenting it, which is what keeps "config upgrade" useful.
func UndocumentedKeys(template string, schema any) ([]string, error) {
var doc yaml.Node
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
@@ -251,6 +278,8 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
if t.Kind() != reflect.Struct {
return
}
// One alternative set: the others are not missing.
chosen := isOneOf(t) && len(m.Content) > 0
for i := range t.NumField() {
f := t.Field(i)
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
@@ -268,7 +297,9 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
sub := append(append([]string(nil), path...), name)
_, val := lookup(m, name)
if val == nil {
if !chosen {
*out = append(*out, strings.Join(sub, "."))
}
continue
}
ft := deref(f.Type)
+218
View File
@@ -0,0 +1,218 @@
package configfamily
import (
"errors"
"flag"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/configcmd"
"yetano.dev/yetano/core/doctor"
"yetano.dev/yetano/core/paths"
)
// Spec is one program's part of the config command.
type Spec struct {
Program Program
// Optional says the program also runs without any configuration
// file, on built-in defaults: validate, show and doctor then report
// that instead of failing.
Optional bool
// Minimal is the template "config create" writes by default: what
// the program needs to start. Full is "config create --full",
// documenting every option the program reads; "config upgrade"
// offers its options a file does not mention yet.
Minimal, Full string
// Validate parses and validates the merged configuration (YAML, see
// Loaded.YAML) the same way the program does at startup. For an
// Optional program without a file it gets nil.
Validate func(merged []byte) error
// Schema is the program's configuration struct (e.g. config.Config{}):
// it enables unknown-option detection and tells "config show" which
// options the program reads.
Schema any
// Options are passed through to core/config; tests use them to
// inject a platform, environment and root.
Options []coreconfig.Option
}
// Core returns the core/configcmd Spec this Spec stands for: create and
// upgrade work on the program's own file, path, validate and show on
// all layers through core's Layered hook.
func (s Spec) Core() configcmd.Spec {
c := coreSpec(s.Program, s.Options)
c.Optional = s.Optional
c.Minimal, c.Full, c.Schema = s.Minimal, s.Full, s.Schema
c.Layered = &configcmd.Layered{
Layers: func(explicit string) ([]configcmd.LayerInfo, error) {
layers, err := Layers(s.Program, explicit, s.Options...)
if err != nil {
return nil, err
}
out := make([]configcmd.LayerInfo, len(layers))
for i, l := range layers {
out[i] = l.Info()
}
return out, nil
},
Load: func(explicit string) (*configcmd.Effective, error) {
l, err := s.Load(explicit)
if err != nil {
return nil, err
}
return l.Effective(), nil
},
Unknown: func(e *configcmd.Effective) ([]configcmd.UnknownKey, error) {
l, ok := e.Loader.(*Loaded)
if !ok || s.Schema == nil {
return nil, nil
}
return l.Unknown(s.Schema)
},
Validate: s.Validate,
Used: func(key string) bool {
return s.Schema == nil || configcmd.KnownKey(s.Schema, key)
},
}
return c
}
// Load is the package's Load for this program.
func (s Spec) Load(explicit string) (*Loaded, error) {
return Load(s.Program, explicit, s.Options...)
}
// Run serves "<program> config <args...>" and returns the exit code.
// explicit is the program's --config value ("" if not given). Only
// "create --shared" is this package's own; everything else is
// core/configcmd's.
func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
shared := s.Program.Family.SharedTemplate != ""
if len(args) > 0 && shared {
switch args[0] {
case "create":
if slices.Contains(args[1:], "--shared") || slices.Contains(args[1:], "-shared") {
return s.createShared(args[1:], stdout, stderr)
}
case "help", "-h", "-help", "--help":
configcmd.Run(s.Core(), explicit, args, stdout, stderr)
fmt.Fprintf(stdout, " create --shared [--force] [--output <file>]\n write a commented starter %s, the options the %s programs share\n", s.Program.Family.SharedFilename(), s.Program.Family.Name)
return configcmd.ExitOK
}
}
return configcmd.Run(s.Core(), explicit, args, stdout, stderr)
}
// Doctor is core/configcmd's Doctor for this program: it records the
// paths and every configuration layer in r, checks that the
// configuration loads and has no unknown options, and returns it (nil
// when there is none or it does not load).
func Doctor(r *doctor.Report, s Spec, explicit string) *Loaded {
e := configcmd.Doctor(r, s.Core(), explicit)
if e == nil {
return nil
}
l, _ := e.Loader.(*Loaded)
return l
}
// WarnUnknown logs every unknown option of every layer of l: the
// program keeps running with the defaults for those keys, but the
// operator sees why a setting has no effect.
func WarnUnknown(log *slog.Logger, l *Loaded, schema any) {
unknown, err := l.Unknown(schema)
if err != nil {
return // Load already read and parsed every file
}
for _, k := range unknown {
log.Warn("configuration: unknown option, ignored (the default applies)", "option", k.Key, "line", k.Line, "path", k.Layer)
}
}
// LogLayers logs the files l was merged from, lowest priority first.
func LogLayers(log *slog.Logger, l *Loaded) {
used := l.Used()
for i := len(used) - 1; i >= 0; i-- {
log.Info("configuration file", "path", used[i].Name(), "source", used[i].SourceName())
}
}
// createShared writes Family.SharedTemplate: to --output, else to the
// family file the program reads first, else into the user config
// directory -- the system one when running as root or without a home.
func (s Spec) createShared(args []string, stdout, stderr io.Writer) int {
name := s.Program.Name
fs := flag.NewFlagSet(name+" config create", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.Bool("shared", true, "write "+s.Program.Family.SharedFilename()+", the options the programs share")
force := fs.Bool("force", false, "overwrite an existing file")
output := fs.String("output", "", "write to this file")
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return configcmd.ExitOK
}
return configcmd.ExitUsage
}
if fs.NArg() != 0 {
fmt.Fprintf(stderr, "%s config create: unexpected argument %q\n", name, fs.Arg(0))
return configcmd.ExitUsage
}
path := *output
if path == "" {
layers, err := Layers(s.Program, "", s.Options...)
if err != nil {
fmt.Fprintf(stderr, "%s config create: %v\n", name, err)
return configcmd.ExitProblem
}
var user, system string
for _, l := range layers {
if l.Kind != SharedLayer {
continue
}
if l.Exists && path == "" {
path = l.Path
}
if l.Source == paths.SystemDirectory {
system = l.Path
} else if user == "" {
user = l.Path
}
}
if path == "" {
path = user
if os.Geteuid() == 0 || user == "" {
path = system
}
}
if path == "" {
fmt.Fprintf(stderr, "%s config create: no configuration directory known; pass --output <file>\n", name)
return configcmd.ExitProblem
}
}
if _, err := os.Stat(path); err == nil && !*force {
fmt.Fprintf(stderr, "%s config create: %s exists; pass --force to overwrite it\n", name, path)
return configcmd.ExitProblem
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
fmt.Fprintf(stderr, "%s config create: %v\n", name, err)
return configcmd.ExitProblem
}
// 0640: a configuration may name credentials files and should not be
// world-readable by default.
if err := os.WriteFile(path, []byte(s.Program.Family.SharedTemplate), 0o640); err != nil {
fmt.Fprintf(stderr, "%s config create: %v\n", name, err)
return configcmd.ExitProblem
}
fmt.Fprintf(stdout, "%s: wrote the shared configuration -- review it, then run \"%s config validate\"\n", path, name)
return configcmd.ExitOK
}
+111
View File
@@ -0,0 +1,111 @@
// Package configfamily locates and merges the configuration of a program
// that belongs to a family of programs sharing one set of config
// directories -- the yamase-* or yaiam-* programs (yamase ADR-0074). Each
// program is responsible for its own file; a family-wide file is
// optional and holds what several programs share.
//
// In each config directory of the family (core/config's tiers, without
// the working directory) a program reads:
//
// - <family>.yaml, its top level: options several programs share
// (storage, logging, ...), minus the program sections;
// - <family>.yaml, the program's section (its name without the
// "<family>-" prefix: "web:" for yaiam-web);
// - <program>.yaml, the program's own file.
//
// Load merges them lowest priority first -- system tier, then user tier,
// then the file --config names -- with core/config's merge rules (maps
// merge key by key, scalars and lists are replaced, null removes a key).
// The working directory is never read; no environment expansion is
// done. Parsing and validating the merged result stays with the program
// (Loaded.YAML), since its options are its own business.
//
// Spec and Run serve the standard "config" command on top of this: path,
// validate and show work on all layers, create and upgrade on the
// program's own file, and "config create --shared" writes the family
// file from Family.SharedTemplate.
package configfamily
import (
"slices"
"strings"
"yetano.dev/yetano/core"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/configcmd"
)
// ErrNotFound is returned (wrapped, with the searched files) by Load
// when no layer exists at all.
var ErrNotFound = configcmd.ErrNotFound
// Family describes a family of programs.
type Family struct {
// Name is the family's name: the core.Application name every
// program shares (it names the config directories) and the prefix
// of the program names ("yaiam" for yaiam-web).
Name string
// Programs are the section names of the family's programs in the
// family file ("web", "authd", ...). These top-level keys are never
// part of the shared layer.
Programs []string
// Shared is the schema (a struct value) of the options the family
// file holds at its top level. Its options are valid in every layer
// of every program, even one that does not read them. nil: none.
Shared any
// SharedTemplate is what "config create --shared" writes as the
// family file. "": the command is not offered.
SharedTemplate string
}
// SharedFilename is the family-wide file, "<Name>.yaml".
func (f Family) SharedFilename() string { return f.Name + ".yaml" }
// IsProgramSection reports whether key is a program section of the
// family file.
func (f Family) IsProgramSection(key string) bool { return slices.Contains(f.Programs, key) }
// IsSharedKey reports whether key (dotted) is an option of the family's
// shared schema.
func (f Family) IsSharedKey(key string) bool {
return f.Shared != nil && configcmd.KnownKey(f.Shared, key)
}
// Service returns the Program for a long-running service of the family.
// Scope stays at its UserScope default, so the user config dir is
// searched before the system one -- Kind and Scope are independent.
func (f Family) Service(name string) Program {
return Program{Family: f, App: core.Application{Name: f.Name, Kind: core.Service}, Name: name}
}
// CLI returns the Program for a command-line tool of the family.
func (f Family) CLI(name string) Program {
return Program{Family: f, App: core.Application{Name: f.Name, Kind: core.CLI}, Name: name}
}
// Program is one program of a family.
type Program struct {
Family Family
// App is the family-wide core.Application (Name is Family.Name);
// only its Kind differs between services and command-line tools.
App core.Application
// Name is the program's own name, e.g. "yaiam-web".
Name string
}
// Filename is the program's own file, "<Name>.yaml".
func (p Program) Filename() string { return p.Name + ".yaml" }
// Section is the key of the program's section in the family file: its
// name without the "<family>-" prefix.
func (p Program) Section() string { return strings.TrimPrefix(p.Name, p.Family.Name+"-") }
// coreSpec is core/configcmd's Spec for p's own file: the family
// directories without the working directory and "<Name>.yaml".
func coreSpec(p Program, opts []coreconfig.Option) configcmd.Spec {
opts = append(append([]coreconfig.Option(nil), opts...), coreconfig.WithWorkingDirectory(false))
return configcmd.Spec{Name: p.Name, App: p.App, Filename: p.Filename(), Options: opts}
}
+252
View File
@@ -0,0 +1,252 @@
package configfamily
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/doctor"
"yetano.dev/yetano/core/paths"
)
type sharedSchema struct {
Storage struct {
Path string `yaml:"path"`
} `yaml:"storage"`
LogLevel string `yaml:"log-level"`
}
type webSchema struct {
Listen string `yaml:"listen"`
Storage struct {
Path string `yaml:"path"`
} `yaml:"storage"`
}
var family = Family{
Name: "fam",
Programs: []string{"web", "authd"},
Shared: sharedSchema{},
SharedTemplate: "# shared\nlog-level: info\n",
}
func testOptions(root string) []coreconfig.Option {
return []coreconfig.Option{
coreconfig.WithEnvironment(map[string]string{"HOME": "/home/test"}),
coreconfig.WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
}
}
func testSpec(root string) Spec {
return Spec{
Program: family.Service("fam-web"),
Optional: true,
Minimal: "listen: \":8080\"\n",
Full: "listen: \":8080\"\nstorage:\n path: \"\"\n",
Validate: func(merged []byte) error {
var w webSchema
if err := yaml.Unmarshal(merged, &w); err != nil {
return err
}
if w.Listen == "bad" {
return errors.New("listen is bad")
}
return nil
},
Schema: webSchema{},
Options: testOptions(root),
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
func dirs(root string) (system, user string) {
return filepath.Join(root, "etc", "fam"), filepath.Join(root, "home", "test", ".config", "fam")
}
func TestLayersOrder(t *testing.T) {
root := t.TempDir()
system, user := dirs(root)
writeFile(t, filepath.Join(user, "fam.yaml"), "web:\n listen: \":1\"\n")
explicit := filepath.Join(root, "explicit.yaml")
writeFile(t, explicit, "listen: \":2\"\n")
layers, err := Layers(family.Service("fam-web"), explicit, testOptions(root)...)
if err != nil {
t.Fatal(err)
}
want := []struct {
kind LayerKind
path string
ok bool
}{
{ExplicitLayer, explicit, true},
{ProgramLayer, filepath.Join(user, "fam-web.yaml"), false},
{SectionLayer, filepath.Join(user, "fam.yaml"), true},
{SharedLayer, filepath.Join(user, "fam.yaml"), true},
{ProgramLayer, filepath.Join(system, "fam-web.yaml"), false},
{SectionLayer, filepath.Join(system, "fam.yaml"), false},
{SharedLayer, filepath.Join(system, "fam.yaml"), false},
}
if len(layers) != len(want) {
t.Fatalf("got %d layers, want %d: %+v", len(layers), len(want), layers)
}
for i, w := range want {
l := layers[i]
if l.Kind != w.kind || l.Path != w.path || l.Exists != w.ok {
t.Errorf("layer %d = %+v, want kind %d path %s exists %v", i, l, w.kind, w.path, w.ok)
}
}
if _, err := Layers(family.Service("fam-web"), filepath.Join(root, "missing.yaml"), testOptions(root)...); err == nil {
t.Error("a missing --config file is not an error")
}
}
func TestLoadMergesByPriority(t *testing.T) {
root := t.TempDir()
system, user := dirs(root)
writeFile(t, filepath.Join(system, "fam.yaml"),
"log-level: info\nstorage:\n path: /var/lib/fam/db\nweb:\n listen: \":1\"\nauthd:\n listen: \":9\"\n")
writeFile(t, filepath.Join(system, "fam-web.yaml"), "listen: \":2\"\n")
writeFile(t, filepath.Join(user, "fam.yaml"), "log-level: debug\n")
l, err := Load(family.Service("fam-web"), "", testOptions(root)...)
if err != nil {
t.Fatal(err)
}
if got := l.Merged["listen"]; got != ":2" {
t.Errorf("listen = %v, want the program file's :2 over the section's :1", got)
}
if got := l.Merged["log-level"]; got != "debug" {
t.Errorf("log-level = %v, want the user tier's debug", got)
}
if _, ok := l.Merged["authd"]; ok {
t.Error("another program's section leaked into the merged configuration")
}
if _, ok := l.Merged["web"]; ok {
t.Error("the program's own section was merged as a key instead of its content")
}
if got := l.Origins["listen"]; got != filepath.Join(system, "fam-web.yaml") {
t.Errorf("origin of listen = %q", got)
}
if !strings.Contains(l.Describe(), "[web]") {
t.Errorf("Describe() = %q, want the section layer named", l.Describe())
}
}
func TestLoadWithoutFiles(t *testing.T) {
_, err := Load(family.Service("fam-web"), "", testOptions(t.TempDir())...)
if !errors.Is(err, ErrNotFound) {
t.Errorf("Load = %v, want ErrNotFound", err)
}
}
func TestUnknown(t *testing.T) {
root := t.TempDir()
system, _ := dirs(root)
// log-level is a shared option fam-web does not read: valid
// everywhere. typo is unknown in every layer; other programs'
// sections are not fam-web's business.
writeFile(t, filepath.Join(system, "fam.yaml"),
"log-level: info\ntypo1: x\nweb:\n listen: \":1\"\n typo2: x\nauthd:\n anything: x\n")
writeFile(t, filepath.Join(system, "fam-web.yaml"), "listen: \":2\"\nlog-level: debug\ntypo3: x\n")
l, err := Load(family.Service("fam-web"), "", testOptions(root)...)
if err != nil {
t.Fatal(err)
}
unknown, err := l.Unknown(webSchema{})
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, k := range unknown {
got[k.Key] = true
}
for _, want := range []string{"typo1", "web.typo2", "typo3"} {
if !got[want] {
t.Errorf("unknown options %v lack %s", unknown, want)
}
}
if len(unknown) != 3 {
t.Errorf("unknown options = %v, want exactly typo1, web.typo2, typo3", unknown)
}
}
func run(t *testing.T, s Spec, explicit string, args ...string) (int, string, string) {
t.Helper()
var out, errOut bytes.Buffer
code := Run(s, explicit, args, &out, &errOut)
return code, out.String(), errOut.String()
}
func TestConfigCommandOptionalWithoutFiles(t *testing.T) {
s := testSpec(t.TempDir())
if code, out, errOut := run(t, s, "", "validate"); code != 0 || !strings.Contains(out, "built-in defaults") {
t.Errorf("validate: exit %d, out %q, err %q", code, out, errOut)
}
if code, out, _ := run(t, s, "", "path"); code != 0 || !strings.Contains(out, "fam-web.yaml") || !strings.Contains(out, "fam.yaml [web]") {
t.Errorf("path: exit %d, out %q", code, out)
}
r := doctor.Report{Program: "fam-web"}
if l := Doctor(&r, s, ""); l != nil {
t.Error("Doctor returned a configuration without any file")
}
if r.Problems() != 0 {
t.Errorf("Doctor reports problems for an optional program without a file: %+v", r)
}
s.Optional = false
if code, _, _ := run(t, s, "", "validate"); code != 1 {
t.Errorf("validate of a required configuration without files: exit %d, want 1", code)
}
}
func TestConfigCommandValidateAndCreate(t *testing.T) {
root := t.TempDir()
system, user := dirs(root)
s := testSpec(root)
if code, out, errOut := run(t, s, "", "create"); code != 0 || !strings.Contains(out, filepath.Join(user, "fam-web.yaml")) {
t.Fatalf("create: exit %d, out %q, err %q", code, out, errOut)
}
if code, out, errOut := run(t, s, "", "create", "--shared"); code != 0 || !strings.Contains(out, filepath.Join(user, "fam.yaml")) {
t.Fatalf("create --shared: exit %d, out %q, err %q", code, out, errOut)
}
if code, _, _ := run(t, s, "", "create", "--shared"); code != 1 {
t.Errorf("create --shared over an existing file: exit %d, want 1", code)
}
if code, out, errOut := run(t, s, "", "validate"); code != 0 || !strings.Contains(out, "valid") {
t.Errorf("validate: exit %d, out %q, err %q", code, out, errOut)
}
writeFile(t, filepath.Join(system, "fam-web.yaml"), "listen: bad\n")
writeFile(t, filepath.Join(user, "fam-web.yaml"), "storage:\n path: /x\n")
if code, _, errOut := run(t, s, "", "validate"); code != 1 || !strings.Contains(errOut, "listen is bad") {
t.Errorf("validate of an invalid merge: exit %d, err %q", code, errOut)
}
}
func TestSection(t *testing.T) {
if got := family.Service("fam-authd").Section(); got != "authd" {
t.Errorf("Section() = %q", got)
}
if got := family.CLI("fam-ctl").Filename(); got != "fam-ctl.yaml" {
t.Errorf("Filename() = %q", got)
}
}
+249
View File
@@ -0,0 +1,249 @@
package configfamily
import (
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
coreconfig "yetano.dev/yetano/core/config"
"yetano.dev/yetano/core/configcmd"
"yetano.dev/yetano/core/paths"
)
// LayerKind says which part of which file a Layer is.
type LayerKind int
const (
// SharedLayer is the top level of the family file, without the
// program sections.
SharedLayer LayerKind = iota
// SectionLayer is the program's section of the family file.
SectionLayer
// ProgramLayer is the program's own file.
ProgramLayer
// ExplicitLayer is the file --config names.
ExplicitLayer
)
// Layer is one input of a program's configuration.
type Layer struct {
Kind LayerKind
// Path is the file. A SectionLayer has the family file's path.
Path string
// Section is the program section's key for a SectionLayer, else "".
Section string
// Source is the tier the file's directory belongs to (user, system,
// ...; paths.APIOverride for --config).
Source paths.Source
// Exists reports whether the layer contributes anything: the file
// exists (for a SectionLayer: and has the section).
Exists bool
}
// Name is how a value's origin is shown: the path, with the section in
// brackets for a SectionLayer.
func (l Layer) Name() string {
if l.Kind == SectionLayer {
return l.Path + " [" + l.Section + "]"
}
return l.Path
}
// SourceName is the tier for display ("--config" for an explicit file).
func (l Layer) SourceName() string {
if l.Kind == ExplicitLayer {
return "--config"
}
return l.Source.String()
}
// Info returns l as core/configcmd's LayerInfo.
func (l Layer) Info() configcmd.LayerInfo {
return configcmd.LayerInfo{Name: l.Name(), Path: l.Path, Source: l.SourceName(), Exists: l.Exists}
}
// Layers returns every layer of p's configuration, highest priority
// first, whether it exists or not:
//
// --config <file>
// user tier: <program>.yaml, <family>.yaml [<section>], <family>.yaml
// system tier: <program>.yaml, <family>.yaml [<section>], <family>.yaml
//
// A --config file that does not exist is an error.
func Layers(p Program, explicit string, opts ...coreconfig.Option) ([]Layer, error) {
var out []Layer
if explicit != "" {
if _, err := os.Stat(explicit); err != nil {
return nil, fmt.Errorf("config: --config %s: %w", explicit, err)
}
out = append(out, Layer{Kind: ExplicitLayer, Path: explicit, Source: paths.APIOverride, Exists: true})
}
programFiles, err := tierFiles(p, p.Filename(), opts)
if err != nil {
return nil, err
}
sharedFiles, err := tierFiles(p, p.Family.SharedFilename(), opts)
if err != nil {
return nil, err
}
if len(programFiles) != len(sharedFiles) {
return nil, fmt.Errorf("config: %d tiers for %s but %d for %s", len(programFiles), p.Filename(), len(sharedFiles), p.Family.SharedFilename())
}
for i, pf := range programFiles {
sf := sharedFiles[i]
section := Layer{Kind: SectionLayer, Path: sf.Path, Section: p.Section(), Source: sf.Source}
if sf.Exists {
data, err := coreconfig.ReadFile(sf.Path)
if err != nil {
return nil, err
}
_, section.Exists = data[p.Section()]
}
out = append(out,
Layer{Kind: ProgramLayer, Path: pf.Path, Source: pf.Source, Exists: pf.Exists},
section,
Layer{Kind: SharedLayer, Path: sf.Path, Source: sf.Source, Exists: sf.Exists},
)
}
return out, nil
}
// tierFiles is core/config's layer list for filename in the family's
// directories, without the working directory.
func tierFiles(p Program, filename string, opts []coreconfig.Option) ([]coreconfig.Layer, error) {
r, err := coreconfig.New(p.App, append(append([]coreconfig.Option(nil), opts...),
coreconfig.WithFilename(filename),
coreconfig.WithWorkingDirectory(false),
coreconfig.WithEnvExpansion(false))...)
if err != nil {
return nil, err
}
return r.ResolveAll()
}
// Loaded is a program's merged configuration.
type Loaded struct {
Program Program
// Layers are all layers, highest priority first (see Layers).
Layers []Layer
// Merged is the merged configuration.
Merged map[string]any
// Origins names the layer (Layer.Name) every leaf of Merged came
// from.
Origins coreconfig.Origins
}
// Load reads and merges every existing layer of p's configuration,
// lowest priority first. explicit is the --config value ("" if not
// given). With no layer at all it returns ErrNotFound, wrapped with the
// searched files; a program that runs on built-in defaults treats that
// as "no file", not as a failure.
func Load(p Program, explicit string, opts ...coreconfig.Option) (*Loaded, error) {
layers, err := Layers(p, explicit, opts...)
if err != nil {
return nil, err
}
var sources []coreconfig.Source
for i := len(layers) - 1; i >= 0; i-- {
l := layers[i]
if !l.Exists {
continue
}
data, err := layerData(p.Family, l)
if err != nil {
return nil, err
}
sources = append(sources, coreconfig.Source{Name: l.Name(), Data: data})
}
if len(sources) == 0 {
return nil, notFound(p, layers)
}
merged, origins := coreconfig.Merge(sources...)
return &Loaded{Program: p, Layers: layers, Merged: merged, Origins: origins}, nil
}
// layerData is the part of l's file that l contributes.
func layerData(f Family, l Layer) (map[string]any, error) {
data, err := coreconfig.ReadFile(l.Path)
if err != nil {
return nil, err
}
switch l.Kind {
case SharedLayer:
shared := make(map[string]any, len(data))
for k, v := range data {
if !f.IsProgramSection(k) {
shared[k] = v
}
}
return shared, nil
case SectionLayer:
v := data[l.Section]
if v == nil {
return map[string]any{}, nil
}
section, ok := v.(map[string]any)
if !ok {
return nil, fmt.Errorf("config: %s: %s: want a mapping of options", l.Path, l.Section)
}
return section, nil
}
return data, nil
}
func notFound(p Program, layers []Layer) error {
seen := map[string]bool{}
var b strings.Builder
for _, l := range layers {
if l.Kind == SectionLayer || seen[l.Path] {
continue
}
seen[l.Path] = true
b.WriteString("\n " + l.Path)
}
return fmt.Errorf("%w for %s; searched:%s", ErrNotFound, p.Name, b.String())
}
// Effective returns l as core/configcmd's Effective (for config show,
// path, validate and doctor), with l itself as its Loader.
func (l *Loaded) Effective() *configcmd.Effective {
layers := make([]configcmd.LayerInfo, len(l.Layers))
for i, layer := range l.Layers {
layers[i] = layer.Info()
}
return &configcmd.Effective{Name: l.Program.Name, Layers: layers, Merged: l.Merged, Origins: l.Origins, Loader: l}
}
// Used returns the layers that contributed, highest priority first.
func (l *Loaded) Used() []Layer {
var out []Layer
for _, layer := range l.Layers {
if layer.Exists {
out = append(out, layer)
}
}
return out
}
// YAML returns the merged configuration as YAML, for the program's own
// parser.
func (l *Loaded) YAML() ([]byte, error) {
data, err := yaml.Marshal(l.Merged)
if err != nil {
return nil, fmt.Errorf("config: marshal merged configuration: %w", err)
}
return data, nil
}
// Describe names the files that contributed, lowest priority first, for
// log lines and error messages ("a.yaml + b.yaml [web]").
func (l *Loaded) Describe() string {
used := l.Used()
names := make([]string, len(used))
for i, layer := range used {
names[len(used)-1-i] = layer.Name()
}
return strings.Join(names, " + ")
}
+89
View File
@@ -0,0 +1,89 @@
package configfamily
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/configcmd"
)
// Unknown returns the unknown options of every layer that contributed,
// checked against schema (the program's configuration struct). The
// program starts anyway with the default for them.
//
// - the program's own file, --config and its section of the family
// file: every key schema does not have, except an option of the
// family's shared schema, which is valid in every layer;
// - the family file's top level: a key neither the shared schema nor
// schema has -- an option some other program reads is not unknown,
// and neither are the other programs' sections.
func (l *Loaded) Unknown(schema any) ([]configcmd.UnknownKey, error) {
f := l.Program.Family
var out []configcmd.UnknownKey
for i := len(l.Layers) - 1; i >= 0; i-- {
layer := l.Layers[i]
if !layer.Exists {
continue
}
root, err := parseMapping(layer.Path)
if err != nil {
return nil, err
}
var keys []configcmd.UnknownKey
switch layer.Kind {
case SharedLayer:
shared := &yaml.Node{Kind: yaml.MappingNode}
for j := 0; j+1 < len(root.Content); j += 2 {
if !f.IsProgramSection(root.Content[j].Value) {
shared.Content = append(shared.Content, root.Content[j], root.Content[j+1])
}
}
keys = configcmd.UnknownKeysNode(shared, schema)
case SectionLayer:
keys = configcmd.UnknownKeysNode(mappingValue(root, layer.Section), schema)
default:
keys = configcmd.UnknownKeysNode(root, schema)
}
for _, k := range keys {
if f.IsSharedKey(k.Key) {
continue // a family option, valid in every layer
}
if layer.Kind == SectionLayer {
k.Key = layer.Section + "." + k.Key
}
k.Layer = layer.Name()
out = append(out, k)
}
}
return out, nil
}
// parseMapping parses path and returns its top-level mapping node (an
// empty one for an empty file).
func parseMapping(path string) (*yaml.Node, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: read %s: %w", path, err)
}
var doc yaml.Node
if err := yaml.Unmarshal(raw, &doc); err != nil {
return nil, fmt.Errorf("config: parse %s: %w", path, err)
}
if doc.Kind == yaml.DocumentNode && len(doc.Content) == 1 && doc.Content[0].Kind == yaml.MappingNode {
return doc.Content[0], nil
}
return &yaml.Node{Kind: yaml.MappingNode}, nil
}
// mappingValue returns the value node of key in mapping n (an empty
// mapping if absent).
func mappingValue(n *yaml.Node, key string) *yaml.Node {
for i := 0; i+1 < len(n.Content); i += 2 {
if n.Content[i].Value == key {
return n.Content[i+1]
}
}
return &yaml.Node{Kind: yaml.MappingNode}
}
+31 -3
View File
@@ -36,11 +36,16 @@ type Path struct {
Error string `json:"error,omitempty"`
}
// Check is one named check.
// Check is one named check. Area (a group such as "config" or
// "services") and Hint (what to do about a failed check) are optional
// and omitted from the JSON form when empty, so a report without them
// looks exactly as before they existed.
type Check struct {
Area string `json:"area,omitempty"`
Name string `json:"name"`
OK bool `json:"ok"`
Note string `json:"note,omitempty"`
Hint string `json:"hint,omitempty"`
}
// Report is "<program> doctor --json"'s output.
@@ -110,6 +115,12 @@ func (r *Report) Check(name string, ok bool, note string) {
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
}
// Add records a check with all its fields, for a program that groups its
// checks into areas or gives hints.
func (r *Report) Add(c Check) {
r.Checks = append(r.Checks, c)
}
// Problems counts failed checks.
func (r Report) Problems() int {
n := 0
@@ -148,9 +159,26 @@ func (r Report) Write(w io.Writer, asJSON bool) error {
}
fmt.Fprintln(tw)
}
fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n")
// The AREA and HINT columns only appear when some check uses them,
// so the table of a program without them is unchanged.
withArea, withHint := false, false
for _, c := range r.Checks {
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note)
withArea = withArea || c.Area != ""
withHint = withHint || c.Hint != ""
}
row := func(area, name, ok, note, hint string) {
cols := []string{name, ok, note}
if withArea {
cols = append([]string{area}, cols...)
}
if withHint {
cols = append(cols, hint)
}
fmt.Fprintln(tw, strings.Join(cols, "\t"))
}
row("AREA", "CHECK", "OK", "NOTE", "HINT")
for _, c := range r.Checks {
row(c.Area, c.Name, yesNo(c.OK), c.Note, c.Hint)
}
return tw.Flush()
}
+34
View File
@@ -49,3 +49,37 @@ func TestAddPaths(t *testing.T) {
}
}
}
func TestAreaAndHint(t *testing.T) {
// Without area/hint neither the JSON nor the table mentions them.
plain := Report{Program: "tool"}
plain.Check("config valid", true, "")
var out strings.Builder
if err := plain.Write(&out, true); err != nil || strings.Contains(out.String(), "area") || strings.Contains(out.String(), "hint") {
t.Fatalf("plain json: %v %s", err, out.String())
}
out.Reset()
if err := plain.Write(&out, false); err != nil || strings.Contains(out.String(), "AREA") || strings.Contains(out.String(), "HINT") {
t.Fatalf("plain table: %v %s", err, out.String())
}
r := Report{Program: "tool"}
r.Add(Check{Area: "config", Name: "config loads", OK: false, Note: "line 3", Hint: "run tool config validate"})
r.Check("other", true, "")
out.Reset()
if err := r.Write(&out, true); err != nil {
t.Fatal(err)
}
var got Report
if err := json.Unmarshal([]byte(out.String()), &got); err != nil || got.Checks[0].Area != "config" || got.Checks[0].Hint != "run tool config validate" || got.Checks[1].Area != "" {
t.Fatalf("json: %v %+v", err, got)
}
out.Reset()
if err := r.Write(&out, false); err != nil {
t.Fatal(err)
}
lines := strings.Split(out.String(), "\n")
if !strings.HasPrefix(lines[0], "AREA") || !strings.Contains(lines[0], "HINT") || !strings.HasPrefix(lines[1], "config") || !strings.Contains(lines[1], "run tool config validate") {
t.Fatalf("table:\n%s", out.String())
}
}