Parse invocation flags across command discovery

This commit is contained in:
2026-11-22 20:53:25 +00:00
parent ea3ce25001
commit b6cb183a71
10 changed files with 136 additions and 30 deletions

View File

@@ -35,7 +35,7 @@ func resolveCompletionContext(snapshot *routingSnapshot, completed []string, cur
context.aliases = snapshot.flagAliases[context.route.canonicalPath.Key()].lookupRecords() context.aliases = snapshot.flagAliases[context.route.canonicalPath.Key()].lookupRecords()
context.commandPosition = len(context.tail) == 0 context.commandPosition = len(context.tail) == 0
case routeDiscovery: 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.tail = append([]string(nil), context.route.args...)
context.aliases = snapshot.discoveryFlags[context.route.discoveryPath.Key()].lookupRecords() context.aliases = snapshot.discoveryFlags[context.route.discoveryPath.Key()].lookupRecords()
} }

View File

@@ -35,7 +35,7 @@ type completionFlagState struct {
func completionFlags(context completionContext) []commandmeta.Flag { func completionFlags(context completionContext) []commandmeta.Flag {
flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1) flags := make([]commandmeta.Flag, 0, len(context.command.Flags)+len(context.command.CoreFlags)+1)
flags = append(flags, commandmeta.HelpFlag()) 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 return flags
} }

View File

@@ -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 ## 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 1. Extend neutral command metadata with invocation-feature flags separate from
consumer-local flags and fixed reporting flags. Extend parser results with consumer-local flags and fixed reporting flags. Extend parser results with
corresponding raw values/spellings. Preserve the existing consumer binding corresponding raw values/spellings. Preserve the existing consumer binding

View File

