Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions confx/cliflags/cliflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
55 changes: 55 additions & 0 deletions confx/cliflags/cliflags_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cliflags_test

import (
"errors"
"io"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -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)
}
}
27 changes: 23 additions & 4 deletions confx/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 --<key>", "removed: <reason>" or "did you mean --<key>?".
// 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).
Expand All @@ -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)
}
Expand Down
Loading