diff --git a/completion_context.go b/completion_context.go index 2ec7ff8..c051afa 100644 --- a/completion_context.go +++ b/completion_context.go @@ -35,7 +35,7 @@ func resolveCompletionContext(snapshot *routingSnapshot, completed []string, cur context.aliases = snapshot.flagAliases[context.route.canonicalPath.Key()].lookupRecords() context.commandPosition = len(context.tail) == 0 case routeDiscovery: - context.command = &commandmeta.Command{CoreFlags: commandmeta.ReportingFlags()} + context.command = &commandmeta.Command{CoreFlags: commandmeta.ReportingFlags(), InvocationFlags: snapshot.featureFlags} context.tail = append([]string(nil), context.route.args...) context.aliases = snapshot.discoveryFlags[context.route.discoveryPath.Key()].lookupRecords() } diff --git a/completion_flags.go b/completion_flags.go index 15dfe32..9118b2d 100644 --- a/completion_flags.go +++ b/completion_flags.go @@ -35,7 +35,7 @@ type completionFlagState struct { func completionFlags(context completionContext) []commandmeta.Flag { flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1) flags = append(flags, commandmeta.HelpFlag()) - flags = append(flags, commandmeta.EffectiveFlags(context.command.Flags, context.command.CoreFlags)...) + flags = append(flags, commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), context.command.Flags...), context.command.InvocationFlags...), context.command.CoreFlags)...) return flags } diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index aca4421..146a0a1 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -166,6 +166,10 @@ rollback. Full parsing and dispatch checks follow their implementation stages. ## Stage 2: Carry invocation flags through parsing, help, aliases, and completion +**Complete.** Invocation metadata and raw values remain separate from local +bindings; focused feature tests exercise aliases, repeated values, conversion +errors, help and completion, and the Go 1.27.4 core suite passes. + 1. Extend neutral command metadata with invocation-feature flags separate from consumer-local flags and fixed reporting flags. Extend parser results with corresponding raw values/spellings. Preserve the existing consumer binding diff --git a/execute.go b/execute.go index 051f55b..2ef5328 100644 --- a/execute.go +++ b/execute.go @@ -45,6 +45,8 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco handlerRan := false if parsed.Failure != nil { outcome = Usage(parsed.Failure.Message) + } else if err := current.prepareFeatures(parsed, !parsed.HelpRequested && current.route.kind == routeCanonical); err != nil { + outcome = classifyInputError(err) } else if current.route.kind == routeDiscovery { if parsed.HelpRequested { outcome = current.renderHelp(parsed.Path) @@ -77,14 +79,35 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco return current.finalize(outcome, path, handlerRan) } +func (current *execution) prepareFeatures(parsed commandmeta.Result, required bool) error { + if current.snapshot == nil { + return nil + } + offset := 0 + for _, feature := range current.snapshot.features { + count := len(feature.payload.bridgeFlags()) + if offset+count > len(parsed.InvocationFlagValues) || offset+count > len(parsed.InvocationFlagSpellings) { + return fmt.Errorf("missing invocation feature flag values") + } + start, err := feature.payload.prepare(parsed.InvocationFlagValues[offset:offset+count], parsed.InvocationFlagSpellings[offset:offset+count], parsed.FlagOccurrences, required) + if err != nil { + return err + } + current.featureStarts = append(current.featureStarts, start) + offset += count + } + return nil +} + type execution struct { - app *App - ctx context.Context - reporter *Reporter - debugEvents []string - snapshot *routingSnapshot - session *internalcobra.Session - route routeResult + app *App + ctx context.Context + reporter *Reporter + featureStarts []func(Invocation) (context.Context, func() Report) + debugEvents []string + snapshot *routingSnapshot + session *internalcobra.Session + route routeResult } type commandExecution struct { diff --git a/help_view.go b/help_view.go index bc0a036..2897040 100644 --- a/help_view.go +++ b/help_view.go @@ -17,6 +17,7 @@ func (a *App) helpView(route routeResult, snapshot *routingSnapshot) commandmeta if snapshot == nil { return view } + view.CoreFlags = append(append([]commandmeta.Flag(nil), snapshot.featureFlags...), view.CoreFlags...) view.CommandAliases = routeHelpAliases(snapshot, route) if view.Discovery { view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords() diff --git a/internal/cobra/parse.go b/internal/cobra/parse.go index bc5a01e..5abb637 100644 --- a/internal/cobra/parse.go +++ b/internal/cobra/parse.go @@ -77,7 +77,7 @@ func (session *Session) Parse(argv []string) commandmeta.Result { } remaining := append(commandpath.CloneTokens(unconsumed), tail...) - localFlags := commandmeta.EffectiveFlags(selectedNode.Flags, selectedNode.CoreFlags) + localFlags := commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), selectedNode.Flags...), selectedNode.InvocationFlags...), selectedNode.CoreFlags) aliases := session.flagAliases if session.flagAliasesForPath != nil { aliases = session.flagAliasesForPath(result.Path) @@ -115,6 +115,15 @@ func (session *Session) Parse(argv []string) commandmeta.Result { result.FlagSpellings[index] = raw.spellingsCopy() } } + result.InvocationFlagValues = make([][]string, len(selectedNode.InvocationFlags)) + result.InvocationFlagSpellings = make([][]string, len(selectedNode.InvocationFlags)) + for index, flag := range selectedNode.InvocationFlags { + if value := selected.Flags().Lookup(flag.Name); value != nil { + raw := value.Value.(*rawValue) + result.InvocationFlagValues[index] = raw.valuesCopy() + result.InvocationFlagSpellings[index] = raw.spellingsCopy() + } + } if helpFlag := selected.Flags().Lookup("help"); helpFlag != nil { helpRequested, err := helpFlag.Value.(*rawValue).lastBool() if err != nil { @@ -271,7 +280,7 @@ func (session *Session) UsageLine(path []string) (string, *commandmeta.Failure) if flag.Name != "debug" || !flag.Boolean { continue } - for _, effective := range commandmeta.EffectiveFlags(declaration.Flags, declaration.CoreFlags) { + for _, effective := range commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), declaration.Flags...), declaration.InvocationFlags...), declaration.CoreFlags) { if effective.Name == "debug" { spelling := "--debug" if effective.Short != "" { @@ -330,7 +339,7 @@ func buildTree(root *commandmeta.Command) (*spfcobra.Command, map[*spfcobra.Comm helpFlag := backend.Flags().Lookup("help") helpFlag.NoOptDefVal = "true" helpFlag.Usage = "help for this command (default: false)" - for _, declarationFlag := range commandmeta.EffectiveFlags(declaration.Flags, declaration.CoreFlags) { + for _, declarationFlag := range commandmeta.EffectiveFlags(append(append([]commandmeta.Flag(nil), declaration.Flags...), declaration.InvocationFlags...), declaration.CoreFlags) { value := &rawValue{boolean: declarationFlag.Boolean} backend.Flags().VarP(value, declarationFlag.Name, declarationFlag.Short, flagUsage(declarationFlag)) backendFlag := backend.Flags().Lookup(declarationFlag.Name) diff --git a/internal/commandmeta/metadata.go b/internal/commandmeta/metadata.go index 0daab59..47ae3b8 100644 --- a/internal/commandmeta/metadata.go +++ b/internal/commandmeta/metadata.go @@ -16,9 +16,10 @@ type Command struct { Runnable bool Flags []Flag // CoreFlags are parsed by CommandKit but do not occupy consumer binding indexes. - CoreFlags []Flag - Arguments []Argument - Children []*Command + CoreFlags []Flag + InvocationFlags []Flag + Arguments []Argument + Children []*Command } // Argument describes one positional input for usage rendering. @@ -196,15 +197,17 @@ type ReportingSelection struct { // Result contains the selected command and raw input collected by the adapter. type Result struct { - Key Key - Path []string - HelpRequested bool - FlagValues [][]string - FlagSpellings [][]string - FlagOccurrences []FlagOccurrence - Reporting ReportingSelection - Operands []string - Failure *Failure + Key Key + Path []string + HelpRequested bool + FlagValues [][]string + FlagSpellings [][]string + InvocationFlagValues [][]string + InvocationFlagSpellings [][]string + FlagOccurrences []FlagOccurrence + Reporting ReportingSelection + Operands []string + Failure *Failure } // ParseOptions selects flag aliases for parser contexts. diff --git a/invocation_feature.go b/invocation_feature.go index bfecaf7..cf8c282 100644 --- a/invocation_feature.go +++ b/invocation_feature.go @@ -23,6 +23,7 @@ type InvocationFeatureSpec[I any] struct { type invocationFeaturePayload interface { bridgeFlags() []commandmeta.Flag + prepare([][]string, [][]string, []commandmeta.FlagOccurrence, bool) (func(Invocation) (context.Context, func() Report), error) } type typedInvocationFeature[I any] struct{ spec InvocationFeatureSpec[I] } @@ -31,6 +32,14 @@ func (f typedInvocationFeature[I]) bridgeFlags() []commandmeta.Flag { return (typedCommand[I]{spec: CommandSpec[I]{Flags: f.spec.Flags}}).bridgeFlags() } +func (f typedInvocationFeature[I]) prepare(values, spellings [][]string, occurrences []commandmeta.FlagOccurrence, required bool) (func(Invocation) (context.Context, func() Report), error) { + input, err := prepareInputWithOccurrences(CommandSpec[I]{NewInput: f.spec.NewInput, Flags: f.spec.Flags}, values, spellings, occurrences, nil, required) + if err != nil { + return nil, err + } + return func(inv Invocation) (context.Context, func() Report) { return f.spec.Start(inv, input.build()) }, nil +} + type invocationFeatureRecord struct { payload invocationFeaturePayload issues []error diff --git a/invocation_feature_test.go b/invocation_feature_test.go index c39bb93..4ee1c84 100644 --- a/invocation_feature_test.go +++ b/invocation_feature_test.go @@ -5,6 +5,9 @@ import ( "errors" "strings" "testing" + + internalcobra "go.maximumdirect.net/commandkit/internal/cobra" + commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta" ) func TestInvocationFeatureCaptureAndInstallation(t *testing.T) { @@ -95,3 +98,56 @@ func TestInvocationFeatureRegistrationOrderAndAliasCollision(t *testing.T) { t.Fatalf("feature alias rejected: %v", err) } } + +func TestInvocationFeatureFlagsParseAndDiscover(t *testing.T) { + type featureInput struct{ selected Supplied[bool] } + constructed := 0 + feature := NewInvocationFeature(InvocationFeatureSpec[featureInput]{ + NewInput: func() featureInput { constructed++; return featureInput{} }, + Flags: []Flag[featureInput]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(i *featureInput, v Supplied[bool]) { i.selected = v })}, + Start: func(inv Invocation, _ featureInput) (context.Context, func() Report) { + t.Fatal("unexpected start") + return nil, nil + }, + }) + type localInput struct{ name string } + var got string + cmd := NewCommand(CommandSpec[localInput]{Name: "run", Flags: []Flag[localInput]{ValueFlag(FlagMeta{Name: "name"}, (*string)(nil), func(s string) (string, error) { return s, nil }, func(i *localInput, v Supplied[string]) { i.name = v.Value })}, Run: func(_ Invocation, i localInput) Outcome { got = i.name; return Success() }}) + app, err := New(Identity{Name: "test"}, WithInvocationFeature(cmd, feature), Alias("short path", "run"), FlagAlias("--watch", "--observe")) + if err != nil { + t.Fatal(err) + } + if out := app.Execute(context.Background(), []string{"run", "--watch", "--observe=false", "--name=ok"}, Streams{}); out.Status != 0 || got != "ok" { + t.Fatalf("result=%#v name=%q", out, got) + } + if out := app.Execute(context.Background(), []string{"run", "--observe=bad", "--observe=true"}, Streams{}); out.Kind != OutcomeUsage { + t.Fatalf("invalid earlier occurrence: %#v", out) + } + if out := app.Execute(context.Background(), []string{"run", "--observe=bad", "--help"}, Streams{}); out.Kind != OutcomeUsage { + t.Fatalf("help invalid flag: %#v", out) + } + if constructed != 0 { + t.Fatal("input constructed before execution boundary") + } + snapshot := app.routeSnapshot() + for _, path := range [][]string{nil, {"run"}, {"short"}} { + route := resolveEnteredRoute(path, snapshot) + view := app.helpView(route, snapshot) + session := internalcobra.Prepare(snapshot.metadata, commandmeta.ParseOptions{}) + content, failure := session.RenderHelpView(view) + if failure != nil || !strings.Contains(content, "--observe") { + t.Fatalf("help %v: %q %#v", path, content, failure) + } + ctx := resolveCompletionContext(snapshot, path, "--obs") + target := completionTargetFor(snapshot, ctx) + found := false + for _, choice := range target.choices { + if choice.Value == "--observe" { + found = true + } + } + if !found { + t.Fatalf("completion %v: %#v", path, target) + } + } +} diff --git a/parser.go b/parser.go index 5952f04..0195ede 100644 --- a/parser.go +++ b/parser.go @@ -71,7 +71,7 @@ func (a *App) routeSnapshot() *routingSnapshot { } func (a *App) buildRoutingSnapshot() *routingSnapshot { - root := &commandmeta.Command{Name: a.identity.Name, CoreFlags: commandmeta.ReportingFlags()} + root := &commandmeta.Command{Name: a.identity.Name, CoreFlags: commandmeta.ReportingFlags(), InvocationFlags: a.featureFlags} snapshot := &routingSnapshot{ metadata: root, runners: make(map[commandmeta.Key]commandPayload), @@ -113,11 +113,12 @@ func bridgeCommand(node *canonicalNode, snapshot *routingSnapshot, next *command record := node.command.record *next = *next + 1 declaration := &commandmeta.Command{ - Key: *next, - Name: record.name, - Summary: record.summary, - Description: record.description, - CoreFlags: commandmeta.ReportingFlags(), + Key: *next, + Name: record.name, + Summary: record.summary, + Description: record.description, + CoreFlags: commandmeta.ReportingFlags(), + InvocationFlags: snapshot.featureFlags, } node.metadata = declaration if record.payload != nil {