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/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 new file mode 100644 index 000000000..cf2dbbc22 --- /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 with ErrNoValues, +// ErrNotSet, or ErrWrongType. +func Get[T any](ctx context.Context, key string) T { + b, ok := ctx.Value(bagKey{}).(valueBag) + if !ok { + panic(ErrNoValues) + } + v, ok := b[key] + if !ok { + panic(fmt.Errorf("%w: %s", ErrNotSet, key)) + } + t, ok := v.(T) + if !ok { + panic(fmt.Errorf("%w: %q is %T, not %T", ErrWrongType, 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(ErrNoValues) + } + 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..8c117282a --- /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.PanicsWithError(t, "context key not set: name", 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.PanicsWithError(t, "context key not set: nope", func() { + Get[int](ctx, "nope") + }) +} + +func TestGetWrongType(t *testing.T) { + ctx := withValues(t.Context()) + put(ctx, "verbose", 2) + assert.PanicsWithError(t, `wrong type: "verbose" is int, not string`, func() { + Get[string](ctx, "verbose") + }) +} + +func TestGetNoBag(t *testing.T) { + assert.PanicsWithError(t, "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.PanicsWithError(t, "context key not set: name", 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) }