From 7bb7c0b0f190801907a464d5869a873fb3409905 Mon Sep 17 00:00:00 2001 From: "lewtec-bot[bot]" <252450460+lewtec-bot[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:07:00 -0300 Subject: [PATCH 1/3] feat(x/cmd): publish tagged args on context Optional ctx tag puts parsed Value()s in a bag App.Run fills. Get[T] reads them. Core App flags are tagged. --- x/cmd/app.go | 14 +++-- x/cmd/ctx.go | 146 ++++++++++++++++++++++++++++++++++++++++++++++ x/cmd/ctx_test.go | 144 +++++++++++++++++++++++++++++++++++++++++++++ x/cmd/parse.go | 11 +++- 4 files changed, 308 insertions(+), 7 deletions(-) create mode 100644 x/cmd/ctx.go create mode 100644 x/cmd/ctx_test.go diff --git a/x/cmd/app.go b/x/cmd/app.go index 5d526e206..300b901fb 100644 --- a/x/cmd/app.go +++ b/x/cmd/app.go @@ -17,10 +17,10 @@ type None struct{} // App wraps process-wide flags around T, the rest of the command spec. type App[T any] struct { - verbose Count `short:"v" long:"verbose" help:"log verbosity"` - profileDir StringArg `long:"profile-dir" help:"write pprof profiles here" default:""` - help Flag `short:"h" long:"help" help:"show help"` - version Flag `long:"version" help:"print version"` + verbose Count `short:"v" long:"verbose" help:"log verbosity" ctx:"verbose"` + profileDir StringArg `long:"profile-dir" help:"write pprof profiles here" default:"" ctx:"profile-dir"` + help Flag `short:"h" long:"help" help:"show help" ctx:"help"` + version Flag `long:"version" help:"print version" ctx:"version"` Args T `flatten:""` } @@ -60,15 +60,17 @@ func (a *App[T]) Setup(ctx context.Context) error { // Run prints help or version when asked, then Setup, then T's selected // command (or T itself) if it has Run(ctx) error. func (a *App[T]) Run(ctx context.Context) error { + ctx = withValues(ctx) + bind(ctx, reflect.ValueOf(a).Elem()) switch { - case a.Help(): + case Get[bool](ctx, "help"): text, err := Usage[App[T]](filepath.Base(os.Args[0])) if err != nil { return err } _, err = fmt.Fprint(os.Stdout, text) return err - case a.WantVersion(): + case Get[bool](ctx, "version"): return release.PrintVersion(os.Stdout) } if err := a.Setup(ctx); err != nil { diff --git a/x/cmd/ctx.go b/x/cmd/ctx.go new file mode 100644 index 000000000..32658fb11 --- /dev/null +++ b/x/cmd/ctx.go @@ -0,0 +1,146 @@ +package cmd + +import ( + "context" + "fmt" + "reflect" + "strings" +) + +type bagKey struct{} + +type valueBag map[string]any + +// Get returns the value stored under key. It panics if the context has no +// value bag, the key is missing, or v is not a T. +func Get[T any](ctx context.Context, key string) T { + b, ok := ctx.Value(bagKey{}).(valueBag) + if !ok { + panic("cmd: context has no values") + } + v, ok := b[key] + if !ok { + panic(`cmd: context key "` + key + `" not set`) + } + t, ok := v.(T) + if !ok { + panic(fmt.Sprintf("cmd: context key %q is %T, not %T", key, v, *new(T))) + } + return t +} + +func withValues(ctx context.Context) context.Context { + if _, ok := ctx.Value(bagKey{}).(valueBag); ok { + return ctx + } + return context.WithValue(ctx, bagKey{}, valueBag{}) +} + +func put(ctx context.Context, key string, v any) { + b, ok := ctx.Value(bagKey{}).(valueBag) + if !ok { + panic("cmd: context has no values") + } + b[key] = v +} + +func ctxName(sf reflect.StructField) string { + ctx, ok := sf.Tag.Lookup("ctx") + if !ok { + return "" + } + if ctx != "" { + return ctx + } + if long := sf.Tag.Get("long"); long != "" { + return long + } + return strings.ToLower(sf.Name) +} + +func bind(ctx context.Context, v reflect.Value) { + if v.Kind() == reflect.Pointer { + if v.IsNil() { + return + } + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return + } + t := v.Type() + for i := range t.NumField() { + sf := t.Field(i) + fv := v.Field(i) + if !fv.CanAddr() { + continue + } + _, flatten := sf.Tag.Lookup("flatten") + if (sf.Anonymous || flatten) && shouldFlatten(fv) { + ev, err := derefStruct(fv) + if err != nil { + continue + } + bind(ctx, ev) + continue + } + if key := ctxName(sf); key != "" && (fv.Kind() != reflect.Pointer || !fv.IsNil()) { + put(ctx, key, storedValue(rvalue{fv}.settable())) + } + if fv.Kind() == reflect.Pointer && !fv.IsNil() && fv.Type().Elem().Kind() == reflect.Struct { + if _, ok := commandName(sf, fv); ok { + bind(ctx, rvalue{fv}.settable()) + } + } + } +} + +func storedValue(fv reflect.Value) any { + switch fv.Kind() { + case reflect.Slice, reflect.Array: + return unwrapSeq(fv) + } + if (rvalue{fv}).hasValue() { + return (rvalue{fv}).callValue() + } + return fv.Interface() +} + +func unwrapSeq(fv reflect.Value) any { + outT, ok := (rvalue{reflect.New(fv.Type().Elem())}).valueType() + if !ok { + return fv.Interface() + } + n := fv.Len() + var out reflect.Value + if fv.Kind() == reflect.Array { + out = reflect.New(reflect.ArrayOf(n, outT)).Elem() + } else { + out = reflect.MakeSlice(reflect.SliceOf(outT), n, n) + } + for i := range n { + out.Index(i).Set(reflect.ValueOf((rvalue{fv.Index(i)}).callValue())) + } + return out.Interface() +} + +func (v rvalue) valueType() (reflect.Type, bool) { + m := v.ptr().MethodByName("Value") + if !m.IsValid() { + return nil, false + } + t := m.Type() + if t.NumIn() != 0 || t.NumOut() != 1 { + return nil, false + } + return t.Out(0), true +} + +func (v rvalue) hasValue() bool { + _, ok := v.valueType() + return ok +} + +func (v rvalue) callValue() any { + return v.ptr().MethodByName("Value").Call(nil)[0].Interface() +} diff --git a/x/cmd/ctx_test.go b/x/cmd/ctx_test.go new file mode 100644 index 000000000..25fb99a91 --- /dev/null +++ b/x/cmd/ctx_test.go @@ -0,0 +1,144 @@ +package cmd + +import ( + "context" + "log/slog" + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetAppFlags(t *testing.T) { + app, err := Parse[App[None]]("-vv", "--profile-dir", "/tmp/p") + require.NoError(t, err) + ctx := withValues(t.Context()) + bind(ctx, reflect.ValueOf(&app).Elem()) + assert.Equal(t, 2, Get[int](ctx, "verbose")) + assert.Equal(t, "/tmp/p", Get[string](ctx, "profile-dir")) + assert.False(t, Get[bool](ctx, "help")) + assert.False(t, Get[bool](ctx, "version")) +} + +type ctxLeaf struct { + got int + dir string +} + +func (l *ctxLeaf) Run(ctx context.Context) error { + l.got = Get[int](ctx, "verbose") + l.dir = Get[string](ctx, "profile-dir") + return nil +} + +type ctxRoot struct { + leaf *ctxLeaf +} + +func TestGetParentFlagAfterCommand(t *testing.T) { + prev := slog.Default() + t.Cleanup(func() { slog.SetDefault(prev) }) + + app, err := Parse[App[ctxRoot]]("leaf", "-vv", "--profile-dir", "/tmp/x") + require.NoError(t, err) + require.NoError(t, app.Run(t.Context())) + require.NotNil(t, app.Args.leaf) + assert.Equal(t, 2, app.Args.leaf.got) + assert.Equal(t, "/tmp/x", app.Args.leaf.dir) +} + +func TestGetUnwrapsArgAndSlice(t *testing.T) { + type args struct { + name StringArg `long:"name" default:"" ctx:"name"` + tag []StringArg `long:"tag" ctx:"tag"` + n Count `long:"n" ctx:"n"` + ok Flag `long:"ok" ctx:"ok"` + } + got, err := Parse[args]("--name", "Ada", "--tag", "a", "--tag", "b", "--n", "3", "--ok") + require.NoError(t, err) + ctx := withValues(t.Context()) + bind(ctx, reflect.ValueOf(&got).Elem()) + assert.Equal(t, "Ada", Get[string](ctx, "name")) + assert.Equal(t, []string{"a", "b"}, Get[[]string](ctx, "tag")) + assert.Equal(t, 3, Get[int](ctx, "n")) + assert.True(t, Get[bool](ctx, "ok")) +} + +func TestEmptyCtxUsesLong(t *testing.T) { + type args struct { + name StringArg `long:"name" default:"" ctx:""` + } + got, err := Parse[args]("--name", "Ada") + require.NoError(t, err) + ctx := withValues(t.Context()) + bind(ctx, reflect.ValueOf(&got).Elem()) + assert.Equal(t, "Ada", Get[string](ctx, "name")) +} + +func TestEmptyCtxUsesFieldName(t *testing.T) { + type args struct { + path StringArg `ctx:"" default:"."` + } + got, err := Parse[args]() + require.NoError(t, err) + ctx := withValues(t.Context()) + bind(ctx, reflect.ValueOf(&got).Elem()) + assert.Equal(t, ".", Get[string](ctx, "path")) +} + +func TestUntaggedNotInBag(t *testing.T) { + type args struct { + name StringArg `long:"name" default:""` + } + got, err := Parse[args]("--name", "Ada") + require.NoError(t, err) + ctx := withValues(t.Context()) + bind(ctx, reflect.ValueOf(&got).Elem()) + assert.PanicsWithValue(t, `cmd: context key "name" not set`, func() { + Get[string](ctx, "name") + }) +} + +func TestDuplicateCtx(t *testing.T) { + type args struct { + a StringArg `long:"a" default:"" ctx:"x"` + b StringArg `long:"b" default:"" ctx:"x"` + } + _, err := Parse[args]() + assert.ErrorIs(t, err, ErrInvalidSpec) +} + +func TestGetMissing(t *testing.T) { + ctx := withValues(t.Context()) + assert.PanicsWithValue(t, `cmd: context key "nope" not set`, func() { + Get[int](ctx, "nope") + }) +} + +func TestGetWrongType(t *testing.T) { + ctx := withValues(t.Context()) + put(ctx, "verbose", 2) + assert.PanicsWithValue(t, `cmd: context key "verbose" is int, not string`, func() { + Get[string](ctx, "verbose") + }) +} + +func TestGetNoBag(t *testing.T) { + assert.PanicsWithValue(t, "cmd: context has no values", func() { + Get[int](t.Context(), "verbose") + }) +} + +func TestNilPointerSkipped(t *testing.T) { + type args struct { + name *StringArg `ctx:"name"` + } + got, err := Parse[args]() + require.NoError(t, err) + ctx := withValues(t.Context()) + bind(ctx, reflect.ValueOf(&got).Elem()) + assert.PanicsWithValue(t, `cmd: context key "name" not set`, func() { + Get[string](ctx, "name") + }) +} diff --git a/x/cmd/parse.go b/x/cmd/parse.go index 4b1e875e2..268a6b5bd 100644 --- a/x/cmd/parse.go +++ b/x/cmd/parse.go @@ -34,6 +34,7 @@ type field struct { def string hasDef bool env string + ctx string optional bool maybePos bool } @@ -44,6 +45,7 @@ type spec struct { longs map[string]int shorts map[rune]int cmds map[string]int + ctxs map[string]int pos []int set []bool counts []int @@ -76,6 +78,7 @@ func newSpec(root reflect.Value) (*spec, error) { longs: make(map[string]int), shorts: make(map[rune]int), cmds: make(map[string]int), + ctxs: make(map[string]int), } if err := s.addStruct(root, nil); err != nil { return nil, err @@ -252,7 +255,7 @@ func newField(sf reflect.StructField, fv reflect.Value) (field, bool, error) { return field{}, false, err } tagged := long != "" || short != 0 - f := field{index: sf.Index, long: long, short: short, help: sf.Tag.Get("help"), env: sf.Tag.Get("env")} + f := field{index: sf.Index, long: long, short: short, help: sf.Tag.Get("help"), env: sf.Tag.Get("env"), ctx: ctxName(sf)} if d, ok := sf.Tag.Lookup("default"); ok { f.def = d f.hasDef = true @@ -391,6 +394,12 @@ func (s *spec) add(f field) error { } s.cmds[f.cmd] = idx } + if f.ctx != "" { + if _, ok := s.ctxs[f.ctx]; ok { + return fmt.Errorf("%w: duplicate ctx %s", ErrInvalidSpec, f.ctx) + } + s.ctxs[f.ctx] = idx + } if isPosKind(f.kind) { s.pos = append(s.pos, idx) } From 3a5abc5888427f62e0536093b2bf0be9c744fa8b Mon Sep 17 00:00:00 2001 From: "lewtec-bot[bot]" <252450460+lewtec-bot[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:16:56 -0300 Subject: [PATCH 2/3] fix(x/cmd): sentinel errors for Get panics ErrNoValues, ErrNotSet, ErrWrongType so tests can errors.Is. --- x/cmd/args.go | 3 +++ x/cmd/ctx.go | 12 ++++++------ x/cmd/ctx_test.go | 23 ++++++++++++++++++----- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/x/cmd/args.go b/x/cmd/args.go index 6545c9a51..8f9507a60 100644 --- a/x/cmd/args.go +++ b/x/cmd/args.go @@ -14,6 +14,9 @@ var ( ErrMissingValue = errors.New("missing value") ErrInvalidSpec = errors.New("invalid command spec") ErrUnknownCommand = errors.New("unknown command") + ErrNoValues = errors.New("context has no values") + ErrNotSet = errors.New("context key not set") + ErrWrongType = errors.New("wrong type") ) type Parser interface { diff --git a/x/cmd/ctx.go b/x/cmd/ctx.go index 32658fb11..cf2dbbc22 100644 --- a/x/cmd/ctx.go +++ b/x/cmd/ctx.go @@ -11,20 +11,20 @@ type bagKey struct{} type valueBag map[string]any -// Get returns the value stored under key. It panics if the context has no -// value bag, the key is missing, or v is not a T. +// Get returns the value stored under key. It panics with ErrNoValues, +// ErrNotSet, or ErrWrongType. func Get[T any](ctx context.Context, key string) T { b, ok := ctx.Value(bagKey{}).(valueBag) if !ok { - panic("cmd: context has no values") + panic(ErrNoValues) } v, ok := b[key] if !ok { - panic(`cmd: context key "` + key + `" not set`) + panic(fmt.Errorf("%w: %s", ErrNotSet, key)) } t, ok := v.(T) if !ok { - panic(fmt.Sprintf("cmd: context key %q is %T, not %T", key, v, *new(T))) + panic(fmt.Errorf("%w: %q is %T, not %T", ErrWrongType, key, v, *new(T))) } return t } @@ -39,7 +39,7 @@ func withValues(ctx context.Context) context.Context { func put(ctx context.Context, key string, v any) { b, ok := ctx.Value(bagKey{}).(valueBag) if !ok { - panic("cmd: context has no values") + panic(ErrNoValues) } b[key] = v } diff --git a/x/cmd/ctx_test.go b/x/cmd/ctx_test.go index 25fb99a91..75fcef8e6 100644 --- a/x/cmd/ctx_test.go +++ b/x/cmd/ctx_test.go @@ -95,7 +95,7 @@ func TestUntaggedNotInBag(t *testing.T) { require.NoError(t, err) ctx := withValues(t.Context()) bind(ctx, reflect.ValueOf(&got).Elem()) - assert.PanicsWithValue(t, `cmd: context key "name" not set`, func() { + assertPanicIs(t, ErrNotSet, func() { Get[string](ctx, "name") }) } @@ -111,7 +111,7 @@ func TestDuplicateCtx(t *testing.T) { func TestGetMissing(t *testing.T) { ctx := withValues(t.Context()) - assert.PanicsWithValue(t, `cmd: context key "nope" not set`, func() { + assertPanicIs(t, ErrNotSet, func() { Get[int](ctx, "nope") }) } @@ -119,13 +119,13 @@ func TestGetMissing(t *testing.T) { func TestGetWrongType(t *testing.T) { ctx := withValues(t.Context()) put(ctx, "verbose", 2) - assert.PanicsWithValue(t, `cmd: context key "verbose" is int, not string`, func() { + assertPanicIs(t, ErrWrongType, func() { Get[string](ctx, "verbose") }) } func TestGetNoBag(t *testing.T) { - assert.PanicsWithValue(t, "cmd: context has no values", func() { + assertPanicIs(t, ErrNoValues, func() { Get[int](t.Context(), "verbose") }) } @@ -138,7 +138,20 @@ func TestNilPointerSkipped(t *testing.T) { require.NoError(t, err) ctx := withValues(t.Context()) bind(ctx, reflect.ValueOf(&got).Elem()) - assert.PanicsWithValue(t, `cmd: context key "name" not set`, func() { + assertPanicIs(t, ErrNotSet, func() { Get[string](ctx, "name") }) } + +func assertPanicIs(t *testing.T, want error, fn func()) { + t.Helper() + var got any + func() { + defer func() { got = recover() }() + fn() + }() + require.NotNil(t, got) + err, ok := got.(error) + require.True(t, ok) + assert.ErrorIs(t, err, want) +} From f7acc8efdc851a952013f1d72df2e20fde1a40c9 Mon Sep 17 00:00:00 2001 From: "lewtec-bot[bot]" <252450460+lewtec-bot[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:19:29 -0300 Subject: [PATCH 3/3] test(x/cmd): use PanicsWithError for Get Drop the recover helper. testify already compares Error(). --- x/cmd/ctx_test.go | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/x/cmd/ctx_test.go b/x/cmd/ctx_test.go index 75fcef8e6..8c117282a 100644 --- a/x/cmd/ctx_test.go +++ b/x/cmd/ctx_test.go @@ -95,7 +95,7 @@ func TestUntaggedNotInBag(t *testing.T) { require.NoError(t, err) ctx := withValues(t.Context()) bind(ctx, reflect.ValueOf(&got).Elem()) - assertPanicIs(t, ErrNotSet, func() { + assert.PanicsWithError(t, "context key not set: name", func() { Get[string](ctx, "name") }) } @@ -111,7 +111,7 @@ func TestDuplicateCtx(t *testing.T) { func TestGetMissing(t *testing.T) { ctx := withValues(t.Context()) - assertPanicIs(t, ErrNotSet, func() { + assert.PanicsWithError(t, "context key not set: nope", func() { Get[int](ctx, "nope") }) } @@ -119,13 +119,13 @@ func TestGetMissing(t *testing.T) { func TestGetWrongType(t *testing.T) { ctx := withValues(t.Context()) put(ctx, "verbose", 2) - assertPanicIs(t, ErrWrongType, func() { + assert.PanicsWithError(t, `wrong type: "verbose" is int, not string`, func() { Get[string](ctx, "verbose") }) } func TestGetNoBag(t *testing.T) { - assertPanicIs(t, ErrNoValues, func() { + assert.PanicsWithError(t, "context has no values", func() { Get[int](t.Context(), "verbose") }) } @@ -138,20 +138,7 @@ func TestNilPointerSkipped(t *testing.T) { require.NoError(t, err) ctx := withValues(t.Context()) bind(ctx, reflect.ValueOf(&got).Elem()) - assertPanicIs(t, ErrNotSet, func() { + assert.PanicsWithError(t, "context key not set: name", func() { Get[string](ctx, "name") }) } - -func assertPanicIs(t *testing.T, want error, fn func()) { - t.Helper() - var got any - func() { - defer func() { got = recover() }() - fn() - }() - require.NotNil(t, got) - err, ok := got.(error) - require.True(t, ok) - assert.ErrorIs(t, err, want) -}