package configfamily import ( "errors" "flag" "fmt" "io" "log/slog" "os" "path/filepath" "slices" coreconfig "yetano.dev/yetano/core/config" "yetano.dev/yetano/core/configcmd" "yetano.dev/yetano/core/doctor" "yetano.dev/yetano/core/paths" ) // Spec is one program's part of the config command. type Spec struct { Program Program // Optional says the program also runs without any configuration // file, on built-in defaults: validate, show and doctor then report // that instead of failing. Optional bool // Minimal is the template "config create" writes by default: what // the program needs to start. Full is "config create --full", // documenting every option the program reads; "config upgrade" // offers its options a file does not mention yet. Minimal, Full string // Validate parses and validates the merged configuration (YAML, see // Loaded.YAML) the same way the program does at startup. For an // Optional program without a file it gets nil. Validate func(merged []byte) error // Schema is the program's configuration struct (e.g. config.Config{}): // it enables unknown-option detection and tells "config show" which // options the program reads. Schema any // Options are passed through to core/config; tests use them to // inject a platform, environment and root. Options []coreconfig.Option } // Core returns the core/configcmd Spec this Spec stands for: create and // upgrade work on the program's own file, path, validate and show on // all layers through core's Layered hook. func (s Spec) Core() configcmd.Spec { c := coreSpec(s.Program, s.Options) c.Optional = s.Optional c.Minimal, c.Full, c.Schema = s.Minimal, s.Full, s.Schema c.Layered = &configcmd.Layered{ Layers: func(explicit string) ([]configcmd.LayerInfo, error) { layers, err := Layers(s.Program, explicit, s.Options...) if err != nil { return nil, err } out := make([]configcmd.LayerInfo, len(layers)) for i, l := range layers { out[i] = l.Info() } return out, nil }, Load: func(explicit string) (*configcmd.Effective, error) { l, err := s.Load(explicit) if err != nil { return nil, err } return l.Effective(), nil }, Unknown: func(e *configcmd.Effective) ([]configcmd.UnknownKey, error) { l, ok := e.Loader.(*Loaded) if !ok || s.Schema == nil { return nil, nil } return l.Unknown(s.Schema) }, Validate: s.Validate, Used: func(key string) bool { return s.Schema == nil || configcmd.KnownKey(s.Schema, key) }, } return c } // Load is the package's Load for this program. func (s Spec) Load(explicit string) (*Loaded, error) { return Load(s.Program, explicit, s.Options...) } // Run serves " config " and returns the exit code. // explicit is the program's --config value ("" if not given). Only // "create --shared" is this package's own; everything else is // core/configcmd's. func Run(s Spec, explicit string, args []string, stdout, stderr io.Writer) int { shared := s.Program.Family.SharedTemplate != "" if len(args) > 0 && shared { switch args[0] { case "create": if slices.Contains(args[1:], "--shared") || slices.Contains(args[1:], "-shared") { return s.createShared(args[1:], stdout, stderr) } case "help", "-h", "-help", "--help": configcmd.Run(s.Core(), explicit, args, stdout, stderr) fmt.Fprintf(stdout, " create --shared [--force] [--output ]\n write a commented starter %s, the options the %s programs share\n", s.Program.Family.SharedFilename(), s.Program.Family.Name) return configcmd.ExitOK } } return configcmd.Run(s.Core(), explicit, args, stdout, stderr) } // Doctor is core/configcmd's Doctor for this program: it records the // paths and every configuration layer in r, checks that the // configuration loads and has no unknown options, and returns it (nil // when there is none or it does not load). func Doctor(r *doctor.Report, s Spec, explicit string) *Loaded { e := configcmd.Doctor(r, s.Core(), explicit) if e == nil { return nil } l, _ := e.Loader.(*Loaded) return l } // WarnUnknown logs every unknown option of every layer of l: the // program keeps running with the defaults for those keys, but the // operator sees why a setting has no effect. func WarnUnknown(log *slog.Logger, l *Loaded, schema any) { unknown, err := l.Unknown(schema) if err != nil { return // Load already read and parsed every file } for _, k := range unknown { log.Warn("configuration: unknown option, ignored (the default applies)", "option", k.Key, "line", k.Line, "path", k.Layer) } } // LogLayers logs the files l was merged from, lowest priority first. func LogLayers(log *slog.Logger, l *Loaded) { used := l.Used() for i := len(used) - 1; i >= 0; i-- { log.Info("configuration file", "path", used[i].Name(), "source", used[i].SourceName()) } } // createShared writes Family.SharedTemplate: to --output, else to the // family file the program reads first, else into the user config // directory -- the system one when running as root or without a home. func (s Spec) createShared(args []string, stdout, stderr io.Writer) int { name := s.Program.Name fs := flag.NewFlagSet(name+" config create", flag.ContinueOnError) fs.SetOutput(stderr) fs.Bool("shared", true, "write "+s.Program.Family.SharedFilename()+", the options the programs share") force := fs.Bool("force", false, "overwrite an existing file") output := fs.String("output", "", "write to this file") if err := fs.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { return configcmd.ExitOK } return configcmd.ExitUsage } if fs.NArg() != 0 { fmt.Fprintf(stderr, "%s config create: unexpected argument %q\n", name, fs.Arg(0)) return configcmd.ExitUsage } path := *output if path == "" { layers, err := Layers(s.Program, "", s.Options...) if err != nil { fmt.Fprintf(stderr, "%s config create: %v\n", name, err) return configcmd.ExitProblem } var user, system string for _, l := range layers { if l.Kind != SharedLayer { continue } if l.Exists && path == "" { path = l.Path } if l.Source == paths.SystemDirectory { system = l.Path } else if user == "" { user = l.Path } } if path == "" { path = user if os.Geteuid() == 0 || user == "" { path = system } } if path == "" { fmt.Fprintf(stderr, "%s config create: no configuration directory known; pass --output \n", name) return configcmd.ExitProblem } } if _, err := os.Stat(path); err == nil && !*force { fmt.Fprintf(stderr, "%s config create: %s exists; pass --force to overwrite it\n", name, path) return configcmd.ExitProblem } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { fmt.Fprintf(stderr, "%s config create: %v\n", name, err) return configcmd.ExitProblem } // 0640: a configuration may name credentials files and should not be // world-readable by default. if err := os.WriteFile(path, []byte(s.Program.Family.SharedTemplate), 0o640); err != nil { fmt.Fprintf(stderr, "%s config create: %v\n", name, err) return configcmd.ExitProblem } fmt.Fprintf(stdout, "%s: wrote the shared configuration -- review it, then run \"%s config validate\"\n", path, name) return configcmd.ExitOK }