4 Commits
Author SHA1 Message Date
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
terminarandClaude Opus 5.5 5288c4ce74 cobracmd: standard completion and exit codes for cobra programs; bash install line via eval
New module yetano.dev/yetano/core/cobracmd (own go.mod, cobra stays out
of the main module): Completion replaces cobra's default completion
command, which exits 0 for an unknown shell, with one that accepts only
bash|zsh|fish|powershell (exit 2 otherwise); Execute maps cobra's usage
errors to exit 2, other errors to 1.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:34:39 +01:00
15 changed files with 1340 additions and 11 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
+7 -7
View File
@@ -1,9 +1,9 @@
MIT License
Copyright (c) 2026 yetano. All rights reserved.
Copyright (c) 2026 yetano
core is proprietary software. No license is granted to use, copy,
modify, merge, publish, distribute, sublicense or sell copies of it, in
whole or in part, except with 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 Yetano projects are closed source for now; until their license is
decided, this notice applies.
+47
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/cobracmd (separate module)
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
yetano.dev/yetano/core/gui/assets
@@ -373,6 +375,51 @@ options of other programs), and `create`/`upgrade` keep working on the
program's own file. `KnownKey(schema, "a.b[0].c")` tells whether a
dotted key is an option of a config struct.
## core/configfamily: one file per program, an optional family file
`core/configfamily` is that layered setup ready-made, for a family of
programs that share one set of config directories (the yamase-* or
yaiam-* programs). Each program is responsible for its own file
(`<program>.yaml`); the family file (`<family>.yaml`) is optional and
holds, at its top level, what several programs share, plus one section
per program (`web:` for `yaiam-web`). Per tier -- system, then user,
then `--config` -- a program merges: family file top level, its section,
its own file. The working directory is never read.
```go
family := configfamily.Family{
Name: "yaiam", Programs: []string{"ctl", "web", "authd"},
Shared: config.Shared{}, SharedTemplate: config.SharedTemplate,
}
spec := configfamily.Spec{
Program: family.Service("yaiam-web"), Optional: true,
Minimal: webMinimal, Full: webFull, Schema: config.WebConfig{},
Validate: func(merged []byte) error { ... },
}
os.Exit(configfamily.Run(spec, configFlag, args, os.Stdout, os.Stderr))
```
`Load(program, explicit)` returns the merged layers (`Loaded.YAML()`
for the program's own parser, `Describe()` for log lines) or
`ErrNotFound`; `Loaded.Unknown(schema)` reports options no layer may
carry -- an option of `Family.Shared` is valid in every layer, other
programs' sections are not this program's business. `Run` adds `config
create --shared` (writes `Family.SharedTemplate`) to core/configcmd's
commands; `Doctor`, `LogLayers` and `WarnUnknown` are the doctor and
startup parts. Defaults that depend on more than the files (yamase's
data-dir and storage roles) stay with the family's own code.
## core/cobracmd: cobra programs (separate module)
`yetano.dev/yetano/core/cobracmd` (own `go.mod`, tags `cobracmd/vX.Y.Z`,
so the main module stays free of cobra) fixes the two places where cobra
behaves differently from the standard: `cobracmd.Completion(root)`
replaces cobra's default `completion` command with one that takes exactly
`bash|zsh|fish|powershell` (cobra's own exits 0 for `completion tcsh`),
and `os.Exit(cobracmd.Execute(root))` maps errors to the standard exit
codes -- 2 for usage errors (unknown command, flag or shell, wrong
argument count, or an error wrapped with `cobracmd.Usage`), 1 otherwise.
## core/version: "<program> version [--json]"
The values stay in each program's `internal/version` (stamped with
+208
View File
@@ -0,0 +1,208 @@
// Package cobracmd gives cobra-based Yetano programs the parts of the
// program standard (docs/program-conventions.md in the yetano
// meta-repository) that cobra does differently by default:
//
// - Completion replaces cobra's default "completion" command with one
// that takes exactly bash, zsh, fish or powershell. cobra's own
// command prints its help and exits 0 for "completion tcsh"; the
// standard wants exit 2 for an unknown shell.
// - Execute runs the root command and returns the standard exit code:
// 0 on success, 2 for a usage error (unknown command, flag or shell,
// wrong number of arguments), 1 for any other error.
//
// It is a separate module (yetano.dev/yetano/core/cobracmd) so that the
// main core module stays free of cobra.
//
// func main() {
// root := newRootCommand()
// cobracmd.Completion(root)
// os.Exit(cobracmd.Execute(root))
// }
//
// A command that wants to report a usage error itself returns
// cobracmd.Usage(err).
package cobracmd
import (
"errors"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
)
// Exit codes, matching core/doctor's.
const (
ExitOK = 0
ExitProblem = 1
ExitUsage = 2
)
// Shells are the shells "completion" accepts.
var Shells = []string{"bash", "zsh", "fish", "powershell"}
// UsageError marks an error as a usage error (exit 2).
type UsageError struct{ Err error }
func (e *UsageError) Error() string { return e.Err.Error() }
func (e *UsageError) Unwrap() error { return e.Err }
// Usage wraps err as a usage error; nil stays nil.
func Usage(err error) error {
if err == nil {
return nil
}
return &UsageError{Err: err}
}
// cobraUsage are the prefixes of the usage errors cobra and pflag
// produce themselves (unknown command, argument validators, flags).
var cobraUsage = []string{
"unknown command ",
"unknown flag: ",
"unknown shorthand flag: ",
"flag needs an argument: ",
"invalid argument ",
"bad flag syntax: ",
"required flag(s) ",
"if any flags in the group ",
"accepts ",
"requires at least ",
"requires at most ",
}
// IsUsage reports whether err is a usage error: wrapped with Usage, or
// one of cobra's/pflag's own argument and flag errors.
func IsUsage(err error) bool {
if err == nil {
return false
}
var u *UsageError
if errors.As(err, &u) {
return true
}
msg := err.Error()
for _, p := range cobraUsage {
if strings.HasPrefix(msg, p) {
return true
}
}
return false
}
// Execute runs root and returns the exit code: 0, 2 for a usage error,
// 1 for any other error. cobra prints the error itself unless the
// command sets SilenceErrors.
//
// Before running, it makes every command group below root strict (see
// StrictGroups): cobra itself rejects an unknown subcommand only at the
// root ("prog nosuch"), while "prog group nosuch" printed the group's
// help and exited 0.
func Execute(root *cobra.Command) int {
StrictGroups(root)
err := root.Execute()
switch {
case err == nil:
return ExitOK
case IsUsage(err):
return ExitUsage
default:
return ExitProblem
}
}
// StrictGroups makes every command below root that only groups
// subcommands (it has subcommands, no Run/RunE and no Args of its own)
// reject an unknown subcommand as a usage error; called without one it
// still prints its help (exit 0). Execute calls it; it is exported for
// programs that run root.Execute themselves.
func StrictGroups(root *cobra.Command) {
var walk func(c *cobra.Command)
walk = func(c *cobra.Command) {
for _, sub := range c.Commands() {
if sub.HasSubCommands() && !sub.Runnable() && sub.Args == nil {
sub.Args = func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return Usage(fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()))
}
return nil
}
sub.RunE = func(cmd *cobra.Command, _ []string) error { return cmd.Help() }
}
walk(sub)
}
}
walk(root)
}
// Completion replaces cobra's default completion command on root with
// "completion <bash|zsh|fish|powershell>": exactly one argument, one of
// Shells; anything else is a usage error. The script is cobra's own
// (subcommands and flags, with descriptions), preceded by its install
// line.
func Completion(root *cobra.Command) {
root.CompletionOptions.DisableDefaultCmd = true
for _, c := range root.Commands() {
if c.Name() == "completion" {
root.RemoveCommand(c)
}
}
name := root.Name()
root.AddCommand(&cobra.Command{
Use: "completion <" + strings.Join(Shells, "|") + ">",
Short: "Print a shell completion script",
Long: installHelp(name),
ValidArgs: Shells,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return Usage(fmt.Errorf("%s completion: exactly one shell expected (%s)", name, strings.Join(Shells, ", ")))
}
for _, s := range Shells {
if args[0] == s {
return nil
}
}
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, args[0], strings.Join(Shells, ", ")))
},
DisableFlagsInUseLine: true,
RunE: func(cmd *cobra.Command, args []string) error {
return Script(root, args[0], cmd.OutOrStdout())
},
})
}
// Script writes root's completion script for shell to w.
func Script(root *cobra.Command, shell string, w io.Writer) error {
name := root.Name()
switch shell {
case "bash":
fmt.Fprintf(w, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", name, name)
return root.GenBashCompletionV2(w, true)
case "zsh":
// cobra's script starts with "#compdef", which must stay the
// first line for zsh's fpath autoloading.
if err := root.GenZshCompletion(w); err != nil {
return err
}
_, err := fmt.Fprintf(w, "# Install with: source <(%s completion zsh) (after compinit)\n", name)
return err
case "fish":
fmt.Fprintf(w, "# %s fish completion. Install with:\n# %s completion fish | source\n", name, name)
return root.GenFishCompletion(w, true)
case "powershell":
fmt.Fprintf(w, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", name, name)
return root.GenPowerShellCompletionWithDesc(w)
default:
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, shell, strings.Join(Shells, ", ")))
}
}
func installHelp(name string) string {
return fmt.Sprintf(`Print a completion script for bash, zsh, fish or PowerShell.
eval "$(%[1]s completion bash)" # ~/.bashrc
source <(%[1]s completion zsh) # ~/.zshrc, after compinit
%[1]s completion fish | source # ~/.config/fish/config.fish
%[1]s completion powershell | Out-String | Invoke-Expression # $PROFILE`, name)
}
+113
View File
@@ -0,0 +1,113 @@
package cobracmd
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
)
func newRoot() *cobra.Command {
root := &cobra.Command{Use: "yatool", SilenceUsage: true, SilenceErrors: true}
root.AddCommand(&cobra.Command{Use: "serve", RunE: func(*cobra.Command, []string) error { return nil }})
root.AddCommand(&cobra.Command{Use: "one <arg>", Args: cobra.ExactArgs(1), RunE: func(*cobra.Command, []string) error { return nil }})
root.AddCommand(&cobra.Command{Use: "fail", RunE: func(*cobra.Command, []string) error { return errors.New("broken") }})
root.AddCommand(&cobra.Command{Use: "bad", RunE: func(*cobra.Command, []string) error { return Usage(errors.New("wrong")) }})
group := &cobra.Command{Use: "queue", Short: "queue commands"}
group.AddCommand(&cobra.Command{Use: "list", RunE: func(*cobra.Command, []string) error { return nil }})
root.AddCommand(group)
Completion(root)
return root
}
func run(args ...string) (int, string) {
root := newRoot()
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs(args)
return Execute(root), out.String()
}
func TestExitCodes(t *testing.T) {
for _, tc := range []struct {
args []string
want int
}{
{[]string{"serve"}, ExitOK},
{[]string{"fail"}, ExitProblem},
{[]string{"bad"}, ExitUsage},
{[]string{"nosuch"}, ExitUsage},
{[]string{"serve", "--nosuch"}, ExitUsage},
{[]string{"one"}, ExitUsage},
{[]string{"one", "a", "b"}, ExitUsage},
{[]string{"completion"}, ExitUsage},
{[]string{"completion", "tcsh"}, ExitUsage},
{[]string{"completion", "bash", "zsh"}, ExitUsage},
{[]string{"queue"}, ExitOK},
{[]string{"queue", "list"}, ExitOK},
{[]string{"queue", "nosuch"}, ExitUsage},
{[]string{"queue", "--nosuch"}, ExitUsage},
} {
if got, out := run(tc.args...); got != tc.want {
t.Errorf("%v: exit %d, want %d (%s)", tc.args, got, tc.want, out)
}
}
}
func TestCompletionScripts(t *testing.T) {
for shell, want := range map[string][]string{
"bash": {`eval "$(yatool completion bash)"`, "__start_yatool"},
"zsh": {"#compdef yatool", "source <(yatool completion zsh)"},
"fish": {"yatool completion fish | source", "complete -c yatool"},
"powershell": {"Invoke-Expression", "Register-ArgumentCompleter"},
} {
code, out := run("completion", shell)
if code != ExitOK {
t.Fatalf("%s: exit %d", shell, code)
}
for _, w := range want {
if !strings.Contains(out, w) {
t.Errorf("%s script lacks %q", shell, w)
}
}
}
if _, out := run("completion", "zsh"); !strings.HasPrefix(out, "#compdef") {
t.Errorf("zsh script must start with #compdef: %.40q", out)
}
}
func TestCompletionReplacesDefault(t *testing.T) {
root := newRoot()
n := 0
for _, c := range root.Commands() {
if c.Name() == "completion" {
n++
}
}
if n != 1 {
t.Fatalf("%d completion commands, want 1", n)
}
// Calling it twice (e.g. a shared root builder) still leaves one.
Completion(root)
n = 0
for _, c := range root.Commands() {
if c.Name() == "completion" {
n++
}
}
if n != 1 {
t.Fatalf("after a second Completion: %d completion commands, want 1", n)
}
}
func TestIsUsage(t *testing.T) {
if IsUsage(nil) || IsUsage(errors.New("disk full")) {
t.Error("plain errors are no usage errors")
}
if !IsUsage(Usage(errors.New("x"))) || Usage(nil) != nil {
t.Error("Usage wrapping")
}
}
+10
View File
@@ -0,0 +1,10 @@
module yetano.dev/yetano/core/cobracmd
go 1.25.0
require github.com/spf13/cobra v1.10.2
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect
)
+10
View File
@@ -0,0 +1,10 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+1 -1
View File
@@ -97,7 +97,7 @@ func Script(program, shell string, tree Tree) (string, error) {
var b strings.Builder
switch shell {
case "bash":
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program)
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
for _, e := range entries {
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
+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
+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) {
+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}
}