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. For an // Optional program without any file it gets nil (the defaults). Validate func(merged []byte) error // Used reports whether the program reads the option key, for "config // 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 // SecretKeys are redacted by Values and Show in addition to the // default secret names (Spec.SecretKeys). SecretKeys []string } // 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 && s.Optional && explicit == "" && errors.Is(err, ErrNotFound) { if s.Layered.Validate != nil { if err := s.Layered.Validate(nil); err != nil { fmt.Fprintf(stderr, "%s: no configuration file, and the built-in defaults are invalid: %v\n", s.Name, err) return ExitProblem } } fmt.Fprintf(stdout, "no configuration file found -- %s runs on its built-in defaults (\"%s config path\" lists the locations)\n", s.Name, s.Name) return ExitOK } if err != nil { fmt.Fprintf(stderr, "%s config validate: %v\n", s.Name, err) return ExitProblem } 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 ") 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() e.SecretKeys = s.SecretKeys 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 && s.Optional && explicit == "" && errors.Is(err, ErrNotFound) { r.Check("config file found", true, "none, "+s.Name+" runs on its built-in defaults") return nil } if err != nil { note := err.Error() if errors.Is(err, ErrNotFound) { note = "none of the searched files exists; pass --config 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 }