From 0e87b51a0ca0e1dcde9662c56bce4f4a2667d3a7 Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Tue, 24 Nov 2026 03:15:35 +0000 Subject: [PATCH] feat(confx): hint the replacement of moved and removed flags --- CHANGELOG.md | 7 +++++ confx/cliflags/cliflags.go | 29 +++++++++++++++++ confx/cliflags/cliflags_test.go | 55 +++++++++++++++++++++++++++++++++ confx/load.go | 27 +++++++++++++--- 4 files changed, 114 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 84180ba..97d2763 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ becomes the release notes of the next tag. ## [Unreleased] +### Added + +- `confx.FlagHint` and `cliflags.Explain`: an unknown command-line flag that + was a moved or removed config key is reported with the same "moved to" or + "removed" hint as the key in a file (`unknown flag: --rls.enabled: moved to + --roles.switch`). Install `Explain` with cobra's `SetFlagErrorFunc`. + ## [0.19.0] - 2026-11-24 ### Added diff --git a/confx/cliflags/cliflags.go b/confx/cliflags/cliflags.go index 7576e14..0b4fcb9 100644 --- a/confx/cliflags/cliflags.go +++ b/confx/cliflags/cliflags.go @@ -4,7 +4,13 @@ package cliflags import ( + "fmt" + "regexp" + "strings" + flag "github.com/spf13/pflag" + + "github.com/suprbdev/pdbcore/confx" ) // Changed returns the flags explicitly set on fs, minus any names in except @@ -30,3 +36,26 @@ func Changed(fs *flag.FlagSet, except ...string) map[string]any { }) return out } + +var unknownFlag = regexp.MustCompile(`^unknown flag: --([^\s=]+)$`) + +// Explain adds the moved-to, removed or closest-key hint of +// [confx.FlagHint] to the error pflag returns for an unknown flag +// (unknown flag: --rls.enabled becomes "unknown flag: --rls.enabled: moved +// to --roles.switch"). Flags without a dot (--config, --output) are +// command-local and left alone, as is any other error. dst and opts are the +// defaults and the options the product passes to [confx.Load]. Install it +// with cobra's SetFlagErrorFunc. +func Explain(err error, dst any, opts ...confx.LoadOption) error { + if err == nil { + return nil + } + m := unknownFlag.FindStringSubmatch(err.Error()) + if m == nil || !strings.Contains(m[1], ".") { + return err + } + if hint := confx.FlagHint(dst, m[1], opts...); hint != "" { + return fmt.Errorf("%w: %s", err, hint) + } + return err +} diff --git a/confx/cliflags/cliflags_test.go b/confx/cliflags/cliflags_test.go index 166f180..e736e1d 100644 --- a/confx/cliflags/cliflags_test.go +++ b/confx/cliflags/cliflags_test.go @@ -1,6 +1,8 @@ package cliflags_test import ( + "errors" + "io" "reflect" "testing" "time" @@ -58,3 +60,56 @@ func TestChanged(t *testing.T) { t.Fatalf("cfg = %+v", cfg) } } + +func TestExplain(t *testing.T) { + var cfg struct { + Limits struct { + MaxCost int `koanf:"max_cost"` + } `koanf:"limits"` + Roles struct { + Switch bool `koanf:"switch"` + } `koanf:"roles"` + Plugins struct { + Settings struct { + AdvancedFilters struct { + Enabled bool `koanf:"enabled"` + } `koanf:"advanced_filters"` + } `koanf:"settings"` + } `koanf:"plugins"` + } + opts := []confx.LoadOption{ + confx.WithMoved(map[string]string{ + "server.max_cost": "limits.max_cost", + "plugins.settings.advanced-filters": "plugins.settings.advanced_filters", + }), + confx.WithRemoved(map[string]string{"transactions.mutations": "mutations always run in a transaction"}), + } + parse := func(args ...string) error { + fs := flag.NewFlagSet("t", flag.ContinueOnError) + fs.SetOutput(io.Discard) + fs.String("config", "", "") + fs.Int("limits.max_cost", 0, "") + return fs.Parse(args) + } + for _, c := range []struct{ arg, want string }{ + {"--rls.enabled=false", "unknown flag: --rls.enabled: moved to --roles.switch"}, + {"--server.max_cost=5", "unknown flag: --server.max_cost: moved to --limits.max_cost"}, + {"--plugins.settings.advanced-filters.enabled", "unknown flag: --plugins.settings.advanced-filters.enabled: moved to --plugins.settings.advanced_filters.enabled"}, + {"--transactions.mutations", "unknown flag: --transactions.mutations: removed: mutations always run in a transaction"}, + {"--limits.max_cots=1", "unknown flag: --limits.max_cots: did you mean --limits.max_cost?"}, + {"--nonsense.zzzz", "unknown flag: --nonsense.zzzz"}, + {"--confg=x", "unknown flag: --confg"}, + } { + got := cliflags.Explain(parse(c.arg), &cfg, opts...) + if got == nil || got.Error() != c.want { + t.Errorf("Explain(%s) = %v, want %q", c.arg, got, c.want) + } + } + if err := cliflags.Explain(nil, &cfg); err != nil { + t.Fatalf("nil: %v", err) + } + other := errors.New("invalid argument") + if got := cliflags.Explain(other, &cfg); !errors.Is(got, other) { + t.Fatalf("other error changed: %v", got) + } +} diff --git a/confx/load.go b/confx/load.go index 8cc953a..c628439 100644 --- a/confx/load.go +++ b/confx/load.go @@ -59,6 +59,28 @@ func WithFlags(values map[string]any) LoadOption { } } +// FlagHint explains an unknown command-line flag name (without the dashes; +// flags are named after koanf paths) the way Load explains an unknown file +// key: "moved to --", "removed: " or "did you mean --?". +// dst is the defaults struct the flags configure and opts the same +// WithMoved and WithRemoved options the product passes to Load. It returns +// "" when nothing is close. +func FlagHint(dst any, name string, opts ...LoadOption) string { + o := newLoadOpts() + for _, opt := range opts { + opt(&o) + } + return schemaOf(dst).unknownKey(name, o.hints, func(p string) string { return "--" + p }) +} + +func newLoadOpts() loadOpts { + o := loadOpts{hints: hints{moved: map[string]string{}, removed: map[string]string{}}, flags: map[string]any{}} + for k, v := range movedKeys { + o.moved[k] = v + } + return o +} + // Load layers configuration into dst (which already holds the defaults): // optional YAML file, then envPrefix-prefixed environment variables, then // command-line values (WithFlags). @@ -74,10 +96,7 @@ func WithFlags(values map[string]any) LoadOption { // are decoded with weak typing, so environment strings set booleans, // numbers, durations and lists. Validation is the caller's job. func Load(envPrefix, path string, dst any, opts ...LoadOption) error { - o := loadOpts{hints: hints{moved: map[string]string{}, removed: map[string]string{}}, flags: map[string]any{}} - for k, v := range movedKeys { - o.moved[k] = v - } + o := newLoadOpts() for _, opt := range opts { opt(&o) }