Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5471863163 | ||
|
|
5288c4ce74 | ||
|
|
fa52990e3e |
No files matched your search
@@ -29,6 +29,7 @@ yetano.dev/yetano/core/doctor
|
|||||||
yetano.dev/yetano/core/configcmd
|
yetano.dev/yetano/core/configcmd
|
||||||
yetano.dev/yetano/core/version
|
yetano.dev/yetano/core/version
|
||||||
yetano.dev/yetano/core/secretref
|
yetano.dev/yetano/core/secretref
|
||||||
|
yetano.dev/yetano/core/cobracmd (separate module)
|
||||||
|
|
||||||
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
|
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
|
||||||
yetano.dev/yetano/core/gui/assets
|
yetano.dev/yetano/core/gui/assets
|
||||||
@@ -355,6 +356,35 @@ in the full template -- that is what keeps `config upgrade` useful.
|
|||||||
report options the program ignores. Taken over from
|
report options the program ignores. Taken over from
|
||||||
`yamase-core/pkg/configcmd`, which now wraps it.
|
`yamase-core/pkg/configcmd`, which now wraps it.
|
||||||
|
|
||||||
|
`config show [--json] [--show-secrets]` prints the configuration with
|
||||||
|
the file every value comes from (`Effective.Show`; secrets -- keys
|
||||||
|
`secrets`, `secret`, `token`, `password` -- are redacted unless
|
||||||
|
`--show-secrets`, references like `env:X` stay visible), and
|
||||||
|
`configcmd.Doctor(report, spec, explicit)` is the config part of a
|
||||||
|
`doctor` command (paths, layers, "config file found", unknown options).
|
||||||
|
|
||||||
|
A program whose configuration is merged from more than one file name
|
||||||
|
per directory -- a family-wide file, a section of it and a per-program
|
||||||
|
file, as in the yamase family -- sets `Spec.Layered`: `Layers` (what
|
||||||
|
`config path` lists), `Load` (merge, e.g. with `config.Merge`, into an
|
||||||
|
`Effective`), optionally `Unknown` (its own unknown-option rules),
|
||||||
|
`Validate(merged)` and `Used(key)`. `path`, `validate` and `show` then
|
||||||
|
work on all layers, unknown options become warnings (shared files carry
|
||||||
|
options of other programs), and `create`/`upgrade` keep working on the
|
||||||
|
program's own file. `KnownKey(schema, "a.b[0].c")` tells whether a
|
||||||
|
dotted key is an option of a config struct.
|
||||||
|
|
||||||
|
## core/cobracmd: cobra programs (separate module)
|
||||||
|
|
||||||
|
`yetano.dev/yetano/core/cobracmd` (own `go.mod`, tags `cobracmd/vX.Y.Z`,
|
||||||
|
so the main module stays free of cobra) fixes the two places where cobra
|
||||||
|
behaves differently from the standard: `cobracmd.Completion(root)`
|
||||||
|
replaces cobra's default `completion` command with one that takes exactly
|
||||||
|
`bash|zsh|fish|powershell` (cobra's own exits 0 for `completion tcsh`),
|
||||||
|
and `os.Exit(cobracmd.Execute(root))` maps errors to the standard exit
|
||||||
|
codes -- 2 for usage errors (unknown command, flag or shell, wrong
|
||||||
|
argument count, or an error wrapped with `cobracmd.Usage`), 1 otherwise.
|
||||||
|
|
||||||
## core/version: "<program> version [--json]"
|
## core/version: "<program> version [--json]"
|
||||||
|
|
||||||
The values stay in each program's `internal/version` (stamped with
|
The values stay in each program's `internal/version` (stamped with
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
// Package cobracmd gives cobra-based Yetano programs the parts of the
|
||||||
|
// program standard (docs/program-conventions.md in the yetano
|
||||||
|
// meta-repository) that cobra does differently by default:
|
||||||
|
//
|
||||||
|
// - Completion replaces cobra's default "completion" command with one
|
||||||
|
// that takes exactly bash, zsh, fish or powershell. cobra's own
|
||||||
|
// command prints its help and exits 0 for "completion tcsh"; the
|
||||||
|
// standard wants exit 2 for an unknown shell.
|
||||||
|
// - Execute runs the root command and returns the standard exit code:
|
||||||
|
// 0 on success, 2 for a usage error (unknown command, flag or shell,
|
||||||
|
// wrong number of arguments), 1 for any other error.
|
||||||
|
//
|
||||||
|
// It is a separate module (yetano.dev/yetano/core/cobracmd) so that the
|
||||||
|
// main core module stays free of cobra.
|
||||||
|
//
|
||||||
|
// func main() {
|
||||||
|
// root := newRootCommand()
|
||||||
|
// cobracmd.Completion(root)
|
||||||
|
// os.Exit(cobracmd.Execute(root))
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// A command that wants to report a usage error itself returns
|
||||||
|
// cobracmd.Usage(err).
|
||||||
|
package cobracmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes, matching core/doctor's.
|
||||||
|
const (
|
||||||
|
ExitOK = 0
|
||||||
|
ExitProblem = 1
|
||||||
|
ExitUsage = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// Shells are the shells "completion" accepts.
|
||||||
|
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
||||||
|
|
||||||
|
// UsageError marks an error as a usage error (exit 2).
|
||||||
|
type UsageError struct{ Err error }
|
||||||
|
|
||||||
|
func (e *UsageError) Error() string { return e.Err.Error() }
|
||||||
|
func (e *UsageError) Unwrap() error { return e.Err }
|
||||||
|
|
||||||
|
// Usage wraps err as a usage error; nil stays nil.
|
||||||
|
func Usage(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &UsageError{Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
// cobraUsage are the prefixes of the usage errors cobra and pflag
|
||||||
|
// produce themselves (unknown command, argument validators, flags).
|
||||||
|
var cobraUsage = []string{
|
||||||
|
"unknown command ",
|
||||||
|
"unknown flag: ",
|
||||||
|
"unknown shorthand flag: ",
|
||||||
|
"flag needs an argument: ",
|
||||||
|
"invalid argument ",
|
||||||
|
"bad flag syntax: ",
|
||||||
|
"required flag(s) ",
|
||||||
|
"if any flags in the group ",
|
||||||
|
"accepts ",
|
||||||
|
"requires at least ",
|
||||||
|
"requires at most ",
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsUsage reports whether err is a usage error: wrapped with Usage, or
|
||||||
|
// one of cobra's/pflag's own argument and flag errors.
|
||||||
|
func IsUsage(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var u *UsageError
|
||||||
|
if errors.As(err, &u) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
msg := err.Error()
|
||||||
|
for _, p := range cobraUsage {
|
||||||
|
if strings.HasPrefix(msg, p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute runs root and returns the exit code: 0, 2 for a usage error,
|
||||||
|
// 1 for any other error. cobra prints the error itself unless the
|
||||||
|
// command sets SilenceErrors.
|
||||||
|
//
|
||||||
|
// Before running, it makes every command group below root strict (see
|
||||||
|
// StrictGroups): cobra itself rejects an unknown subcommand only at the
|
||||||
|
// root ("prog nosuch"), while "prog group nosuch" printed the group's
|
||||||
|
// help and exited 0.
|
||||||
|
func Execute(root *cobra.Command) int {
|
||||||
|
StrictGroups(root)
|
||||||
|
err := root.Execute()
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
return ExitOK
|
||||||
|
case IsUsage(err):
|
||||||
|
return ExitUsage
|
||||||
|
default:
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// StrictGroups makes every command below root that only groups
|
||||||
|
// subcommands (it has subcommands, no Run/RunE and no Args of its own)
|
||||||
|
// reject an unknown subcommand as a usage error; called without one it
|
||||||
|
// still prints its help (exit 0). Execute calls it; it is exported for
|
||||||
|
// programs that run root.Execute themselves.
|
||||||
|
func StrictGroups(root *cobra.Command) {
|
||||||
|
var walk func(c *cobra.Command)
|
||||||
|
walk = func(c *cobra.Command) {
|
||||||
|
for _, sub := range c.Commands() {
|
||||||
|
if sub.HasSubCommands() && !sub.Runnable() && sub.Args == nil {
|
||||||
|
sub.Args = func(cmd *cobra.Command, args []string) error {
|
||||||
|
if len(args) > 0 {
|
||||||
|
return Usage(fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sub.RunE = func(cmd *cobra.Command, _ []string) error { return cmd.Help() }
|
||||||
|
}
|
||||||
|
walk(sub)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Completion replaces cobra's default completion command on root with
|
||||||
|
// "completion <bash|zsh|fish|powershell>": exactly one argument, one of
|
||||||
|
// Shells; anything else is a usage error. The script is cobra's own
|
||||||
|
// (subcommands and flags, with descriptions), preceded by its install
|
||||||
|
// line.
|
||||||
|
func Completion(root *cobra.Command) {
|
||||||
|
root.CompletionOptions.DisableDefaultCmd = true
|
||||||
|
for _, c := range root.Commands() {
|
||||||
|
if c.Name() == "completion" {
|
||||||
|
root.RemoveCommand(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name := root.Name()
|
||||||
|
root.AddCommand(&cobra.Command{
|
||||||
|
Use: "completion <" + strings.Join(Shells, "|") + ">",
|
||||||
|
Short: "Print a shell completion script",
|
||||||
|
Long: installHelp(name),
|
||||||
|
ValidArgs: Shells,
|
||||||
|
Args: func(cmd *cobra.Command, args []string) error {
|
||||||
|
if len(args) != 1 {
|
||||||
|
return Usage(fmt.Errorf("%s completion: exactly one shell expected (%s)", name, strings.Join(Shells, ", ")))
|
||||||
|
}
|
||||||
|
for _, s := range Shells {
|
||||||
|
if args[0] == s {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, args[0], strings.Join(Shells, ", ")))
|
||||||
|
},
|
||||||
|
DisableFlagsInUseLine: true,
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
return Script(root, args[0], cmd.OutOrStdout())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Script writes root's completion script for shell to w.
|
||||||
|
func Script(root *cobra.Command, shell string, w io.Writer) error {
|
||||||
|
name := root.Name()
|
||||||
|
switch shell {
|
||||||
|
case "bash":
|
||||||
|
fmt.Fprintf(w, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", name, name)
|
||||||
|
return root.GenBashCompletionV2(w, true)
|
||||||
|
case "zsh":
|
||||||
|
// cobra's script starts with "#compdef", which must stay the
|
||||||
|
// first line for zsh's fpath autoloading.
|
||||||
|
if err := root.GenZshCompletion(w); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := fmt.Fprintf(w, "# Install with: source <(%s completion zsh) (after compinit)\n", name)
|
||||||
|
return err
|
||||||
|
case "fish":
|
||||||
|
fmt.Fprintf(w, "# %s fish completion. Install with:\n# %s completion fish | source\n", name, name)
|
||||||
|
return root.GenFishCompletion(w, true)
|
||||||
|
case "powershell":
|
||||||
|
fmt.Fprintf(w, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", name, name)
|
||||||
|
return root.GenPowerShellCompletionWithDesc(w)
|
||||||
|
default:
|
||||||
|
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, shell, strings.Join(Shells, ", ")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func installHelp(name string) string {
|
||||||
|
return fmt.Sprintf(`Print a completion script for bash, zsh, fish or PowerShell.
|
||||||
|
|
||||||
|
eval "$(%[1]s completion bash)" # ~/.bashrc
|
||||||
|
source <(%[1]s completion zsh) # ~/.zshrc, after compinit
|
||||||
|
%[1]s completion fish | source # ~/.config/fish/config.fish
|
||||||
|
%[1]s completion powershell | Out-String | Invoke-Expression # $PROFILE`, name)
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package cobracmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newRoot() *cobra.Command {
|
||||||
|
root := &cobra.Command{Use: "yatool", SilenceUsage: true, SilenceErrors: true}
|
||||||
|
root.AddCommand(&cobra.Command{Use: "serve", RunE: func(*cobra.Command, []string) error { return nil }})
|
||||||
|
root.AddCommand(&cobra.Command{Use: "one <arg>", Args: cobra.ExactArgs(1), RunE: func(*cobra.Command, []string) error { return nil }})
|
||||||
|
root.AddCommand(&cobra.Command{Use: "fail", RunE: func(*cobra.Command, []string) error { return errors.New("broken") }})
|
||||||
|
root.AddCommand(&cobra.Command{Use: "bad", RunE: func(*cobra.Command, []string) error { return Usage(errors.New("wrong")) }})
|
||||||
|
group := &cobra.Command{Use: "queue", Short: "queue commands"}
|
||||||
|
group.AddCommand(&cobra.Command{Use: "list", RunE: func(*cobra.Command, []string) error { return nil }})
|
||||||
|
root.AddCommand(group)
|
||||||
|
Completion(root)
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(args ...string) (int, string) {
|
||||||
|
root := newRoot()
|
||||||
|
var out bytes.Buffer
|
||||||
|
root.SetOut(&out)
|
||||||
|
root.SetErr(&out)
|
||||||
|
root.SetArgs(args)
|
||||||
|
return Execute(root), out.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExitCodes(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
args []string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{[]string{"serve"}, ExitOK},
|
||||||
|
{[]string{"fail"}, ExitProblem},
|
||||||
|
{[]string{"bad"}, ExitUsage},
|
||||||
|
{[]string{"nosuch"}, ExitUsage},
|
||||||
|
{[]string{"serve", "--nosuch"}, ExitUsage},
|
||||||
|
{[]string{"one"}, ExitUsage},
|
||||||
|
{[]string{"one", "a", "b"}, ExitUsage},
|
||||||
|
{[]string{"completion"}, ExitUsage},
|
||||||
|
{[]string{"completion", "tcsh"}, ExitUsage},
|
||||||
|
{[]string{"completion", "bash", "zsh"}, ExitUsage},
|
||||||
|
{[]string{"queue"}, ExitOK},
|
||||||
|
{[]string{"queue", "list"}, ExitOK},
|
||||||
|
{[]string{"queue", "nosuch"}, ExitUsage},
|
||||||
|
{[]string{"queue", "--nosuch"}, ExitUsage},
|
||||||
|
} {
|
||||||
|
if got, out := run(tc.args...); got != tc.want {
|
||||||
|
t.Errorf("%v: exit %d, want %d (%s)", tc.args, got, tc.want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompletionScripts(t *testing.T) {
|
||||||
|
for shell, want := range map[string][]string{
|
||||||
|
"bash": {`eval "$(yatool completion bash)"`, "__start_yatool"},
|
||||||
|
"zsh": {"#compdef yatool", "source <(yatool completion zsh)"},
|
||||||
|
"fish": {"yatool completion fish | source", "complete -c yatool"},
|
||||||
|
"powershell": {"Invoke-Expression", "Register-ArgumentCompleter"},
|
||||||
|
} {
|
||||||
|
code, out := run("completion", shell)
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("%s: exit %d", shell, code)
|
||||||
|
}
|
||||||
|
for _, w := range want {
|
||||||
|
if !strings.Contains(out, w) {
|
||||||
|
t.Errorf("%s script lacks %q", shell, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, out := run("completion", "zsh"); !strings.HasPrefix(out, "#compdef") {
|
||||||
|
t.Errorf("zsh script must start with #compdef: %.40q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompletionReplacesDefault(t *testing.T) {
|
||||||
|
root := newRoot()
|
||||||
|
n := 0
|
||||||
|
for _, c := range root.Commands() {
|
||||||
|
if c.Name() == "completion" {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
t.Fatalf("%d completion commands, want 1", n)
|
||||||
|
}
|
||||||
|
// Calling it twice (e.g. a shared root builder) still leaves one.
|
||||||
|
Completion(root)
|
||||||
|
n = 0
|
||||||
|
for _, c := range root.Commands() {
|
||||||
|
if c.Name() == "completion" {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
t.Fatalf("after a second Completion: %d completion commands, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsUsage(t *testing.T) {
|
||||||
|
if IsUsage(nil) || IsUsage(errors.New("disk full")) {
|
||||||
|
t.Error("plain errors are no usage errors")
|
||||||
|
}
|
||||||
|
if !IsUsage(Usage(errors.New("x"))) || Usage(nil) != nil {
|
||||||
|
t.Error("Usage wrapping")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
module yetano.dev/yetano/core/cobracmd
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require github.com/spf13/cobra v1.10.2
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.9 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||||
|
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||||
|
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||||
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
@@ -97,7 +97,7 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
switch shell {
|
switch shell {
|
||||||
case "bash":
|
case "bash":
|
||||||
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program)
|
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
|
||||||
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
|
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
|
||||||
|
|||||||
+37
-4
@@ -6,6 +6,7 @@
|
|||||||
// <program> config validate
|
// <program> config validate
|
||||||
// <program> config upgrade [--write]
|
// <program> config upgrade [--write]
|
||||||
// <program> config path
|
// <program> config path
|
||||||
|
// <program> config show [--json] [--show-secrets]
|
||||||
//
|
//
|
||||||
// The command behaves the same in every program; what differs is only
|
// The command behaves the same in every program; what differs is only
|
||||||
// the program's own part, passed in as a Spec: its name and
|
// the program's own part, passed in as a Spec: its name and
|
||||||
@@ -33,6 +34,11 @@
|
|||||||
// Exit codes: 0 success, 1 the command ran and found a problem (invalid
|
// Exit codes: 0 success, 1 the command ran and found a problem (invalid
|
||||||
// configuration, no file found, refusing to overwrite), 2 usage error.
|
// configuration, no file found, refusing to overwrite), 2 usage error.
|
||||||
//
|
//
|
||||||
|
// "config show" prints the configuration with the origin of every value.
|
||||||
|
// A program merged from several inputs (a family-wide file, a section
|
||||||
|
// of it, its own file) sets Spec.Layered so that path, validate and show
|
||||||
|
// work on all of them (see Layered).
|
||||||
|
//
|
||||||
// The package does not depend on cobra: a cobra program wires Run into
|
// The package does not depend on cobra: a cobra program wires Run into
|
||||||
// a command with flag parsing disabled, taking --config out of the
|
// a command with flag parsing disabled, taking --config out of the
|
||||||
// arguments itself, the same way it wires core/doctor.
|
// arguments itself, the same way it wires core/doctor.
|
||||||
@@ -113,6 +119,12 @@ type Spec struct {
|
|||||||
// Options are passed through to core/config; tests use them to
|
// Options are passed through to core/config; tests use them to
|
||||||
// inject a platform, environment, root and working directory.
|
// inject a platform, environment, root and working directory.
|
||||||
Options []coreconfig.Option
|
Options []coreconfig.Option
|
||||||
|
|
||||||
|
// Layered, when set, makes path, validate and show work on a
|
||||||
|
// configuration merged from several inputs (see Layered); create
|
||||||
|
// and upgrade still work on Filename. nil: the program reads the
|
||||||
|
// single file Find selects.
|
||||||
|
Layered *Layered
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Spec) filename() string {
|
func (s Spec) filename() string {
|
||||||
@@ -131,7 +143,7 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
|||||||
}
|
}
|
||||||
sub, rest := args[0], args[1:]
|
sub, rest := args[0], args[1:]
|
||||||
switch sub {
|
switch sub {
|
||||||
case "create", "validate", "upgrade", "path":
|
case "create", "validate", "upgrade", "path", "show":
|
||||||
if s.None {
|
if s.None {
|
||||||
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
||||||
return ExitOK
|
return ExitOK
|
||||||
@@ -141,11 +153,25 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
|||||||
case "create":
|
case "create":
|
||||||
return s.create(explicit, rest, stdout, stderr)
|
return s.create(explicit, rest, stdout, stderr)
|
||||||
case "validate":
|
case "validate":
|
||||||
|
if s.Layered != nil {
|
||||||
|
if code := parse(s.newFlagSet("validate", stderr), rest); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
return s.layeredValidate(explicit, stdout, stderr)
|
||||||
|
}
|
||||||
return s.validate(explicit, rest, stdout, stderr)
|
return s.validate(explicit, rest, stdout, stderr)
|
||||||
case "upgrade":
|
case "upgrade":
|
||||||
return s.upgrade(explicit, rest, stdout, stderr)
|
return s.upgrade(explicit, rest, stdout, stderr)
|
||||||
case "path":
|
case "path":
|
||||||
|
if s.Layered != nil {
|
||||||
|
if code := parse(s.newFlagSet("path", stderr), rest); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
return s.layeredPath(explicit, stdout, stderr)
|
||||||
|
}
|
||||||
return s.path(explicit, rest, stdout, stderr)
|
return s.path(explicit, rest, stdout, stderr)
|
||||||
|
case "show":
|
||||||
|
return s.show(explicit, rest, stdout, stderr)
|
||||||
case "help", "-h", "-help", "--help":
|
case "help", "-h", "-help", "--help":
|
||||||
usage(s, stdout)
|
usage(s, stdout)
|
||||||
return ExitOK
|
return ExitOK
|
||||||
@@ -158,9 +184,13 @@ func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
|||||||
|
|
||||||
// Subcommands are the config subcommands, for a program's completion
|
// Subcommands are the config subcommands, for a program's completion
|
||||||
// tree and help text.
|
// tree and help text.
|
||||||
var Subcommands = []string{"create", "validate", "upgrade", "path"}
|
var Subcommands = []string{"create", "validate", "upgrade", "path", "show"}
|
||||||
|
|
||||||
func usage(s Spec, w io.Writer) {
|
func usage(s Spec, w io.Writer) {
|
||||||
|
pathHelp := "list the locations searched for " + s.filename() + ", highest priority first"
|
||||||
|
if s.Layered != nil {
|
||||||
|
pathHelp = "list every configuration layer, highest priority first"
|
||||||
|
}
|
||||||
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
||||||
|
|
||||||
create [--minimal|--full] [--force] [--output <file>]
|
create [--minimal|--full] [--force] [--output <file>]
|
||||||
@@ -169,8 +199,11 @@ func usage(s Spec, w io.Writer) {
|
|||||||
upgrade [--write]
|
upgrade [--write]
|
||||||
show the options of "create --full" the file does not mention
|
show the options of "create --full" the file does not mention
|
||||||
yet, as commented blocks; --write adds them to the file
|
yet, as commented blocks; --write adds them to the file
|
||||||
path list the locations searched for %[2]s, highest priority first
|
path %[3]s
|
||||||
`, s.Name, s.filename())
|
show [--json] [--show-secrets]
|
||||||
|
print the configuration with the file every value comes from;
|
||||||
|
secrets are redacted unless --show-secrets
|
||||||
|
`, s.Name, s.filename(), pathHelp)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newFlagSet returns a flag set for one subcommand whose usage errors go
|
// newFlagSet returns a flag set for one subcommand whose usage errors go
|
||||||
|
|||||||
@@ -0,0 +1,301 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
coreconfig "yetano.dev/yetano/core/config"
|
||||||
|
"yetano.dev/yetano/core/doctor"
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Layered describes a program whose configuration is merged from
|
||||||
|
// several inputs that are not one file name per directory -- e.g. a
|
||||||
|
// family-wide file, one section of it and a per-program file in every
|
||||||
|
// tier (the yamase family, yamase ADR-0074). With Spec.Layered set,
|
||||||
|
// "config path", "config validate" and "config show" work on all
|
||||||
|
// layers; "config create" and "config upgrade" keep working on the
|
||||||
|
// program's own file (Spec.Filename).
|
||||||
|
//
|
||||||
|
// Unknown options are warnings for a layered program, not problems:
|
||||||
|
// files shared between programs (of different versions) legitimately
|
||||||
|
// carry options one program does not read.
|
||||||
|
type Layered struct {
|
||||||
|
// Layers lists every input, highest priority first, whether it
|
||||||
|
// exists or not (for "config path" and doctor). explicit is the
|
||||||
|
// --config value.
|
||||||
|
Layers func(explicit string) ([]LayerInfo, error)
|
||||||
|
|
||||||
|
// Load merges the existing layers. With none at all it returns an
|
||||||
|
// error wrapping ErrNotFound.
|
||||||
|
Load func(explicit string) (*Effective, error)
|
||||||
|
|
||||||
|
// Unknown reports the unknown options of e's layers. nil: every
|
||||||
|
// existing layer's file is checked against Spec.Schema.
|
||||||
|
Unknown func(e *Effective) ([]UnknownKey, error)
|
||||||
|
|
||||||
|
// Validate parses and validates the merged configuration (YAML) the
|
||||||
|
// way the program does at startup, including files it names.
|
||||||
|
Validate func(merged []byte) error
|
||||||
|
|
||||||
|
// Used reports whether the program reads the option key, for "config
|
||||||
|
// show". nil: KnownKey(Spec.Schema, key).
|
||||||
|
Used func(key string) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// LayerInfo is one input of a layered configuration.
|
||||||
|
type LayerInfo struct {
|
||||||
|
// Name is how the layer is shown and recorded as an origin: the
|
||||||
|
// path, plus e.g. " [section]" for a part of a file.
|
||||||
|
Name string
|
||||||
|
// Path is the file that holds it.
|
||||||
|
Path string
|
||||||
|
// Source names the tier ("system-directory", "--config", ...).
|
||||||
|
Source string
|
||||||
|
// Exists reports whether the layer contributes anything.
|
||||||
|
Exists bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effective is a merged configuration: its layers, the merged mapping
|
||||||
|
// and the origin (LayerInfo.Name, or a default's name) of every leaf.
|
||||||
|
type Effective struct {
|
||||||
|
// Name is the program's name, for "config show"'s header.
|
||||||
|
Name string
|
||||||
|
// Layers are all layers, highest priority first.
|
||||||
|
Layers []LayerInfo
|
||||||
|
Merged map[string]any
|
||||||
|
Origins coreconfig.Origins
|
||||||
|
// Loader is the Layered loader's own value for this configuration
|
||||||
|
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
|
||||||
|
Loader any
|
||||||
|
}
|
||||||
|
|
||||||
|
// Used returns the layers that contributed, highest priority first.
|
||||||
|
func (e *Effective) Used() []LayerInfo {
|
||||||
|
var out []LayerInfo
|
||||||
|
for _, l := range e.Layers {
|
||||||
|
if l.Exists {
|
||||||
|
out = append(out, l)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Describe names the layers that contributed, lowest priority first
|
||||||
|
// ("a.yaml + b.yaml [section]"), for log lines and messages.
|
||||||
|
func (e *Effective) Describe() string {
|
||||||
|
used := e.Used()
|
||||||
|
names := make([]string, len(used))
|
||||||
|
for i, l := range used {
|
||||||
|
names[len(used)-1-i] = l.Name
|
||||||
|
}
|
||||||
|
return strings.Join(names, " + ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// YAML returns the merged configuration as YAML, for the program's own
|
||||||
|
// parser.
|
||||||
|
func (e *Effective) YAML() ([]byte, error) {
|
||||||
|
data, err := yaml.Marshal(e.Merged)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("config: marshal merged configuration: %w", err)
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// effective loads the configuration "config show" and Doctor report:
|
||||||
|
// Layered.Load, or else the single file Find selects as the only layer.
|
||||||
|
func (s Spec) effective(explicit string) (*Effective, error) {
|
||||||
|
if s.Layered != nil {
|
||||||
|
return s.Layered.Load(explicit)
|
||||||
|
}
|
||||||
|
file, err := s.Find(explicit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := coreconfig.ReadFile(file.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
merged, origins := coreconfig.Merge(coreconfig.Source{Name: file.Path, Data: data})
|
||||||
|
src := file.Source.String()
|
||||||
|
return &Effective{
|
||||||
|
Name: s.Name,
|
||||||
|
Layers: []LayerInfo{{Name: file.Path, Path: file.Path, Source: src, Exists: true}},
|
||||||
|
Merged: merged,
|
||||||
|
Origins: origins,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnknownIn returns the unknown options of e's layers: Layered.Unknown
|
||||||
|
// if set, else every existing layer's file against s.Schema.
|
||||||
|
func (s Spec) UnknownIn(e *Effective) ([]UnknownKey, error) {
|
||||||
|
if s.Layered != nil && s.Layered.Unknown != nil {
|
||||||
|
return s.Layered.Unknown(e)
|
||||||
|
}
|
||||||
|
if s.Schema == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var out []UnknownKey
|
||||||
|
for i := len(e.Layers) - 1; i >= 0; i-- {
|
||||||
|
l := e.Layers[i]
|
||||||
|
if !l.Exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
keys, err := UnknownKeysFile(l.Path, s.Schema)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
k.Layer = l.Name
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) layeredPath(explicit string, stdout, stderr io.Writer) int {
|
||||||
|
layers, err := s.Layered.Layers(explicit)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config path: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, l := range layers {
|
||||||
|
mark, state := " ", "missing"
|
||||||
|
if l.Exists {
|
||||||
|
mark, state, found = "*", "used", true
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s %s (%s, %s)\n", mark, l.Name, l.Source, state)
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- \"%s config create\" writes one\n", s.Name)
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) layeredValidate(explicit string, stdout, stderr io.Writer) int {
|
||||||
|
e, err := s.Layered.Load(explicit)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
unknown, err := s.UnknownIn(e)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
for _, k := range unknown {
|
||||||
|
fmt.Fprintf(stdout, "warning: unknown option %s (%s, line %d), ignored -- the default applies\n", k.Key, k.Layer, k.Line)
|
||||||
|
}
|
||||||
|
if s.Layered.Validate != nil {
|
||||||
|
data, err := e.YAML()
|
||||||
|
if err == nil {
|
||||||
|
err = s.Layered.Validate(data)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config validate: %s: %v\n", s.Name, e.Describe(), err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "%s: valid\n", e.Describe())
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||||
|
fs := s.newFlagSet("show", stderr)
|
||||||
|
asJSON := fs.Bool("json", false, "print a JSON array of {key, value, source, used}")
|
||||||
|
secrets := fs.Bool("show-secrets", false, "print secret values instead of <redacted>")
|
||||||
|
if code := parse(fs, args); code >= 0 {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
e, err := s.effective(explicit)
|
||||||
|
if err != nil {
|
||||||
|
if s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
|
||||||
|
fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults\n", s.Name)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
used := s.usedFunc()
|
||||||
|
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
||||||
|
return ExitProblem
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// usedFunc is Layered.Used, else KnownKey against the schema (every key
|
||||||
|
// counts as used without one).
|
||||||
|
func (s Spec) usedFunc() func(string) bool {
|
||||||
|
if s.Layered != nil && s.Layered.Used != nil {
|
||||||
|
return s.Layered.Used
|
||||||
|
}
|
||||||
|
if s.Schema == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return func(key string) bool { return KnownKey(s.Schema, key) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Doctor records the program's core/paths locations and every
|
||||||
|
// configuration layer in r, checks that the configuration loads and has
|
||||||
|
// no unknown options, and returns it (nil when it does not load).
|
||||||
|
// Nothing is created. A layered program's unknown options are reported
|
||||||
|
// as a failed check like any program's: doctor is where an operator
|
||||||
|
// looks for them.
|
||||||
|
func Doctor(r *doctor.Report, s Spec, explicit string) *Effective {
|
||||||
|
r.AddPaths(s.App)
|
||||||
|
if s.Layered != nil {
|
||||||
|
layers, err := s.Layered.Layers(explicit)
|
||||||
|
if err != nil {
|
||||||
|
r.AddPath("config search", "", err)
|
||||||
|
}
|
||||||
|
for _, l := range layers {
|
||||||
|
name := "config search (" + l.Source + ")"
|
||||||
|
if l.Exists {
|
||||||
|
name = "config file (" + l.Source + ")"
|
||||||
|
}
|
||||||
|
r.AddPath(name, l.Name, nil)
|
||||||
|
}
|
||||||
|
} else if layers, err := s.Layers(explicit); err != nil {
|
||||||
|
r.AddPath("config search", "", err)
|
||||||
|
} else {
|
||||||
|
for _, l := range layers {
|
||||||
|
src := l.Source.String()
|
||||||
|
if l.Source == paths.APIOverride {
|
||||||
|
src = "--config"
|
||||||
|
}
|
||||||
|
r.AddPath("config search ("+src+")", l.Path, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e, err := s.effective(explicit)
|
||||||
|
if err != nil {
|
||||||
|
note := err.Error()
|
||||||
|
if errors.Is(err, ErrNotFound) {
|
||||||
|
note = "none of the searched files exists; pass --config <file> or run \"" + s.Name + " config create\""
|
||||||
|
}
|
||||||
|
r.Check("config file found", false, note)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
r.Check("config file found", true, e.Describe())
|
||||||
|
if s.Schema != nil || (s.Layered != nil && s.Layered.Unknown != nil) {
|
||||||
|
unknown, err := s.UnknownIn(e)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
r.Check("config has no unknown options", false, err.Error())
|
||||||
|
case len(unknown) == 0:
|
||||||
|
r.Check("config has no unknown options", true, "")
|
||||||
|
default:
|
||||||
|
parts := make([]string, len(unknown))
|
||||||
|
for i, k := range unknown {
|
||||||
|
parts[i] = k.String()
|
||||||
|
}
|
||||||
|
r.Check("config has no unknown options", false, "ignored, the defaults apply: "+strings.Join(parts, ", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
coreconfig "yetano.dev/yetano/core/config"
|
||||||
|
"yetano.dev/yetano/core/doctor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestShowSingleFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
file := filepath.Join(root, "etc", "yamase", "yamase-test.yaml")
|
||||||
|
writeFile(t, file, minimalTemplate+"log-level: debug\nunread: 1\n")
|
||||||
|
code, out, errOut := run(t, s, "", "show")
|
||||||
|
if code != ExitOK {
|
||||||
|
t.Fatalf("show: exit %d: %s", code, errOut)
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
`log-level: "debug"`,
|
||||||
|
"# " + file,
|
||||||
|
`root: "/var/lib/yamase/queue"`,
|
||||||
|
"unread: 1",
|
||||||
|
"not used by yamase-test",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("show output lacks %q:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
code, out, _ = run(t, s, "", "show", "--json")
|
||||||
|
var values []Value
|
||||||
|
if code != ExitOK || json.Unmarshal([]byte(out), &values) != nil || len(values) == 0 {
|
||||||
|
t.Errorf("show --json: exit %d, output %q", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeLayered serves two layers of one directory, as a family-wide file
|
||||||
|
// plus a program file.
|
||||||
|
func fakeLayered(dir string) *Layered {
|
||||||
|
shared := filepath.Join(dir, "family.yaml")
|
||||||
|
own := filepath.Join(dir, "own.yaml")
|
||||||
|
layers := func(string) ([]LayerInfo, error) {
|
||||||
|
return []LayerInfo{
|
||||||
|
{Name: own, Path: own, Source: "test", Exists: statOK(own)},
|
||||||
|
{Name: shared, Path: shared, Source: "test", Exists: statOK(shared)},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return &Layered{
|
||||||
|
Layers: layers,
|
||||||
|
Load: func(explicit string) (*Effective, error) {
|
||||||
|
ls, _ := layers(explicit)
|
||||||
|
var sources []coreconfig.Source
|
||||||
|
for i := len(ls) - 1; i >= 0; i-- {
|
||||||
|
if !ls[i].Exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := coreconfig.ReadFile(ls[i].Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sources = append(sources, coreconfig.Source{Name: ls[i].Name, Data: data})
|
||||||
|
}
|
||||||
|
if len(sources) == 0 {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
merged, origins := coreconfig.Merge(sources...)
|
||||||
|
return &Effective{Name: "yamase-test", Layers: ls, Merged: merged, Origins: origins}, nil
|
||||||
|
},
|
||||||
|
Validate: func(merged []byte) error {
|
||||||
|
var s schema
|
||||||
|
if err := yaml.Unmarshal(merged, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(s.Listen) == 0 {
|
||||||
|
return errNoListener
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type testErr string
|
||||||
|
|
||||||
|
func (e testErr) Error() string { return string(e) }
|
||||||
|
|
||||||
|
const errNoListener = testErr("listen: at least one listener is required")
|
||||||
|
|
||||||
|
func statOK(path string) bool { return statExistsForTest(path) }
|
||||||
|
|
||||||
|
func TestLayered(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
dir := filepath.Join(root, "cfg")
|
||||||
|
s := testSpec(root)
|
||||||
|
s.Layered = fakeLayered(dir)
|
||||||
|
|
||||||
|
if code, out, _ := run(t, s, "", "path"); code != ExitOK || !strings.Contains(out, "no configuration file found") {
|
||||||
|
t.Errorf("path without files: exit %d, %q", code, out)
|
||||||
|
}
|
||||||
|
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, ErrNotFound.Error()) {
|
||||||
|
t.Errorf("validate without files: exit %d, %q", code, errOut)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\nlisten:\n - address: \":25\"\n")
|
||||||
|
writeFile(t, filepath.Join(dir, "own.yaml"), "log-level: debug\nlog-levle: x\n")
|
||||||
|
|
||||||
|
code, out, _ := run(t, s, "", "path")
|
||||||
|
if code != ExitOK || strings.Count(out, "(test, used)") != 2 {
|
||||||
|
t.Errorf("path: exit %d, %q", code, out)
|
||||||
|
}
|
||||||
|
// Unknown options are warnings for a layered program.
|
||||||
|
code, out, errOut := run(t, s, "", "validate")
|
||||||
|
if code != ExitOK || !strings.Contains(out, "warning: unknown option log-levle ("+filepath.Join(dir, "own.yaml")+", line 2)") || !strings.Contains(out, ": valid") {
|
||||||
|
t.Errorf("validate: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
code, out, _ = run(t, s, "", "show")
|
||||||
|
if code != ExitOK || !strings.Contains(out, `log-level: "debug"`) || !strings.Contains(out, "# "+filepath.Join(dir, "family.yaml")) {
|
||||||
|
t.Errorf("show: exit %d:\n%s", code, out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "layers, lowest priority first: "+filepath.Join(dir, "family.yaml")+" + "+filepath.Join(dir, "own.yaml")) {
|
||||||
|
t.Errorf("show header:\n%s", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeFile(t, filepath.Join(dir, "family.yaml"), "log-level: info\n")
|
||||||
|
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "listen") {
|
||||||
|
t.Errorf("validate of an invalid merge: exit %d, %q", code, errOut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDoctor(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
r := doctor.Report{Program: "yamase-test"}
|
||||||
|
if e := Doctor(&r, s, ""); e != nil {
|
||||||
|
t.Error("Doctor without a file returned a configuration")
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-levle: x\n")
|
||||||
|
r = doctor.Report{Program: "yamase-test"}
|
||||||
|
e := Doctor(&r, s, "")
|
||||||
|
if e == nil {
|
||||||
|
t.Fatal("Doctor with a file returned nil")
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
r.Run([]string{"--json"}, &out, &out)
|
||||||
|
if !strings.Contains(out.String(), "log-levle (") || !strings.Contains(out.String(), "config file found") {
|
||||||
|
t.Errorf("doctor report = %s", out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValuesRedaction(t *testing.T) {
|
||||||
|
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
|
||||||
|
"srs": map[string]any{"secrets": []any{"plain", "env:X", "base64:abc"}},
|
||||||
|
"yaais": map[string]any{"token": "file:/run/t", "password": "hunter2"},
|
||||||
|
}})
|
||||||
|
e := &Effective{Name: "p", Merged: merged, Origins: origins}
|
||||||
|
got := map[string]any{}
|
||||||
|
for _, v := range e.Values(nil, false) {
|
||||||
|
got[v.Key] = v.Value
|
||||||
|
}
|
||||||
|
want := map[string]any{
|
||||||
|
"srs.secrets": []any{"<redacted>", "env:X", "<redacted>"},
|
||||||
|
"yaais.token": "file:/run/t",
|
||||||
|
"yaais.password": "<redacted>",
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Values = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type inlineBase struct {
|
||||||
|
Enabled bool `yaml:"enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKnownKey(t *testing.T) {
|
||||||
|
type cfg struct {
|
||||||
|
Throttle struct {
|
||||||
|
inlineBase `yaml:",inline"`
|
||||||
|
Window string `yaml:"window"`
|
||||||
|
} `yaml:"throttle"`
|
||||||
|
Listen []struct {
|
||||||
|
Address string `yaml:"address"`
|
||||||
|
} `yaml:"listen"`
|
||||||
|
Backends map[string]struct{ Root string } `yaml:"backends"`
|
||||||
|
Custom selfDecoding `yaml:"custom"`
|
||||||
|
}
|
||||||
|
for key, want := range map[string]bool{
|
||||||
|
"throttle.enabled": true,
|
||||||
|
"throttle.window": true,
|
||||||
|
"throttle.nope": false,
|
||||||
|
"listen[0].address": true,
|
||||||
|
"listen[].address": true,
|
||||||
|
"backends.any.root": true,
|
||||||
|
"backends.any.nope": false,
|
||||||
|
"custom.anything": true,
|
||||||
|
"missing": false,
|
||||||
|
} {
|
||||||
|
if got := KnownKey(cfg{}, key); got != want {
|
||||||
|
t.Errorf("KnownKey(%q) = %v, want %v", key, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func statExistsForTest(path string) bool {
|
||||||
|
_, err := os.Stat(path)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package configcmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Value is one leaf of a merged configuration, as "config show" reports
|
||||||
|
// it.
|
||||||
|
type Value struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Value any `json:"value"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
// Used reports whether the program reads this option; an option in a
|
||||||
|
// shared file that only other programs read has Used false.
|
||||||
|
Used bool `json:"used"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultOrigin is the origin of a leaf no layer set (a value a loader
|
||||||
|
// filled in).
|
||||||
|
const DefaultOrigin = "default"
|
||||||
|
|
||||||
|
// Values returns every leaf of e, sorted by key, with its origin.
|
||||||
|
// used reports whether the program reads a key (nil: every key); a
|
||||||
|
// default it does not read is left out. Secret values (keys secrets,
|
||||||
|
// secret, token, password) are replaced by "<redacted>" unless
|
||||||
|
// showSecrets; a reference that only says where a secret is (env:,
|
||||||
|
// file:, secret://) is shown.
|
||||||
|
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
|
||||||
|
var out []Value
|
||||||
|
walkLeaves("", e.Merged, func(key string, v any) {
|
||||||
|
source := e.Origins[key]
|
||||||
|
if source == "" {
|
||||||
|
source = DefaultOrigin
|
||||||
|
}
|
||||||
|
u := used == nil || used(key)
|
||||||
|
if !u && source == DefaultOrigin {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !showSecrets && isSecretKey(key) {
|
||||||
|
v = redact(v)
|
||||||
|
}
|
||||||
|
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show writes the merged configuration: indented YAML with every
|
||||||
|
// value's origin as a comment, or with asJSON a JSON array of Values.
|
||||||
|
func (e *Effective) Show(w io.Writer, used func(string) bool, asJSON, showSecrets bool) error {
|
||||||
|
values := e.Values(used, showSecrets)
|
||||||
|
if asJSON {
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(values)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "# %s: effective configuration\n# layers, lowest priority first: %s\n", e.Name, e.Describe())
|
||||||
|
var printed []string // the parent path last printed, by depth
|
||||||
|
for _, v := range values {
|
||||||
|
parts := strings.Split(v.Key, ".")
|
||||||
|
for depth, name := range parts[:len(parts)-1] {
|
||||||
|
if depth < len(printed) && printed[depth] == name {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
printed = append(printed[:depth], name)
|
||||||
|
fmt.Fprintf(w, "%s%s:\n", strings.Repeat(" ", depth), name)
|
||||||
|
}
|
||||||
|
printed = printed[:len(parts)-1]
|
||||||
|
line := fmt.Sprintf("%s%s: %s", strings.Repeat(" ", len(parts)-1), parts[len(parts)-1], renderValue(v.Value))
|
||||||
|
note := v.Source
|
||||||
|
if !v.Used {
|
||||||
|
note += ", not used by " + e.Name
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "%s%s# %s\n", line, strings.Repeat(" ", max(44-len(line), 1)), note)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func walkLeaves(prefix string, m map[string]any, fn func(string, any)) {
|
||||||
|
keys := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
key := k
|
||||||
|
if prefix != "" {
|
||||||
|
key = prefix + "." + k
|
||||||
|
}
|
||||||
|
if sub, ok := m[k].(map[string]any); ok && len(sub) > 0 {
|
||||||
|
walkLeaves(key, sub, fn)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fn(key, m[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderValue formats a leaf as a single-line YAML value (JSON is a subset
|
||||||
|
// of YAML's flow style).
|
||||||
|
func renderValue(v any) string {
|
||||||
|
var b strings.Builder
|
||||||
|
enc := json.NewEncoder(&b)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
if err := enc.Encode(v); err != nil {
|
||||||
|
return fmt.Sprint(v)
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(b.String(), "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true, "password": true}
|
||||||
|
|
||||||
|
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
|
||||||
|
|
||||||
|
// redact replaces secret values, keeping references that only say where
|
||||||
|
// the secret is.
|
||||||
|
func redact(v any) any {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case string:
|
||||||
|
for _, ref := range []string{"env:", "file:", "secret://"} {
|
||||||
|
if strings.HasPrefix(x, ref) {
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "<redacted>"
|
||||||
|
case []any:
|
||||||
|
out := make([]any, len(x))
|
||||||
|
for i, e := range x {
|
||||||
|
out[i] = redact(e)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
return "<redacted>"
|
||||||
|
}
|
||||||
|
|
||||||
|
// listIndex matches the "[n]" (or "[]") of a list entry in a dotted key.
|
||||||
|
var listIndex = regexp.MustCompile(`\[\d*\]`)
|
||||||
|
|
||||||
|
// KnownKey reports whether the dotted option key ("storage.inbound.root",
|
||||||
|
// "listen[0].address") exists in schema (a configuration struct) by its
|
||||||
|
// yaml tags. A map accepts any key; a list, an interface or a type that
|
||||||
|
// decodes itself accepts everything below it; an embedded ",inline"
|
||||||
|
// struct contributes its fields.
|
||||||
|
func KnownKey(schema any, key string) bool {
|
||||||
|
if schema == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return knownPath(reflect.TypeOf(schema), strings.Split(listIndex.ReplaceAllString(key, ""), "."))
|
||||||
|
}
|
||||||
|
|
||||||
|
func knownPath(t reflect.Type, path []string) bool {
|
||||||
|
t = deref(t)
|
||||||
|
if len(path) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch t.Kind() {
|
||||||
|
case reflect.Struct:
|
||||||
|
ft, ok := fieldType(t, path[0])
|
||||||
|
return ok && knownPath(ft, path[1:])
|
||||||
|
case reflect.Map:
|
||||||
|
return knownPath(t.Elem(), path[1:])
|
||||||
|
case reflect.Interface, reflect.Slice, reflect.Array:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -19,9 +19,17 @@ type UnknownKey struct {
|
|||||||
// entries of a list are "listen[1].tls".
|
// entries of a list are "listen[1].tls".
|
||||||
Key string
|
Key string
|
||||||
Line int
|
Line int
|
||||||
|
// Layer names the layer the key is in, for a layered configuration
|
||||||
|
// (LayerInfo.Name); "" for a single file.
|
||||||
|
Layer string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k UnknownKey) String() string { return fmt.Sprintf("%s (line %d)", k.Key, k.Line) }
|
func (k UnknownKey) String() string {
|
||||||
|
if k.Layer != "" {
|
||||||
|
return fmt.Sprintf("%s (%s, line %d)", k.Key, k.Layer, k.Line)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s (line %d)", k.Key, k.Line)
|
||||||
|
}
|
||||||
|
|
||||||
// UnknownKeys lists the keys of raw that schema (the program's
|
// UnknownKeys lists the keys of raw that schema (the program's
|
||||||
// configuration struct, e.g. config.Config{}) has no field for, by its
|
// configuration struct, e.g. config.Config{}) has no field for, by its
|
||||||
|
|||||||
@@ -74,12 +74,12 @@ Ignored: x
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
want := []UnknownKey{
|
want := []UnknownKey{
|
||||||
{"log-levle", 2},
|
{Key: "log-levle", Line: 2},
|
||||||
{"listen[0].tsl", 5},
|
{Key: "listen[0].tsl", Line: 5},
|
||||||
{"storage.mailstore.rot", 9},
|
{Key: "storage.mailstore.rot", Line: 9},
|
||||||
{"backends.inbound.extra", 11},
|
{Key: "backends.inbound.extra", Line: 11},
|
||||||
{"throttle.enabeld", 15},
|
{Key: "throttle.enabeld", Line: 15},
|
||||||
{"Ignored", 18},
|
{Key: "Ignored", Line: 18},
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(got, want) {
|
if !reflect.DeepEqual(got, want) {
|
||||||
t.Fatalf("UnknownKeys =\n%v\nwant\n%v", got, want)
|
t.Fatalf("UnknownKeys =\n%v\nwant\n%v", got, want)
|
||||||
|
|||||||
Reference in new issue
Block a user