// Package configcmd is the shared " config" command of the // Yetano program standard (docs/program-conventions.md and ADR-0012 in // the yetano meta-repository): // // config create [--minimal|--full] [--force] [--output ] // config validate // config upgrade [--write] // config path // config show [--json] [--show-secrets] // // 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. // // "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 // 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 // ".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 // 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 { if s.Filename != "" { return s.Filename } return s.Name + ".yaml" } // Run serves " config " 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", "show": 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": 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) case "upgrade": return s.upgrade(explicit, rest, stdout, stderr) 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) case "show": return s.show(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", "show"} 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 [--config ] create [--minimal|--full] [--force] [--output ] 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 %[3]s 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 // 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 , 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 ") } 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 }