@@ -45,6 +45,8 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
handlerRan := false handlerRan := false
if parsed.Failure != nil { if parsed.Failure != nil {
outcome = Usage(parsed.Failure.Message) 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 { } else if current.route.kind == routeDiscovery {
if parsed.HelpRequested { if parsed.HelpRequested {
outcome = current.renderHelp(parsed.Path) 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) 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 { type execution struct {
app *App app *App
ctx context.Context ctx context.Context
reporter *Reporter reporter *Reporter
debugEvents []string featureStarts []func(Invocation) (context.Context, func() Report)
snapshot *routingSnapshot debugEvents []string
session *internalcobra.Session snapshot *routingSnapshot
route routeResult session *internalcobra.Session
route routeResult
} }
type commandExecution struct { type commandExecution struct {

View File

@@ -17,6 +17,7 @@ func (a *App) helpView(route routeResult, snapshot *routingSnapshot) commandmeta
if snapshot == nil { if snapshot == nil {
return view return view
} }
view.CoreFlags = append(append([]commandmeta.Flag(nil), snapshot.featureFlags...), view.CoreFlags...)
view.CommandAliases = routeHelpAliases(snapshot, route) view.CommandAliases = routeHelpAliases(snapshot, route)
if view.Discovery { if view.Discovery {
view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords() view.FlagAliases = snapshot.discoveryFlags[route.discoveryPath.Key()].neutralRecords()

View File

@@ -77,7 +77,7 @@ func (session *Session) Parse(argv []string) commandmeta.Result {
} }
remaining := append(commandpath.CloneTokens(unconsumed), tail...) 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 aliases := session.flagAliases
if session.flagAliasesForPath != nil { if session.flagAliasesForPath != nil {
aliases = session.flagAliasesForPath(result.Path) aliases = session.flagAliasesForPath(result.Path)
@@ -115,6 +115,15 @@ func (session *Session) Parse(argv []string) commandmeta.Result {
result.FlagSpellings[index] = raw.spellingsCopy() 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 { if helpFlag := selected.Flags().Lookup("help"); helpFlag != nil {
helpRequested, err := helpFlag.Value.(*rawValue).lastBool() helpRequested, err := helpFlag.Value.(*rawValue).lastBool()
if err != nil { if err != nil {
@@ -271,7 +280,7 @@ func (session *Session) UsageLine(path []string) (string, *commandmeta.Failure)
if flag.Name != "debug" || !flag.Boolean { if flag.Name != "debug" || !flag.Boolean {
continue 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" { if effective.Name == "debug" {
spelling := "--debug" spelling := "--debug"
if effective.Short != "" { if effective.Short != "" {
@@ -330,7 +339,7 @@ func buildTree(root *commandmeta.Command) (*spfcobra.Command, map[*spfcobra.Comm
helpFlag := backend.Flags().Lookup("help") helpFlag := backend.Flags().Lookup("help")
helpFlag.NoOptDefVal = "true" helpFlag.NoOptDefVal = "true"
helpFlag.Usage = "help for this command (default: false)" 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} value := &rawValue{boolean: declarationFlag.Boolean}
backend.Flags().VarP(value, declarationFlag.Name, declarationFlag.Short, flagUsage(declarationFlag)) backend.Flags().VarP(value, declarationFlag.Name, declarationFlag.Short, flagUsage(declarationFlag))
backendFlag := backend.Flags().Lookup(declarationFlag.Name) backendFlag := backend.Flags().Lookup(declarationFlag.Name)

View File

@@ -16,9 +16,10 @@ type Command struct {
Runnable bool Runnable bool
Flags []Flag Flags []Flag
// CoreFlags are parsed by CommandKit but do not occupy consumer binding indexes. // CoreFlags are parsed by CommandKit but do not occupy consumer binding indexes.
CoreFlags []Flag CoreFlags []Flag
Arguments []Argument InvocationFlags []Flag
Children []*Command Arguments []Argument
Children []*Command
} }
// Argument describes one positional input for usage rendering. // 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. // Result contains the selected command and raw input collected by the adapter.
type Result struct { type Result struct {
Key Key Key Key
Path []string Path []string
HelpRequested bool HelpRequested bool
FlagValues [][]string FlagValues [][]string
FlagSpellings [][]string FlagSpellings [][]string
FlagOccurrences []FlagOccurrence InvocationFlagValues [][]string
Reporting ReportingSelection InvocationFlagSpellings [][]string
Operands []string FlagOccurrences []FlagOccurrence
Failure *Failure Reporting ReportingSelection
Operands []string
Failure *Failure
} }
// ParseOptions selects flag aliases for parser contexts. // ParseOptions selects flag aliases for parser contexts.

View File

@@ -23,6 +23,7 @@ type InvocationFeatureSpec[I any] struct {
type invocationFeaturePayload interface { type invocationFeaturePayload interface {
bridgeFlags() []commandmeta.Flag bridgeFlags() []commandmeta.Flag
prepare([][]string, [][]string, []commandmeta.FlagOccurrence, bool) (func(Invocation) (context.Context, func() Report), error)
} }
type typedInvocationFeature[I any] struct{ spec InvocationFeatureSpec[I] } 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() 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 { type invocationFeatureRecord struct {
payload invocationFeaturePayload payload invocationFeaturePayload
issues []error issues []error

View File

@@ -5,6 +5,9 @@ import (
"errors" "errors"
"strings" "strings"
"testing" "testing"
internalcobra "go.maximumdirect.net/commandkit/internal/cobra"
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
) )
func TestInvocationFeatureCaptureAndInstallation(t *testing.T) { func TestInvocationFeatureCaptureAndInstallation(t *testing.T) {
@@ -95,3 +98,56 @@ func TestInvocationFeatureRegistrationOrderAndAliasCollision(t *testing.T) {
t.Fatalf("feature alias rejected: %v", err) 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)
}
}
}

View File

@@ -71,7 +71,7 @@ func (a *App) routeSnapshot() *routingSnapshot {
} }
func (a *App) buildRoutingSnapshot() *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{ snapshot := &routingSnapshot{
metadata: root, metadata: root,
runners: make(map[commandmeta.Key]commandPayload), runners: make(map[commandmeta.Key]commandPayload),
@@ -113,11 +113,12 @@ func bridgeCommand(node *canonicalNode, snapshot *routingSnapshot, next *command
record := node.command.record record := node.command.record
*next = *next + 1 *next = *next + 1
declaration := &commandmeta.Command{ declaration := &commandmeta.Command{
Key: *next, Key: *next,
Name: record.name, Name: record.name,
Summary: record.summary, Summary: record.summary,
Description: record.description, Description: record.description,
CoreFlags: commandmeta.ReportingFlags(), CoreFlags: commandmeta.ReportingFlags(),
InvocationFlags: snapshot.featureFlags,
} }
node.metadata = declaration node.metadata = declaration
if record.payload != nil { if record.payload != nil {