Skip to content

Config Files

An explicit flag beats an environment variable, which beats a config-file value, which beats the tag default.

Config values are loaded before flags register and overwrite the tag defaults, so flags and environment variables still win. Config files feed the root config type T only: a command’s own F struct is parsed from flags alone and has no config-file source.

WithConfigFile(paths...) enables loading. Paths are tried in order and the first existing file wins:

  • JSON, YAML, and TOML are detected by file extension (.json, .yaml/.yml, .toml).
  • $VAR and a leading ~/ are expanded in every path.
  • Missing files are skipped, and an empty file counts as missing.
  • If no path exists, startup continues on defaults.
  • Declare a config flag on the root struct so --config path is accepted; that value then replaces the configured search path.
~/.config/app/config.yaml
log-level: info
database:
host: db.internal
port: 5432
password: from-vault
package main
import (
"context"
"fmt"
"log"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
)
type DatabaseConfig struct {
Host string `flag:"db-host" env:"APP_DB_HOST" default:"localhost" help:"Database host"`
Port int `flag:"db-port" default:"5432" help:"Database port" validate:"min=1,max=65535"`
Password string `flag:"db-password" env:"APP_DB_PASSWORD" secret:"true" help:"Database password"`
}
type AppConfig struct {
LogLevel string `flag:"log-level" env:"APP_LOG_LEVEL" default:"info" help:"Log level"`
Database DatabaseConfig `help:"Database settings"`
Config string `flag:"config" help:"Path to the config file"`
}
func main() {
cli, err := v5.NewCLI[AppConfig]("app", "Config file example", AppConfig{},
v5.WithConfigFile("$HOME/.config/app/config.yaml", "app.yaml"),
v5.WithConfigExplainCommand(),
)
if err != nil {
log.Fatal(err)
}
b := v5.NewBuilder(cli)
v5.Add(b, "status", v5.NoFlags{},
func(_ context.Context, cfg *AppConfig, _ v5.NoFlags) error {
fmt.Printf("%s:%d at %s\n", cfg.Database.Host, cfg.Database.Port, cfg.LogLevel)
return nil
},
v5.WithShort("Show the resolved database endpoint"),
)
if err := b.Build(); err != nil {
log.Fatal(err)
}
cli.ExecuteAndExit(context.Background())
}

Nested structs are walked, so database.host in the file feeds the db-host flag. The CLI still exposes flat flags: --db-host, not --database.host.

Strict key checking is ON by default in v5. A key that no field accepts fails the load with ErrConfigUnknownKey, naming the key and the file, plus a “did you mean” suggestion when the typo is close:

Terminal window
$ app status --config /etc/app/broken.yaml
Error: failed to load config file: loading config file: "/etc/app/broken.yaml": unknown config key "db-hots" (did you mean "db-host"?)

Opt out with WithoutStrictConfigKeys() when the same file is shared with other tools and may carry extra keys. cli.StrictConfigKeys() reports the current mode. A key is accepted when it matches any of these spellings:

Spelling Example for the db-host flag
Canonical key Host (Go field name) or the json tag name
Flag name db-host
Case and separator folding DB_HOST, db_host, DbHost

Custom loaders that do not implement StrictConfigKeyLoader keep accepting unknown keys, because cmdguard cannot inspect their parse step.

v5.ConfigKeys(cfg) returns the public list of keys a config file accepts, derived from the same tags that drive flags. It is the source of truth for the strict check and for schema generation. Each ConfigKey carries Key, Flag, Type, Format, Help, Values, Required, Default, Env, Secret, and Validate; nested objects use Properties and arrays use Items.

Lower-level helpers are exported for tooling:

Symbol Purpose
v5.ParseFlagTags(cfg) Returns the parsed []FlagTag for a config struct
v5.SetField(cfg, "LogLevel", v) Sets one field by Go field name
v5.MergeConfigs(cfgs...) Deep-copies and merges configs, later values win
v5.ValidateConfig(cfg) Applies values and validate rules to a config

WithConfigExplainCommand() registers the config explain command at Execute time. It reports where each root value came from: flag, environment, config-file, default, or unset. Values tagged secret:"true" are always redacted to ***, in the table and in JSON output. The same data is available programmatically:

explanation := cli.ExplainConfig()
fmt.Println("config file:", explanation.ConfigFile)
for _, flag := range explanation.Flags {
fmt.Println(flag.Name, flag.Source, flag.Value)
}

Call it after Execute to describe that run, or before it to describe the constructor defaults plus the config file. Related accessors: cli.ConfigFilePath() returns the file the search order picked, and cli.ConfigDiagnostics() returns []ConfigDiagnostic with config-path, config-parse, and config-keys results. The auto-registered doctor command runs those checks.

WithConfigFileLoader takes anything implementing ConfigFileLoader, whose single method is Load(data []byte, cfg any) (setFields []string, err error). The returned field names are what lets cmdguard treat file values as defaults that flags and env vars override, so a loader that returns an empty slice lets the flag defaults overwrite the file values at parse time. data may be nil for loaders that read their own files; the built-in loader is exported, so you can also construct one explicitly:

loader := v5.NewKoanfLoader("$HOME/.config/app/config.toml", "/etc/app/config.toml")
cli, err := v5.NewCLI[AppConfig]("app", "My app", AppConfig{},
v5.WithConfigFileLoader(loader, "$HOME/.config/app/config.toml", "/etc/app/config.toml"),
)

Tag rules (values, validate) run during flag parsing. For checks that span fields, add WithConfigValidation, which runs after root parsing and before any handler:

cli, err := v5.NewCLI[AppConfig]("app", "My app", AppConfig{},
v5.WithConfigValidation(func(cfg *AppConfig) error {
if cfg.Database.Port < 1024 {
return fmt.Errorf("db-port %d requires root privileges", cfg.Database.Port)
}
return nil
}),
)

Validation errors wrap ErrConfigValidation, so callers can test with errors.Is. v5.ValidateConfig(cfg) applies the tag rules to a config value you built yourself, which is useful in tests and in tooling.