configcmd and version: the config and version standard commands; darwin /var/run
core/configcmd: "<program> config create|validate|upgrade|path" from a Spec (name, application, minimal/full templates, Validate, Schema), taken over from yamase-core/pkg/configcmd and generalized: Filename, Optional (programs that run on defaults) and None (no configuration). core/version: "<program> version [--json]" over the values each program stamps into its internal/version; JSON keys match yasta's existing output (yavebu reads it), VCS fallback for unstamped builds. paths: macOS CLI/Service system-scope RuntimeDir is /var/run/<app> instead of /run/<app>, which macOS does not have. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ca0f06f978
commit
90132e2d76
13 files changed
+1824
-20
No files matched your search
@@ -0,0 +1,466 @@
|
||||
// Package configcmd is the shared "<program> config" command of the
|
||||
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
|
||||
// the yetano meta-repository):
|
||||
//
|
||||
// <program> config create [--minimal|--full] [--force] [--output <file>]
|
||||
// <program> config validate
|
||||
// <program> config upgrade [--write]
|
||||
// <program> config path
|
||||
//
|
||||
// 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
|
||||
// core.Application (which determine the file name and the directories
|
||||
// searched), its two templates (a minimal one that is just enough to be
|
||||
// valid, and a full one documenting every option), and the function
|
||||
// that loads and validates a file. The schema itself stays in each
|
||||
// program's own config package.
|
||||
//
|
||||
// var configSpec = configcmd.Spec{
|
||||
// Name: "yasl", App: app,
|
||||
// Minimal: config.MinimalTemplate, Full: config.FullTemplate,
|
||||
// Validate: func(path string) error { _, err := config.Load(path); return err },
|
||||
// Schema: config.Config{},
|
||||
// }
|
||||
//
|
||||
// case "config":
|
||||
// os.Exit(configcmd.Run(configSpec, configFlag, args[1:], os.Stdout, os.Stderr))
|
||||
//
|
||||
// A program's tests call UndocumentedKeys with its full template so a
|
||||
// new option cannot be added without documenting it -- that is what
|
||||
// keeps "config upgrade" useful. create/upgrade/unknown-key detection
|
||||
// work on YAML files.
|
||||
//
|
||||
// Exit codes: 0 success, 1 the command ran and found a problem (invalid
|
||||
// configuration, no file found, refusing to overwrite), 2 usage error.
|
||||
//
|
||||
// The package does not depend on cobra: a cobra program wires Run into
|
||||
// a command with flag parsing disabled, taking --config out of the
|
||||
// arguments itself, the same way it wires core/doctor.
|
||||
package configcmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core"
|
||||
coreconfig "yetano.dev/yetano/core/config"
|
||||
"yetano.dev/yetano/core/paths"
|
||||
)
|
||||
|
||||
// Exit codes, matching core/doctor's.
|
||||
const (
|
||||
ExitOK = 0
|
||||
ExitProblem = 1
|
||||
ExitUsage = 2
|
||||
)
|
||||
|
||||
// ErrNotFound is returned (wrapped, with the list of searched
|
||||
// locations) by Find when no explicit path was given and no location
|
||||
// has the file.
|
||||
var ErrNotFound = errors.New("no configuration file found")
|
||||
|
||||
// Spec is one program's part of the config command.
|
||||
type Spec struct {
|
||||
// Name is the program's own name, used in messages ("yasl",
|
||||
// "yamase-smtpd").
|
||||
Name string
|
||||
|
||||
// App determines the directories searched (core/config). Programs
|
||||
// of one family may share an App and differ only in Filename.
|
||||
App core.Application
|
||||
|
||||
// Filename is the file searched for in every location; default
|
||||
// "<Name>.yaml".
|
||||
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.
|
||||
Optional bool
|
||||
|
||||
// None says the program has no configuration at all; every
|
||||
// subcommand says so (the standard still requires the command).
|
||||
None bool
|
||||
|
||||
// Minimal is the template "config create" writes by default: just
|
||||
// enough to be valid, with placeholder values an operator adjusts.
|
||||
Minimal string
|
||||
|
||||
// Full is the template "config create --full" writes, documenting
|
||||
// every option. "config upgrade" offers the options of Full a file
|
||||
// does not mention yet, so every key the program reads should be in
|
||||
// it (see UndocumentedKeys).
|
||||
Full string
|
||||
|
||||
// Validate loads and validates the configuration the same way the
|
||||
// program does at startup, including files it names (TLS key pairs,
|
||||
// ...). path is the file Find selected; "" for an Optional program
|
||||
// without a file (validate the built-in defaults). A program that
|
||||
// merges several layers may ignore path and load its own way.
|
||||
Validate func(path string) error
|
||||
|
||||
// Schema is the program's configuration struct (e.g. config.Config{}).
|
||||
// It enables unknown-option detection in "validate" and tells
|
||||
// "upgrade" which mappings hold operator-named entries rather than
|
||||
// options (see Missing). Optional.
|
||||
Schema any
|
||||
|
||||
// Options are passed through to core/config; tests use them to
|
||||
// inject a platform, environment, root and working directory.
|
||||
Options []coreconfig.Option
|
||||
}
|
||||
|
||||
func (s Spec) filename() string {
|
||||
if s.Filename != "" {
|
||||
return s.Filename
|
||||
}
|
||||
return s.Name + ".yaml"
|
||||
}
|
||||
|
||||
// Run serves "<program> config <args...>" and returns the exit code.
|
||||
// explicit is the program's --config value ("" if not given).
|
||||
func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
usage(s, stderr)
|
||||
return ExitUsage
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "create", "validate", "upgrade", "path":
|
||||
if s.None {
|
||||
fmt.Fprintf(stdout, "%s has no configuration file\n", s.Name)
|
||||
return ExitOK
|
||||
}
|
||||
}
|
||||
switch sub {
|
||||
case "create":
|
||||
return s.create(explicit, rest, stdout, stderr)
|
||||
case "validate":
|
||||
return s.validate(explicit, rest, stdout, stderr)
|
||||
case "upgrade":
|
||||
return s.upgrade(explicit, rest, stdout, stderr)
|
||||
case "path":
|
||||
return s.path(explicit, rest, stdout, stderr)
|
||||
case "help", "-h", "-help", "--help":
|
||||
usage(s, stdout)
|
||||
return ExitOK
|
||||
default:
|
||||
fmt.Fprintf(stderr, "%s config: unknown subcommand %q\n", s.Name, sub)
|
||||
usage(s, stderr)
|
||||
return ExitUsage
|
||||
}
|
||||
}
|
||||
|
||||
// Subcommands are the config subcommands, for a program's completion
|
||||
// tree and help text.
|
||||
var Subcommands = []string{"create", "validate", "upgrade", "path"}
|
||||
|
||||
func usage(s Spec, w io.Writer) {
|
||||
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
||||
|
||||
create [--minimal|--full] [--force] [--output <file>]
|
||||
write a commented starter configuration (minimal by default)
|
||||
validate check the configuration file the program would use
|
||||
upgrade [--write]
|
||||
show the options of "create --full" the file does not mention
|
||||
yet, as commented blocks; --write adds them to the file
|
||||
path list the locations searched for %[2]s, highest priority first
|
||||
`, s.Name, s.filename())
|
||||
}
|
||||
|
||||
// newFlagSet returns a flag set for one subcommand whose usage errors go
|
||||
// to stderr.
|
||||
func (s Spec) newFlagSet(sub string, stderr io.Writer) *flag.FlagSet {
|
||||
fs := flag.NewFlagSet(s.Name+" config "+sub, flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
return fs
|
||||
}
|
||||
|
||||
// parse parses args into fs and maps the outcome to an exit code: -1 to
|
||||
// go on, ExitOK for --help, ExitUsage for anything else that is wrong,
|
||||
// including positional arguments (no subcommand takes any).
|
||||
func parse(fs *flag.FlagSet, args []string) int {
|
||||
if err := fs.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return ExitOK
|
||||
}
|
||||
return ExitUsage
|
||||
}
|
||||
if fs.NArg() != 0 {
|
||||
fmt.Fprintf(fs.Output(), "%s: unexpected argument %q\n", fs.Name(), fs.Arg(0))
|
||||
return ExitUsage
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Layers returns every location searched, highest priority first, the
|
||||
// one in use marked Selected. explicit is the --config value.
|
||||
func (s Spec) Layers(explicit string) ([]coreconfig.Layer, error) {
|
||||
opts := append([]coreconfig.Option{
|
||||
coreconfig.WithExplicitPath(explicit),
|
||||
coreconfig.WithFilename(s.filename()),
|
||||
coreconfig.WithEnvExpansion(false),
|
||||
}, s.Options...)
|
||||
r, err := coreconfig.New(s.App, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
return r.ResolveAll()
|
||||
}
|
||||
|
||||
// Find returns the configuration file the program uses: the explicit
|
||||
// --config path (which must exist), else the highest-priority existing
|
||||
// file. Without one it returns an error wrapping ErrNotFound that lists
|
||||
// the locations searched -- a program that needs a file can print it
|
||||
// as is. Programs use it at startup so "config path" and the program
|
||||
// always agree.
|
||||
func (s Spec) Find(explicit string) (coreconfig.Layer, error) {
|
||||
layers, err := s.Layers(explicit)
|
||||
if err != nil {
|
||||
return coreconfig.Layer{}, err
|
||||
}
|
||||
for _, l := range layers {
|
||||
if l.Selected {
|
||||
return l, nil
|
||||
}
|
||||
}
|
||||
searched := make([]string, len(layers))
|
||||
for i, l := range layers {
|
||||
searched[i] = " " + l.Path
|
||||
}
|
||||
return coreconfig.Layer{}, fmt.Errorf("%w for %s: pass --config <file>, or create one (\"%s config create\" writes a starter file) of (highest priority first):\n%s",
|
||||
ErrNotFound, s.Name, s.Name, strings.Join(searched, "\n"))
|
||||
}
|
||||
|
||||
// find returns the configuration file the program would use. ok is
|
||||
// false after a failure was reported on stderr; path is "" (and ok
|
||||
// true) for an Optional program without a file.
|
||||
func (s Spec) find(explicit, sub string, stderr io.Writer) (path string, ok bool) {
|
||||
file, err := s.Find(explicit)
|
||||
if err != nil {
|
||||
if s.Optional && explicit == "" && errors.Is(err, ErrNotFound) {
|
||||
return "", true
|
||||
}
|
||||
fmt.Fprintf(stderr, "%s config %s: %v\n", s.Name, sub, err)
|
||||
return "", false
|
||||
}
|
||||
return file.Path, true
|
||||
}
|
||||
|
||||
func (s Spec) validate(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
if code := parse(s.newFlagSet("validate", stderr), args); code >= 0 {
|
||||
return code
|
||||
}
|
||||
path, ok := s.find(explicit, "validate", stderr)
|
||||
if !ok {
|
||||
return ExitProblem
|
||||
}
|
||||
if path == "" {
|
||||
if s.Validate != nil {
|
||||
if err := s.Validate(""); 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
|
||||
}
|
||||
code := ExitOK
|
||||
// Unknown keys first: a typo there is often why a value is "wrong".
|
||||
// The program ignores them (it starts and warns), validate fails.
|
||||
if s.Schema != nil {
|
||||
unknown, err := UnknownKeysFile(path, s.Schema)
|
||||
if err == nil && len(unknown) > 0 {
|
||||
for _, k := range unknown {
|
||||
fmt.Fprintf(stderr, "%s: %s: unknown option %s -- ignored, the default applies (a typo? see \"%s config create --full\")\n", s.Name, path, k, s.Name)
|
||||
}
|
||||
code = ExitProblem
|
||||
}
|
||||
}
|
||||
if s.Validate != nil {
|
||||
if err := s.Validate(path); err != nil {
|
||||
fmt.Fprintf(stderr, "%s: configuration %s is invalid: %v\n", s.Name, path, err)
|
||||
return ExitProblem
|
||||
}
|
||||
}
|
||||
if code != ExitOK {
|
||||
fmt.Fprintf(stderr, "%s: configuration %s is otherwise valid, but has unknown options\n", s.Name, path)
|
||||
return code
|
||||
}
|
||||
fmt.Fprintf(stdout, "configuration %s is valid\n", path)
|
||||
return ExitOK
|
||||
}
|
||||
|
||||
func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
fs := s.newFlagSet("create", stderr)
|
||||
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
|
||||
full := fs.Bool("full", false, "write the fully commented reference configuration")
|
||||
force := fs.Bool("force", false, "overwrite the file if it already exists")
|
||||
output := fs.String("output", "", "file to write (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
|
||||
if code := parse(fs, args); code >= 0 {
|
||||
return code
|
||||
}
|
||||
if *minimal && *full {
|
||||
fmt.Fprintf(stderr, "%s config create: --minimal and --full are mutually exclusive\n", s.Name)
|
||||
return ExitUsage
|
||||
}
|
||||
content, kind := s.Minimal, "minimal"
|
||||
if *full || content == "" {
|
||||
content, kind = s.Full, "full"
|
||||
}
|
||||
|
||||
path := *output
|
||||
if path == "" {
|
||||
var err error
|
||||
if path, err = s.defaultCreatePath(explicit); err != nil {
|
||||
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
if !*force {
|
||||
fmt.Fprintf(stderr, "%s config create: %s already exists -- use --force to overwrite it, --output to write somewhere else, or \"%s config upgrade\" to add new options to it\n", s.Name, path, s.Name)
|
||||
return ExitProblem
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
}
|
||||
// 0640: a configuration may name credentials files and should not
|
||||
// be world-readable by default.
|
||||
if err := os.WriteFile(path, []byte(content), 0o640); err != nil {
|
||||
fmt.Fprintf(stderr, "%s config create: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
}
|
||||
fmt.Fprintf(stdout, "%s: wrote %s configuration -- review it, then run \"%s config validate\"\n", path, kind, s.Name)
|
||||
return ExitOK
|
||||
}
|
||||
|
||||
// defaultCreatePath is the explicit --config path, else the file the
|
||||
// program would currently use, else the program's file in the user
|
||||
// config directory -- the system one when running as root, since a
|
||||
// daemon started by root does not look in root's home first by intent.
|
||||
func (s Spec) defaultCreatePath(explicit string) (string, error) {
|
||||
if explicit != "" {
|
||||
return explicit, nil
|
||||
}
|
||||
layers, err := s.Layers("")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var user, system string
|
||||
for _, l := range layers {
|
||||
if l.Selected {
|
||||
return l.Path, nil
|
||||
}
|
||||
switch l.Source {
|
||||
case paths.WorkingDirectory, paths.APIOverride:
|
||||
case paths.SystemDirectory:
|
||||
system = l.Path
|
||||
default:
|
||||
if user == "" {
|
||||
user = l.Path
|
||||
}
|
||||
}
|
||||
}
|
||||
if (os.Geteuid() == 0 || user == "") && system != "" {
|
||||
return system, nil
|
||||
}
|
||||
if user == "" {
|
||||
return "", errors.New("no configuration directory known; pass --output <file>")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s Spec) upgrade(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
fs := s.newFlagSet("upgrade", stderr)
|
||||
write := fs.Bool("write", false, "add the missing options to the file (default: only show them)")
|
||||
if code := parse(fs, args); code >= 0 {
|
||||
return code
|
||||
}
|
||||
path, ok := s.find(explicit, "upgrade", stderr)
|
||||
if !ok {
|
||||
return ExitProblem
|
||||
}
|
||||
if path == "" {
|
||||
fmt.Fprintf(stdout, "no configuration file found -- nothing to upgrade (\"%s config create\" writes one)\n", s.Name)
|
||||
return ExitOK
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s config upgrade: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
}
|
||||
adds, err := Missing(raw, []byte(s.Full), s.Schema)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s config upgrade: %s: %v\n", s.Name, path, err)
|
||||
return ExitProblem
|
||||
}
|
||||
if len(adds) == 0 {
|
||||
fmt.Fprintf(stdout, "%s: already mentions every option this %s version knows about\n", path, s.Name)
|
||||
return ExitOK
|
||||
}
|
||||
keys := make([]string, len(adds))
|
||||
for i, a := range adds {
|
||||
keys[i] = a.Key
|
||||
}
|
||||
if !*write {
|
||||
fmt.Fprintf(stdout, "%s does not mention %d option(s): %s\n", path, len(adds), strings.Join(keys, ", "))
|
||||
fmt.Fprintln(stdout, "These commented blocks would be added (nothing changes until the \"#\" is removed):")
|
||||
for _, a := range adds {
|
||||
where := "at the end of the file"
|
||||
if a.AfterLine > 0 {
|
||||
where = fmt.Sprintf("after line %d", a.AfterLine)
|
||||
}
|
||||
fmt.Fprintf(stdout, "\n# --- %s, %s:\n%s", a.Key, where, a.Text)
|
||||
}
|
||||
fmt.Fprintln(stdout, "\nRun again with --write to apply.")
|
||||
return ExitOK
|
||||
}
|
||||
if err := os.WriteFile(path, Apply(raw, adds), 0o640); err != nil {
|
||||
fmt.Fprintf(stderr, "%s config upgrade: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
}
|
||||
fmt.Fprintf(stdout, "%s: added %d commented option(s): %s\n", path, len(adds), strings.Join(keys, ", "))
|
||||
return ExitOK
|
||||
}
|
||||
|
||||
func (s Spec) path(explicit string, args []string, stdout, stderr io.Writer) int {
|
||||
if code := parse(s.newFlagSet("path", stderr), args); code >= 0 {
|
||||
return code
|
||||
}
|
||||
layers, err := s.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"
|
||||
switch {
|
||||
case l.Selected:
|
||||
mark, state, found = "*", "used", true
|
||||
case l.Exists:
|
||||
state = "exists, shadowed"
|
||||
}
|
||||
src := l.Source.String()
|
||||
if l.Source == paths.APIOverride {
|
||||
src = "--config"
|
||||
}
|
||||
fmt.Fprintf(stdout, "%s %s (%s, %s)\n", mark, l.Path, src, state)
|
||||
}
|
||||
if !found {
|
||||
fmt.Fprintf(stdout, "no configuration file found -- \"%s config create\" writes one\n", s.Name)
|
||||
}
|
||||
return ExitOK
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package configcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
coreconfig "yetano.dev/yetano/core/config"
|
||||
"yetano.dev/yetano/core/paths"
|
||||
|
||||
"yetano.dev/yetano/core"
|
||||
)
|
||||
|
||||
const fullTemplate = `# yamase-test full configuration.
|
||||
|
||||
# Minimum log level: debug, info, warn, error.
|
||||
log-level: info
|
||||
|
||||
listen:
|
||||
- address: "0.0.0.0:25"
|
||||
tls: false
|
||||
|
||||
limits:
|
||||
# Largest message accepted, in bytes.
|
||||
max-message-size-bytes: 52428800
|
||||
# Not yet enforced.
|
||||
connection-rate-per-source: 20
|
||||
|
||||
storage:
|
||||
queue:
|
||||
# Only "filesystem" is implemented.
|
||||
driver: filesystem
|
||||
root: /var/lib/yamase/queue
|
||||
|
||||
tls:
|
||||
cert-file: /etc/yamase/tls/test.crt
|
||||
key-file: /etc/yamase/tls/test.key
|
||||
`
|
||||
|
||||
const minimalTemplate = `listen:
|
||||
- address: "0.0.0.0:25"
|
||||
storage:
|
||||
queue:
|
||||
driver: filesystem
|
||||
root: /var/lib/yamase/queue
|
||||
`
|
||||
|
||||
type schema struct {
|
||||
LogLevel string `yaml:"log-level"`
|
||||
Listen []struct {
|
||||
Address string `yaml:"address"`
|
||||
TLS string `yaml:"tls"`
|
||||
} `yaml:"listen"`
|
||||
Limits struct {
|
||||
MaxMessageSizeBytes int64 `yaml:"max-message-size-bytes"`
|
||||
ConnectionRate int `yaml:"connection-rate-per-source"`
|
||||
} `yaml:"limits"`
|
||||
Storage struct {
|
||||
Queue struct {
|
||||
Driver string `yaml:"driver"`
|
||||
Root string `yaml:"root"`
|
||||
} `yaml:"queue"`
|
||||
} `yaml:"storage"`
|
||||
TLS *struct {
|
||||
CertFile string `yaml:"cert-file"`
|
||||
KeyFile string `yaml:"key-file"`
|
||||
} `yaml:"tls"`
|
||||
}
|
||||
|
||||
func validate(path string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var s schema
|
||||
if err := yaml.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s.Listen) == 0 {
|
||||
return errors.New("listen: at least one listener is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// testSpec returns a Spec for a simulated Linux host rooted at root,
|
||||
// with the working directory at root/work.
|
||||
func testSpec(root string) Spec {
|
||||
return Spec{
|
||||
Name: "yamase-test",
|
||||
App: core.Application{Name: "yamase", Kind: core.Service},
|
||||
Minimal: minimalTemplate,
|
||||
Full: fullTemplate,
|
||||
Validate: validate,
|
||||
Schema: schema{},
|
||||
Options: []coreconfig.Option{
|
||||
coreconfig.WithEnvironment(map[string]string{"HOME": "/home/test"}),
|
||||
coreconfig.WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
|
||||
coreconfig.WithWorkdirPath(filepath.Join(root, "work")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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 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), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsage(t *testing.T) {
|
||||
s := testSpec(t.TempDir())
|
||||
if code, _, _ := run(t, s, ""); code != ExitUsage {
|
||||
t.Errorf("no subcommand: exit %d, want %d", code, ExitUsage)
|
||||
}
|
||||
if code, _, _ := run(t, s, "", "frobnicate"); code != ExitUsage {
|
||||
t.Errorf("unknown subcommand: exit %d, want %d", code, ExitUsage)
|
||||
}
|
||||
if code, _, _ := run(t, s, "", "validate", "extra"); code != ExitUsage {
|
||||
t.Errorf("positional argument: exit %d, want %d", code, ExitUsage)
|
||||
}
|
||||
if code, _, _ := run(t, s, "", "create", "--minimal", "--full"); code != ExitUsage {
|
||||
t.Errorf("--minimal --full: exit %d, want %d", code, ExitUsage)
|
||||
}
|
||||
if code, out, _ := run(t, s, "", "help"); code != ExitOK || !strings.Contains(out, "upgrade") {
|
||||
t.Errorf("help: exit %d, output %q", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDefaultsToUserConfigDir(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("as root, create defaults to the system config dir")
|
||||
}
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
code, _, errOut := run(t, s, "", "create")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("create: exit %d: %s", code, errOut)
|
||||
}
|
||||
want := filepath.Join(root, "home", "test", ".config", "yamase", "yamase-test.yaml")
|
||||
got, err := os.ReadFile(want)
|
||||
if err != nil {
|
||||
t.Fatalf("create did not write %s: %v", want, err)
|
||||
}
|
||||
if string(got) != minimalTemplate {
|
||||
t.Errorf("create wrote %q, want the minimal template", got)
|
||||
}
|
||||
|
||||
// The file now exists: a second create refuses, --force overwrites.
|
||||
if code, _, _ := run(t, s, "", "create", "--full"); code != ExitProblem {
|
||||
t.Errorf("create over an existing file: exit %d, want %d", code, ExitProblem)
|
||||
}
|
||||
if code, _, errOut := run(t, s, "", "create", "--full", "--force"); code != ExitOK {
|
||||
t.Fatalf("create --force: exit %d: %s", code, errOut)
|
||||
}
|
||||
if got, _ := os.ReadFile(want); string(got) != fullTemplate {
|
||||
t.Errorf("create --full --force did not write the full template")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateExplicitAndOutput(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
explicit := filepath.Join(root, "x", "explicit.yaml")
|
||||
if code, _, errOut := run(t, s, explicit, "create"); code != ExitOK {
|
||||
t.Fatalf("create --config: exit %d: %s", code, errOut)
|
||||
}
|
||||
if _, err := os.Stat(explicit); err != nil {
|
||||
t.Errorf("create --config did not write %s: %v", explicit, err)
|
||||
}
|
||||
output := filepath.Join(root, "out.yaml")
|
||||
if code, _, errOut := run(t, s, explicit, "create", "--output", output, "--full"); code != ExitOK {
|
||||
t.Fatalf("create --output: exit %d: %s", code, errOut)
|
||||
}
|
||||
if got, _ := os.ReadFile(output); string(got) != fullTemplate {
|
||||
t.Errorf("create --output --full did not write the full template to --output")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "no configuration file found") {
|
||||
t.Errorf("validate without a file: exit %d, stderr %q", code, errOut)
|
||||
}
|
||||
file := filepath.Join(root, "work", "yamase-test.yaml")
|
||||
writeFile(t, file, "log-level: info\n")
|
||||
if code, _, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "listen") {
|
||||
t.Errorf("validate invalid file: exit %d, stderr %q", code, errOut)
|
||||
}
|
||||
writeFile(t, file, minimalTemplate)
|
||||
if code, out, errOut := run(t, s, "", "validate"); code != ExitOK || !strings.Contains(out, file) {
|
||||
t.Errorf("validate valid file: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||
}
|
||||
// An unknown option fails validate, with its path and line, though
|
||||
// the program itself would start (it ignores the key).
|
||||
writeFile(t, file, minimalTemplate+"log-levle: debug\n")
|
||||
if code, out, errOut := run(t, s, "", "validate"); code != ExitProblem || !strings.Contains(errOut, "unknown option log-levle (line") || strings.Contains(out, "is valid") {
|
||||
t.Errorf("validate with an unknown option: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathNeverCreates(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
code, out, _ := run(t, s, "", "path")
|
||||
if code != ExitOK || !strings.Contains(out, "no configuration file found") {
|
||||
t.Errorf("path: exit %d, output %q", code, out)
|
||||
}
|
||||
for _, f := range []string{"work/yamase-test.yaml", "etc/yamase/yamase-test.yaml"} {
|
||||
if !strings.Contains(out, filepath.Join(root, f)) {
|
||||
t.Errorf("path output does not list %s:\n%s", f, out)
|
||||
}
|
||||
}
|
||||
entries, _ := os.ReadDir(root)
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("path created %d entries under the root", len(entries))
|
||||
}
|
||||
|
||||
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate)
|
||||
if _, out, _ := run(t, s, "", "path"); !strings.Contains(out, "* "+filepath.Join(root, "etc", "yamase", "yamase-test.yaml")) {
|
||||
t.Errorf("path does not mark the used file:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpgradePreviewWriteIdempotent(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
file := filepath.Join(root, "work", "yamase-test.yaml")
|
||||
original := minimalTemplate + "limits:\n max-message-size-bytes: 1000\n"
|
||||
writeFile(t, file, original)
|
||||
|
||||
code, out, errOut := run(t, s, "", "upgrade")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("upgrade: exit %d: %s", code, errOut)
|
||||
}
|
||||
for _, k := range []string{"log-level", "limits.connection-rate-per-source", "tls"} {
|
||||
if !strings.Contains(out, k) {
|
||||
t.Errorf("upgrade preview does not mention %s:\n%s", k, out)
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"storage.queue", "listen[]", "limits.max-message-size-bytes"} {
|
||||
if strings.Contains(out, "# --- "+k) {
|
||||
t.Errorf("upgrade preview offers %s, which the file already has:\n%s", k, out)
|
||||
}
|
||||
}
|
||||
if got, _ := os.ReadFile(file); string(got) != original {
|
||||
t.Fatal("upgrade without --write changed the file")
|
||||
}
|
||||
|
||||
if code, _, errOut := run(t, s, "", "upgrade", "--write"); code != ExitOK {
|
||||
t.Fatalf("upgrade --write: exit %d: %s", code, errOut)
|
||||
}
|
||||
upgraded, _ := os.ReadFile(file)
|
||||
|
||||
// The result still loads, with the same effective values: the
|
||||
// additions are comments only.
|
||||
var before, after schema
|
||||
if err := yaml.Unmarshal([]byte(original), &before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := yaml.Unmarshal(upgraded, &after); err != nil {
|
||||
t.Fatalf("upgraded file does not parse: %v\n%s", err, upgraded)
|
||||
}
|
||||
if !equalYAML(t, before, after) {
|
||||
t.Errorf("upgrade changed the effective configuration:\n%s", upgraded)
|
||||
}
|
||||
if !strings.Contains(string(upgraded), " # Not yet enforced.\n # connection-rate-per-source: 20\n") {
|
||||
t.Errorf("connection-rate-per-source not added into limits: with its comment:\n%s", upgraded)
|
||||
}
|
||||
|
||||
// Running again finds nothing and changes nothing.
|
||||
code, out, _ = run(t, s, "", "upgrade", "--write")
|
||||
if code != ExitOK || !strings.Contains(out, "already mentions every option") {
|
||||
t.Errorf("second upgrade: exit %d, output %q", code, out)
|
||||
}
|
||||
if again, _ := os.ReadFile(file); !bytes.Equal(again, upgraded) {
|
||||
t.Errorf("second upgrade changed the file:\n%s", again)
|
||||
}
|
||||
}
|
||||
|
||||
func equalYAML(t *testing.T, a, b any) bool {
|
||||
t.Helper()
|
||||
ya, _ := yaml.Marshal(a)
|
||||
yb, _ := yaml.Marshal(b)
|
||||
return bytes.Equal(ya, yb)
|
||||
}
|
||||
|
||||
func TestMissingRespectsCommentsAndNonMappings(t *testing.T) {
|
||||
file := `listen:
|
||||
- address: ":25"
|
||||
# log-level: debug
|
||||
tls:
|
||||
storage:
|
||||
queue: {driver: filesystem}
|
||||
limits:
|
||||
max-message-size-bytes: 1
|
||||
# connection-rate-per-source: 5
|
||||
`
|
||||
adds, err := Missing([]byte(file), []byte(fullTemplate), schema{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(adds) != 0 {
|
||||
t.Errorf("Missing() = %+v, want nothing (commented, empty and flow values count as present)", adds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingEmptyFile(t *testing.T) {
|
||||
adds, err := Missing([]byte("# nothing yet\n"), []byte(fullTemplate), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(adds) != 5 {
|
||||
t.Errorf("Missing() on an empty file = %d additions, want every top-level option (5)", len(adds))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingRejectsNonMapping(t *testing.T) {
|
||||
if _, err := Missing([]byte("- a\n- b\n"), []byte(fullTemplate), nil); err == nil {
|
||||
t.Error("Missing() on a top-level list succeeded, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUndocumentedKeys(t *testing.T) {
|
||||
got, err := UndocumentedKeys(fullTemplate, schema{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Errorf("UndocumentedKeys(full) = %v, want none", got)
|
||||
}
|
||||
got, _ = UndocumentedKeys(minimalTemplate, schema{})
|
||||
want := "log-level listen[].tls limits tls"
|
||||
if strings.Join(got, " ") != want {
|
||||
t.Errorf("UndocumentedKeys(minimal) = %v, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingDoesNotOfferEntriesOfOperatorNamedMaps(t *testing.T) {
|
||||
type backend struct {
|
||||
Driver string `yaml:"driver"`
|
||||
Root string `yaml:"root"`
|
||||
}
|
||||
type ctl struct {
|
||||
Backends map[string]backend `yaml:"backends"`
|
||||
}
|
||||
tmpl := "backends:\n inbound:\n driver: filesystem\n root: /q\n"
|
||||
file := "backends:\n queue:\n driver: filesystem\n root: /x\n"
|
||||
adds, err := Missing([]byte(file), []byte(tmpl), ctl{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(adds) != 0 {
|
||||
t.Errorf("Missing() with schema = %+v, want nothing (backends names are operator data)", adds)
|
||||
}
|
||||
// Without the schema the template's example entry is offered.
|
||||
if adds, _ := Missing([]byte(file), []byte(tmpl), nil); len(adds) != 1 || adds[0].Key != "backends.inbound" {
|
||||
t.Errorf("Missing() without schema = %+v, want backends.inbound", adds)
|
||||
}
|
||||
// A file without the map at all is offered the whole block.
|
||||
if adds, _ := Missing([]byte("{}\n"), []byte(tmpl), ctl{}); len(adds) != 1 || adds[0].Key != "backends" {
|
||||
t.Errorf("Missing() on a file without backends = %+v, want backends", adds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalWithoutFile(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
s.Optional = true
|
||||
s.Validate = func(path string) error {
|
||||
if path != "" {
|
||||
t.Errorf("Validate got %q, want the defaults (\"\")", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
code, out, errOut := run(t, s, "", "validate")
|
||||
if code != ExitOK || !strings.Contains(out, "built-in defaults") {
|
||||
t.Fatalf("validate: code %d, out %q, err %q", code, out, errOut)
|
||||
}
|
||||
code, out, _ = run(t, s, "", "upgrade")
|
||||
if code != ExitOK || !strings.Contains(out, "nothing to upgrade") {
|
||||
t.Fatalf("upgrade: code %d, out %q", code, out)
|
||||
}
|
||||
// An explicit --config that does not exist is still an error.
|
||||
if code, _, _ = run(t, s, filepath.Join(root, "nope.yaml"), "validate"); code != ExitProblem {
|
||||
t.Fatalf("validate --config missing: code %d, want %d", code, ExitProblem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNone(t *testing.T) {
|
||||
s := Spec{Name: "yatool", None: true}
|
||||
for _, sub := range Subcommands {
|
||||
code, out, _ := run(t, s, "", sub)
|
||||
if code != ExitOK || out != "yatool has no configuration file\n" {
|
||||
t.Errorf("%s: code %d, out %q", sub, code, out)
|
||||
}
|
||||
}
|
||||
if code, _, _ := run(t, s, "", "bogus"); code != ExitUsage {
|
||||
t.Errorf("bogus: code %d, want %d", code, ExitUsage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilenameAndFind(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
s.Filename = "custom.yml"
|
||||
if _, err := s.Find(""); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("Find without file: %v, want ErrNotFound", err)
|
||||
}
|
||||
writeFile(t, filepath.Join(root, "work", "custom.yml"), minimalTemplate)
|
||||
l, err := s.Find("")
|
||||
if err != nil || filepath.Base(l.Path) != "custom.yml" {
|
||||
t.Fatalf("Find: %v, %v", l.Path, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package configcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// UnknownKey is a key of a configuration file that no option of the
|
||||
// program has: a typo, an option of another program, or one a newer
|
||||
// version dropped. The program ignores it, so it silently gets the
|
||||
// default instead of what the operator meant.
|
||||
type UnknownKey struct {
|
||||
// Key is the dotted path ("pre-accept-checks.requre-known-domain");
|
||||
// entries of a list are "listen[1].tls".
|
||||
Key string
|
||||
Line int
|
||||
}
|
||||
|
||||
func (k UnknownKey) String() string { return fmt.Sprintf("%s (line %d)", k.Key, k.Line) }
|
||||
|
||||
// UnknownKeys lists the keys of raw that schema (the program's
|
||||
// configuration struct, e.g. config.Config{}) has no field for, by its
|
||||
// yaml tags. It descends into struct-typed mappings, lists of structs
|
||||
// and maps of structs (a map of named backends: the names are the
|
||||
// operator's, their contents are options). A type with its own
|
||||
// UnmarshalYAML is taken as a whole: it decides itself what it accepts.
|
||||
func UnknownKeys(raw []byte, schema any) ([]UnknownKey, error) {
|
||||
var doc yaml.Node
|
||||
if err := yaml.Unmarshal(raw, &doc); err != nil {
|
||||
return nil, fmt.Errorf("parsing: %w", err)
|
||||
}
|
||||
root := docMapping(&doc)
|
||||
if root == nil || schema == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var out []UnknownKey
|
||||
walkUnknown(nil, reflect.TypeOf(schema), root, &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UnknownKeysFile is UnknownKeys for the file at path.
|
||||
func UnknownKeysFile(path string, schema any) ([]UnknownKey, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return UnknownKeys(raw, schema)
|
||||
}
|
||||
|
||||
var unmarshalerType = reflect.TypeOf((*yaml.Unmarshaler)(nil)).Elem()
|
||||
|
||||
// opaque reports whether t decodes itself (or is no struct/map/list),
|
||||
// so its contents are not checked key by key.
|
||||
func opaque(t reflect.Type) bool {
|
||||
if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) {
|
||||
return true
|
||||
}
|
||||
switch t.Kind() {
|
||||
case reflect.Struct, reflect.Map, reflect.Slice, reflect.Array:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func walkUnknown(path []string, t reflect.Type, n *yaml.Node, out *[]UnknownKey) {
|
||||
t = deref(t)
|
||||
if opaque(t) {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case n.Kind == yaml.MappingNode && t.Kind() == reflect.Struct:
|
||||
for i := 0; i+1 < len(n.Content); i += 2 {
|
||||
k, v := n.Content[i], n.Content[i+1]
|
||||
sub := append(append([]string(nil), path...), k.Value)
|
||||
ft, ok := fieldType(t, k.Value)
|
||||
if !ok {
|
||||
*out = append(*out, UnknownKey{Key: strings.Join(sub, "."), Line: k.Line})
|
||||
continue
|
||||
}
|
||||
walkUnknown(sub, ft, v, out)
|
||||
}
|
||||
case n.Kind == yaml.MappingNode && t.Kind() == reflect.Map:
|
||||
for i := 0; i+1 < len(n.Content); i += 2 {
|
||||
k, v := n.Content[i], n.Content[i+1]
|
||||
walkUnknown(append(append([]string(nil), path...), k.Value), t.Elem(), v, out)
|
||||
}
|
||||
case n.Kind == yaml.SequenceNode && (t.Kind() == reflect.Slice || t.Kind() == reflect.Array):
|
||||
for i, item := range n.Content {
|
||||
sub := append([]string(nil), path...)
|
||||
if len(sub) > 0 {
|
||||
sub[len(sub)-1] = fmt.Sprintf("%s[%d]", sub[len(sub)-1], i)
|
||||
}
|
||||
walkUnknown(sub, t.Elem(), item, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WarnUnknown logs every unknown option of the configuration file at
|
||||
// path. A program calls it after loading its configuration: it keeps
|
||||
// running with the defaults for those keys (a typo must not take a
|
||||
// server down), but the operator sees why a setting has no effect.
|
||||
func WarnUnknown(log *slog.Logger, path string, schema any) {
|
||||
unknown, err := UnknownKeysFile(path, schema)
|
||||
if err != nil {
|
||||
return // Load already reported a file it cannot parse
|
||||
}
|
||||
for _, k := range unknown {
|
||||
log.Warn("configuration: unknown option, ignored (the default applies)", "option", k.Key, "line", k.Line, "path", path)
|
||||
}
|
||||
}
|
||||
|
||||
// UnknownCheck is doctor's check of the file at path: ok without
|
||||
// unknown options, else a note listing them.
|
||||
func UnknownCheck(path string, schema any) (ok bool, note string) {
|
||||
unknown, err := UnknownKeysFile(path, schema)
|
||||
if err != nil {
|
||||
return false, err.Error()
|
||||
}
|
||||
if len(unknown) == 0 {
|
||||
return true, ""
|
||||
}
|
||||
parts := make([]string, len(unknown))
|
||||
for i, k := range unknown {
|
||||
parts[i] = k.String()
|
||||
}
|
||||
return false, "ignored, the defaults apply: " + strings.Join(parts, ", ")
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package configcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type testInner struct {
|
||||
Driver string `yaml:"driver"`
|
||||
Root string `yaml:"root"`
|
||||
}
|
||||
|
||||
type testThrottle struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
}
|
||||
|
||||
type testThrottleSection struct {
|
||||
Config testThrottle `yaml:",inline"`
|
||||
Storage testInner `yaml:"storage"`
|
||||
}
|
||||
|
||||
type testListener struct {
|
||||
Address string `yaml:"address"`
|
||||
TLS string `yaml:"tls"`
|
||||
}
|
||||
|
||||
type selfDecoding struct{ v map[string]string }
|
||||
|
||||
func (s *selfDecoding) UnmarshalYAML(n *yaml.Node) error { return n.Decode(&s.v) }
|
||||
|
||||
type testConfig struct {
|
||||
LogLevel string `yaml:"log-level"`
|
||||
Listen []testListener `yaml:"listen"`
|
||||
Storage struct {
|
||||
Mail *testInner `yaml:"mailstore"`
|
||||
} `yaml:"storage"`
|
||||
Backends map[string]testInner `yaml:"backends"`
|
||||
Throttle testThrottleSection `yaml:"throttle"`
|
||||
Timeout time.Duration `yaml:"timeout"`
|
||||
Custom selfDecoding `yaml:"custom"`
|
||||
Ignored string `yaml:"-"`
|
||||
}
|
||||
|
||||
func TestUnknownKeys(t *testing.T) {
|
||||
raw := []byte(`log-level: info
|
||||
log-levle: debug
|
||||
listen:
|
||||
- address: ":25"
|
||||
tsl: auto
|
||||
storage:
|
||||
mailstore:
|
||||
driver: filesystem
|
||||
rot: /x
|
||||
backends:
|
||||
inbound: {driver: filesystem, root: /q, extra: 1}
|
||||
throttle:
|
||||
enabled: true
|
||||
storage: {driver: filesystem, root: /t}
|
||||
enabeld: false
|
||||
timeout: 5s
|
||||
custom: {anything: goes}
|
||||
Ignored: x
|
||||
`)
|
||||
got, err := UnknownKeys(raw, testConfig{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []UnknownKey{
|
||||
{"log-levle", 2},
|
||||
{"listen[0].tsl", 5},
|
||||
{"storage.mailstore.rot", 9},
|
||||
{"backends.inbound.extra", 11},
|
||||
{"throttle.enabeld", 15},
|
||||
{"Ignored", 18},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("UnknownKeys =\n%v\nwant\n%v", got, want)
|
||||
}
|
||||
if got, _ := UnknownKeys([]byte("log-level: info\n"), testConfig{}); len(got) != 0 {
|
||||
t.Fatalf("a clean file has unknown keys: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWarnUnknownAndCheck(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "c.yaml")
|
||||
if err := os.WriteFile(path, []byte("log-level: info\nlog-levle: debug\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
WarnUnknown(slog.New(slog.NewTextHandler(&buf, nil)), path, testConfig{})
|
||||
if !strings.Contains(buf.String(), "level=WARN") || !strings.Contains(buf.String(), "option=log-levle") || !strings.Contains(buf.String(), "line=2") {
|
||||
t.Errorf("warning = %q", buf.String())
|
||||
}
|
||||
if ok, note := UnknownCheck(path, testConfig{}); ok || !strings.Contains(note, "log-levle (line 2)") {
|
||||
t.Errorf("check = %v %q", ok, note)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("log-level: info\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, note := UnknownCheck(path, testConfig{}); !ok || note != "" {
|
||||
t.Errorf("clean file: %v %q", ok, note)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package configcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Addition is one option a configuration file does not mention yet,
|
||||
// rendered from the full template as a commented YAML block.
|
||||
type Addition struct {
|
||||
// Key is the option's dotted path, e.g. "limits.connection-rate-per-source".
|
||||
Key string
|
||||
// Text is the commented block, indented for where it goes, ending
|
||||
// in a newline.
|
||||
Text string
|
||||
// AfterLine is the 1-based line of the file the block goes after;
|
||||
// 0 means the end of the file (a top-level option).
|
||||
AfterLine int
|
||||
}
|
||||
|
||||
// Missing compares a configuration file with the full template and
|
||||
// returns, in template order, every option the template documents that
|
||||
// the file neither sets nor mentions as a "# key:" comment -- the same
|
||||
// shape the blocks themselves are added in, so running it again on the
|
||||
// upgraded file finds nothing.
|
||||
//
|
||||
// The comparison descends into mappings the file and the template both
|
||||
// have; a list (listeners, blocklists, ...) is the operator's data and
|
||||
// is never descended into, and neither is an option the file sets to a
|
||||
// non-mapping value (e.g. "tls:" left empty on purpose).
|
||||
//
|
||||
// schema is the program's configuration struct (e.g. config.Config{}).
|
||||
// With it, a mapping whose Go type is a map (keys the operator names,
|
||||
// like a map of named backends) is operator data too: only its presence
|
||||
// counts, the template's example entries are never offered inside it.
|
||||
// nil compares by the template alone.
|
||||
func Missing(raw, full []byte, schema any) ([]Addition, error) {
|
||||
var file, tmpl yaml.Node
|
||||
if err := yaml.Unmarshal(raw, &file); err != nil {
|
||||
return nil, fmt.Errorf("parsing: %w", err)
|
||||
}
|
||||
if err := yaml.Unmarshal(full, &tmpl); err != nil {
|
||||
return nil, fmt.Errorf("parsing the full template: %w", err)
|
||||
}
|
||||
troot := docMapping(&tmpl)
|
||||
if troot == nil {
|
||||
return nil, nil
|
||||
}
|
||||
lines := strings.Split(string(raw), "\n")
|
||||
froot := docMapping(&file)
|
||||
if froot == nil {
|
||||
if len(file.Content) > 0 {
|
||||
return nil, fmt.Errorf("top level is not a mapping")
|
||||
}
|
||||
// empty (or comments only): every top-level option is missing
|
||||
froot = &yaml.Node{Kind: yaml.MappingNode}
|
||||
}
|
||||
var t reflect.Type
|
||||
if schema != nil {
|
||||
t = reflect.TypeOf(schema)
|
||||
}
|
||||
return compare(nil, t, froot, troot, 0, 1, len(lines), 0, lines), nil
|
||||
}
|
||||
|
||||
func docMapping(doc *yaml.Node) *yaml.Node {
|
||||
if doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
|
||||
return nil
|
||||
}
|
||||
return doc.Content[0]
|
||||
}
|
||||
|
||||
// compare collects the template keys missing in fmap. t is the Go type
|
||||
// of the mapping (nil: unknown, compare by the template alone), from..to
|
||||
// (1-based) are the file lines fmap spans, childIndent the column its
|
||||
// keys start at, and afterLine where a missing key's block goes (0: end
|
||||
// of file).
|
||||
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
||||
var out []Addition
|
||||
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
||||
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
||||
sub := append(append([]string(nil), path...), tkey.Value)
|
||||
var ft reflect.Type
|
||||
if t != nil {
|
||||
var ok bool
|
||||
if ft, ok = fieldType(t, tkey.Value); !ok {
|
||||
continue // not an option of this program
|
||||
}
|
||||
}
|
||||
fkey, fval := lookup(fmap, tkey.Value)
|
||||
if fval != nil {
|
||||
if fval.Kind == yaml.MappingNode && tval.Kind == yaml.MappingNode && fval.Style&yaml.FlowStyle == 0 &&
|
||||
(ft == nil || deref(ft).Kind() == reflect.Struct) {
|
||||
indent := childIndent + 2
|
||||
if len(fval.Content) > 0 {
|
||||
indent = fval.Content[0].Column - 1
|
||||
}
|
||||
end := blockEnd(lines, lastLine(fval), indent)
|
||||
out = append(out, compare(sub, ft, fval, tval, indent, fkey.Line, end, end, lines)...)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if mentioned(lines, from, to, childIndent, tkey.Value) {
|
||||
continue
|
||||
}
|
||||
out = append(out, Addition{
|
||||
Key: strings.Join(sub, "."),
|
||||
Text: render(tkey, tval, childIndent),
|
||||
AfterLine: afterLine,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func lookup(m *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
|
||||
for i := 0; i+1 < len(m.Content); i += 2 {
|
||||
if m.Content[i].Value == key {
|
||||
return m.Content[i], m.Content[i+1]
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// lastLine is the last file line a node's value occupies.
|
||||
func lastLine(n *yaml.Node) int {
|
||||
last := n.Line
|
||||
if n.Kind == yaml.ScalarNode && n.Style&(yaml.LiteralStyle|yaml.FoldedStyle) != 0 {
|
||||
last += strings.Count(strings.TrimRight(n.Value, "\n"), "\n") + 1
|
||||
}
|
||||
for _, c := range n.Content {
|
||||
last = max(last, lastLine(c))
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
func indentOf(l string) int { return len(l) - len(strings.TrimLeft(l, " ")) }
|
||||
|
||||
// blockEnd extends a block's last line over the comment lines right
|
||||
// after it that are indented as its children -- blocks an earlier
|
||||
// upgrade added there still belong to it.
|
||||
func blockEnd(lines []string, last, minIndent int) int {
|
||||
for last < len(lines) {
|
||||
l := lines[last] // the line after "last" (1-based)
|
||||
if !strings.HasPrefix(strings.TrimSpace(l), "#") || indentOf(l) < minIndent {
|
||||
break
|
||||
}
|
||||
last++
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
// mentioned reports whether lines from..to (1-based) set key or carry it
|
||||
// as a "# key:" comment at the given indent. Only "#" followed by at
|
||||
// most one space counts, so the deeper lines of a commented block
|
||||
// ("# driver: ...") are not taken for a sibling option.
|
||||
func mentioned(lines []string, from, to, indent int, key string) bool {
|
||||
re := regexp.MustCompile(`^#\s?` + regexp.QuoteMeta(key) + `:`)
|
||||
for i := max(from, 1) - 1; i < to && i < len(lines); i++ {
|
||||
if indentOf(lines[i]) == indent && re.MatchString(lines[i][indent:]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// render returns one template option as a commented block at indent:
|
||||
// the template's comment lines stay as they are, every YAML line gets
|
||||
// "# " in front, so adding it changes nothing until the operator
|
||||
// removes the "#".
|
||||
func render(key, val *yaml.Node, indent int) string {
|
||||
k := *key
|
||||
k.FootComment = ""
|
||||
var buf bytes.Buffer
|
||||
enc := yaml.NewEncoder(&buf)
|
||||
enc.SetIndent(2)
|
||||
_ = enc.Encode(&yaml.Node{Kind: yaml.MappingNode, Content: []*yaml.Node{&k, val}})
|
||||
_ = enc.Close()
|
||||
|
||||
pad := strings.Repeat(" ", indent)
|
||||
var b strings.Builder
|
||||
for _, l := range strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") {
|
||||
switch {
|
||||
case strings.TrimSpace(l) == "":
|
||||
case strings.HasPrefix(l, "#"):
|
||||
b.WriteString(pad + l + "\n")
|
||||
default:
|
||||
b.WriteString(pad + "# " + l + "\n")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Apply inserts the additions Missing returned into raw: nested ones
|
||||
// after their line (bottom-up, so earlier line numbers stay valid),
|
||||
// top-level ones at the end of the file.
|
||||
func Apply(raw []byte, adds []Addition) []byte {
|
||||
lines := strings.Split(string(raw), "\n")
|
||||
byLine := map[int]string{}
|
||||
var at []int
|
||||
var tail strings.Builder
|
||||
for _, a := range adds {
|
||||
if a.AfterLine == 0 {
|
||||
tail.WriteString("\n" + a.Text)
|
||||
continue
|
||||
}
|
||||
if _, ok := byLine[a.AfterLine]; !ok {
|
||||
at = append(at, a.AfterLine)
|
||||
}
|
||||
byLine[a.AfterLine] += a.Text
|
||||
}
|
||||
sort.Sort(sort.Reverse(sort.IntSlice(at)))
|
||||
for _, n := range at {
|
||||
n = min(n, len(lines))
|
||||
ins := strings.Split(strings.TrimRight(byLine[n], "\n"), "\n")
|
||||
lines = append(lines[:n], append(ins, lines[n:]...)...)
|
||||
}
|
||||
out := strings.Join(lines, "\n")
|
||||
if tail.Len() > 0 {
|
||||
out = strings.TrimRight(out, "\n") + "\n" + tail.String()
|
||||
}
|
||||
return []byte(out)
|
||||
}
|
||||
|
||||
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
||||
// value, e.g. config.Config{}) that the template does not contain --
|
||||
// neither as a key nor, for a list of structs, in the list's first
|
||||
// item. A program's tests call it with its full template so that a new
|
||||
// option cannot be added without documenting it, which is what keeps
|
||||
// "config upgrade" useful.
|
||||
func UndocumentedKeys(template string, schema any) ([]string, error) {
|
||||
var doc yaml.Node
|
||||
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
||||
return nil, fmt.Errorf("parsing the template: %w", err)
|
||||
}
|
||||
root := docMapping(&doc)
|
||||
if root == nil {
|
||||
return nil, fmt.Errorf("template top level is not a mapping")
|
||||
}
|
||||
var out []string
|
||||
walkSchema(reflect.TypeOf(schema), root, nil, &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
||||
t = deref(t)
|
||||
if t.Kind() != reflect.Struct {
|
||||
return
|
||||
}
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||
if name == "-" || !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
// An inline (embedded) struct's fields are keys of this mapping.
|
||||
if f.Anonymous && strings.Contains(","+opts+",", ",inline,") {
|
||||
walkSchema(f.Type, m, path, out)
|
||||
continue
|
||||
}
|
||||
if name == "" {
|
||||
name = strings.ToLower(f.Name)
|
||||
}
|
||||
sub := append(append([]string(nil), path...), name)
|
||||
_, val := lookup(m, name)
|
||||
if val == nil {
|
||||
*out = append(*out, strings.Join(sub, "."))
|
||||
continue
|
||||
}
|
||||
ft := deref(f.Type)
|
||||
switch {
|
||||
case ft.Kind() == reflect.Struct && val.Kind == yaml.MappingNode:
|
||||
walkSchema(ft, val, sub, out)
|
||||
case ft.Kind() == reflect.Slice && deref(ft.Elem()).Kind() == reflect.Struct &&
|
||||
val.Kind == yaml.SequenceNode && len(val.Content) > 0 && val.Content[0].Kind == yaml.MappingNode:
|
||||
walkSchema(ft.Elem(), val.Content[0], append(sub[:len(sub)-1:len(sub)-1], name+"[]"), out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fieldType returns the type of the field of struct t (or a pointer to
|
||||
// one) whose YAML name is key.
|
||||
func fieldType(t reflect.Type, key string) (reflect.Type, bool) {
|
||||
t = deref(t)
|
||||
if t.Kind() != reflect.Struct {
|
||||
return nil, false
|
||||
}
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||
if strings.Contains(","+opts+",", ",inline,") {
|
||||
// An inline struct's keys are its parent's (named or
|
||||
// embedded); an inline map takes every other key.
|
||||
if deref(f.Type).Kind() == reflect.Map {
|
||||
return deref(f.Type).Elem(), true
|
||||
}
|
||||
if ft, ok := fieldType(f.Type, key); ok {
|
||||
return ft, true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if name == "" {
|
||||
name = strings.ToLower(f.Name)
|
||||
}
|
||||
if name == key && name != "-" && f.IsExported() {
|
||||
return f.Type, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func deref(t reflect.Type) reflect.Type {
|
||||
for t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
return t
|
||||
}
|
||||
Reference in new issue
Block a user