Capture and validate invocation features
This commit is contained in:
4
app.go
4
app.go
@@ -16,6 +16,8 @@ type App struct {
|
||||
aliases *alias.Resolver
|
||||
flagAliases map[string]resolvedFlagAliases
|
||||
discoveryFlags map[string]resolvedFlagAliases
|
||||
features []*invocationFeatureRecord
|
||||
featureFlags []commandmeta.Flag
|
||||
snapshot *routingSnapshot
|
||||
}
|
||||
|
||||
@@ -27,6 +29,8 @@ type routingSnapshot struct {
|
||||
commandAliases []commandmeta.CommandAlias
|
||||
flagAliases map[string]resolvedFlagAliases
|
||||
discoveryFlags map[string]resolvedFlagAliases
|
||||
features []*invocationFeatureRecord
|
||||
featureFlags []commandmeta.Flag
|
||||
completion bool
|
||||
}
|
||||
|
||||
|
||||
10
command.go
10
command.go
@@ -71,6 +71,7 @@ type commandRecord struct {
|
||||
summary string
|
||||
description string
|
||||
children []Command
|
||||
features []InvocationFeature
|
||||
payload commandPayload
|
||||
issues []error
|
||||
rootOnly bool
|
||||
@@ -467,6 +468,15 @@ func validateCommandPlacement(command Command) error {
|
||||
issues = append(issues, issue)
|
||||
}
|
||||
}
|
||||
for _, feature := range record.features {
|
||||
if feature.record == nil {
|
||||
issues = append(issues, fmt.Errorf("command %q: invalid zero invocation feature", record.name))
|
||||
continue
|
||||
}
|
||||
for _, issue := range feature.record.issues {
|
||||
issues = append(issues, fmt.Errorf("command %q invocation feature: %w", record.name, issue))
|
||||
}
|
||||
}
|
||||
if record.rootOnly && !root {
|
||||
issues = append(issues, fmt.Errorf("root-only command %q is nested beneath another command", label))
|
||||
}
|
||||
|
||||
@@ -133,6 +133,11 @@ The proposed API and wiring are reviewed with this plan, before implementation.
|
||||
|
||||
## Stage 1: Capture features and validate their installation
|
||||
|
||||
**Complete.** Captured features, installation-wide collision and alias validation,
|
||||
reusable handles, absence handling, and atomic registration are covered by
|
||||
`TestInvocationFeature*`; the core `GOTOOLCHAIN=local go test ./...` suite passed
|
||||
with Go 1.27.4.
|
||||
|
||||
1. Add the selected public API, preferably in a focused root `invocation_feature.go`,
|
||||
with private typed payloads analogous to `typedCommand`. Copy captured flag
|
||||
collections; retain callbacks under existing caller-ownership rules. Add
|
||||
|
||||
@@ -67,7 +67,7 @@ func (spelling capturedFlagSpelling) token() string {
|
||||
func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, aliases interface {
|
||||
Resolve(commandpath.Path) commandpath.Path
|
||||
ProperSourcePrefixes() []commandpath.Path
|
||||
}) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
|
||||
}, features []commandmeta.Flag) (map[string]resolvedFlagAliases, map[string]resolvedFlagAliases, error) {
|
||||
canonicalNodes := indexCanonicalNodes(roots)
|
||||
global := make(map[string]flagAliasMapping)
|
||||
scoped := make(map[string]map[string]flagAliasMapping)
|
||||
@@ -97,6 +97,15 @@ func compileFlagAliases(rules []RoutingRule, roots map[string]*canonicalNode, al
|
||||
canonicalContexts[key] = flagAliasContext{path: node.path.Clone(), canonical: canonicalFlagSpellings(node.command)}
|
||||
}
|
||||
discoveryContexts := discoverFlagContexts(rules, roots, aliases, canonicalNodes)
|
||||
for _, contexts := range []map[string]flagAliasContext{canonicalContexts, discoveryContexts} {
|
||||
for _, context := range contexts {
|
||||
for _, flag := range features {
|
||||
for _, spelling := range featureSpellings(flag) {
|
||||
context.canonical[flagSpellingKey(spelling)] = spelling
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
canonicalKeys := sortedContextKeys(canonicalContexts)
|
||||
resolvedCanonical := make(map[string]resolvedFlagAliases, len(canonicalContexts))
|
||||
|
||||
72
invocation_feature.go
Normal file
72
invocation_feature.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package commandkit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.maximumdirect.net/commandkit/internal/commandmeta"
|
||||
)
|
||||
|
||||
// InvocationFeature is a captured, reusable invocation-wide capability.
|
||||
// Attach it to an installed command with WithInvocationFeature.
|
||||
type InvocationFeature struct{ record *invocationFeatureRecord }
|
||||
|
||||
// InvocationFeatureSpec declares invocation flags and a report producer.
|
||||
// NewInput creates fresh input for each invocation; nil uses the zero value.
|
||||
// Start receives the current invocation and may return a replacement context
|
||||
// and a function producing a report at invocation finalization. Start is required.
|
||||
type InvocationFeatureSpec[I any] struct {
|
||||
NewInput func() I
|
||||
Flags []Flag[I]
|
||||
Start func(Invocation, I) (context.Context, func() Report)
|
||||
}
|
||||
|
||||
type invocationFeaturePayload interface {
|
||||
bridgeFlags() []commandmeta.Flag
|
||||
}
|
||||
|
||||
type typedInvocationFeature[I any] struct{ spec InvocationFeatureSpec[I] }
|
||||
|
||||
func (f typedInvocationFeature[I]) bridgeFlags() []commandmeta.Flag {
|
||||
return (typedCommand[I]{spec: CommandSpec[I]{Flags: f.spec.Flags}}).bridgeFlags()
|
||||
}
|
||||
|
||||
type invocationFeatureRecord struct {
|
||||
payload invocationFeaturePayload
|
||||
issues []error
|
||||
}
|
||||
|
||||
// NewInvocationFeature captures flag declarations and callbacks without invoking
|
||||
// them. Construction errors are reported when an attached command is installed.
|
||||
func NewInvocationFeature[I any](spec InvocationFeatureSpec[I]) InvocationFeature {
|
||||
spec.Flags = append([]Flag[I](nil), spec.Flags...)
|
||||
record := &invocationFeatureRecord{payload: typedInvocationFeature[I]{spec: spec}}
|
||||
if err := validateBindings(spec.Flags, nil); err != nil {
|
||||
record.issues = append(record.issues, err)
|
||||
}
|
||||
for _, flag := range spec.Flags {
|
||||
if commandmeta.IsReportingFlag(flag.binding.meta.Name) {
|
||||
record.issues = append(record.issues, fmt.Errorf("feature flag name %q is reserved for reporting", flag.binding.meta.Name))
|
||||
}
|
||||
}
|
||||
if spec.Start == nil {
|
||||
record.issues = append(record.issues, fmt.Errorf("invocation feature requires Start"))
|
||||
}
|
||||
return InvocationFeature{record: record}
|
||||
}
|
||||
|
||||
// WithInvocationFeature returns a copy of command with feature attached. When
|
||||
// installed, the feature applies to the application, not only this command.
|
||||
// Reusing the same feature in one application installs it once. An absent
|
||||
// command contributes no feature, but attached errors are still reported.
|
||||
func WithInvocationFeature(command Command, feature InvocationFeature) Command {
|
||||
var record commandRecord
|
||||
if command.record == nil {
|
||||
record.invalid = true
|
||||
record.issues = append(record.issues, fmt.Errorf("invalid zero command declaration"))
|
||||
} else {
|
||||
record = *command.record
|
||||
}
|
||||
record.features = append(append([]InvocationFeature(nil), record.features...), feature)
|
||||
return Command{record: &record}
|
||||
}
|
||||
97
invocation_feature_test.go
Normal file
97
invocation_feature_test.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package commandkit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInvocationFeatureCaptureAndInstallation(t *testing.T) {
|
||||
type input struct{ enabled bool }
|
||||
flags := []Flag[input]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(i *input, v Supplied[bool]) { i.enabled = v.Value })}
|
||||
feature := NewInvocationFeature(InvocationFeatureSpec[input]{Flags: flags, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }})
|
||||
flags[0] = BoolFlag(FlagMeta{Name: "changed"}, false, func(*input, Supplied[bool]) {})
|
||||
original := Group("owner", "", Group("child", ""))
|
||||
attached := WithInvocationFeature(original, feature)
|
||||
first, err := New(Identity{Name: "test"}, attached, Group("other", ""), FlagAlias("--watch", "--observe"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := New(Identity{Name: "test"}, attached)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(first.features) != 1 || len(second.features) != 1 || first.features[0] != second.features[0] || first.featureFlags[0].Name != "observe" {
|
||||
t.Fatal("feature capture or reuse failed")
|
||||
}
|
||||
if len(original.record.features) != 0 {
|
||||
t.Fatal("attachment mutated original")
|
||||
}
|
||||
if _, ok := first.flagAliases[""].bySpelling[flagSpellingKey(capturedFlagSpelling{name: "watch"})]; !ok {
|
||||
t.Fatal("feature alias missing")
|
||||
}
|
||||
if err := first.Register(WithInvocationFeature(Group("reused", ""), feature)); err != nil || len(first.features) != 1 {
|
||||
t.Fatalf("deduplication: %v", err)
|
||||
}
|
||||
if err := first.Register(Group("collision", "", NewCommand(CommandSpec[struct{}]{Name: "nested", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe"}, false, func(*struct{}, Supplied[bool]) {})}}))); err == nil {
|
||||
t.Fatal("expected local collision")
|
||||
}
|
||||
if first.commands["collision"] != nil || len(first.features) != 1 {
|
||||
t.Fatal("failed registration mutated registry")
|
||||
}
|
||||
if err := second.Register(WithInvocationFeature(Group("another", ""), NewInvocationFeature(InvocationFeatureSpec[input]{Flags: flags, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }}))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := second.Register(WithInvocationFeature(Group("duplicate", ""), NewInvocationFeature(InvocationFeatureSpec[input]{Flags: []Flag[input]{BoolFlag(FlagMeta{Name: "observe"}, false, func(*input, Supplied[bool]) {})}, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }}))); err == nil {
|
||||
t.Fatal("expected feature collision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvocationFeatureInvalidAndAbsent(t *testing.T) {
|
||||
marker := errors.New("wiring")
|
||||
invalid := NewInvocationFeature(InvocationFeatureSpec[struct{}]{})
|
||||
for _, command := range []Command{WithInvocationFeature(NoCommand(), invalid), WithInvocationFeature(Group("x", ""), InvocationFeature{}), WithInvocationFeature(Command{}, NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})), WithError(WithInvocationFeature(NoCommand(), invalid), marker)} {
|
||||
_, err := New(Identity{Name: "test"}, command)
|
||||
if err == nil {
|
||||
t.Fatal("invalid feature accepted")
|
||||
}
|
||||
if len(command.record.issues) > 0 && errors.Is(command.record.issues[0], marker) && !errors.Is(err, marker) {
|
||||
t.Fatalf("lost attached error: %v", err)
|
||||
}
|
||||
}
|
||||
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
|
||||
app, err := New(Identity{Name: "test"}, WithInvocationFeature(NoCommand(), feature))
|
||||
if err != nil || len(app.features) != 0 {
|
||||
t.Fatalf("absent feature: %v", err)
|
||||
}
|
||||
bad := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "debug"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
|
||||
if _, err = New(Identity{Name: "test"}, WithInvocationFeature(Group("x", ""), bad)); err == nil || !strings.Contains(err.Error(), "reserved") {
|
||||
t.Fatalf("reporting collision: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvocationFeatureRegistrationOrderAndAliasCollision(t *testing.T) {
|
||||
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
|
||||
owner := WithInvocationFeature(Group("owner", ""), feature)
|
||||
collision := NewCommand(CommandSpec[struct{}]{Name: "local", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "other", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}})
|
||||
for _, pair := range [][2]Command{{owner, collision}, {collision, owner}} {
|
||||
app, err := New(Identity{Name: "test"}, pair[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := app.buildRoutingSnapshot()
|
||||
if err := app.Register(pair[1]); err == nil {
|
||||
t.Fatal("expected collision")
|
||||
}
|
||||
if app.commands[pair[1].record.name] != nil || len(app.features) != len(old.features) {
|
||||
t.Fatal("registration was not atomic")
|
||||
}
|
||||
}
|
||||
if _, err := New(Identity{Name: "test"}, owner, FlagAlias("--observe", "--verbose")); err == nil {
|
||||
t.Fatal("feature spelling accepted as alias source")
|
||||
}
|
||||
if _, err := New(Identity{Name: "test"}, owner, FlagAliasFor("owner", "--watch", "--observe")); err != nil {
|
||||
t.Fatalf("feature alias rejected: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,8 @@ func (a *App) buildRoutingSnapshot() *routingSnapshot {
|
||||
canonical: buildCanonicalTree(a.commands),
|
||||
flagAliases: a.flagAliases,
|
||||
discoveryFlags: a.discoveryFlags,
|
||||
features: a.features,
|
||||
featureFlags: a.featureFlags,
|
||||
}
|
||||
if node := a.commands["completion"]; node != nil {
|
||||
snapshot.completion = node.command.record.completion
|
||||
|
||||
77
registry.go
77
registry.go
@@ -28,6 +28,8 @@ type installationCandidate struct {
|
||||
aliases *internalalias.Resolver
|
||||
flagAliases map[string]resolvedFlagAliases
|
||||
discoveryFlags map[string]resolvedFlagAliases
|
||||
features []*invocationFeatureRecord
|
||||
featureFlags []commandmeta.Flag
|
||||
changed bool
|
||||
}
|
||||
|
||||
@@ -91,6 +93,8 @@ func (a *App) installBatch(declarations ...Declaration) error {
|
||||
a.aliases = candidate.aliases
|
||||
a.flagAliases = candidate.flagAliases
|
||||
a.discoveryFlags = candidate.discoveryFlags
|
||||
a.features = candidate.features
|
||||
a.featureFlags = candidate.featureFlags
|
||||
a.snapshot = nil
|
||||
return nil
|
||||
}
|
||||
@@ -154,11 +158,18 @@ func (a *App) buildInstallationCandidate(commands []Command, addedRules []Routin
|
||||
}
|
||||
candidate.aliases = resolver
|
||||
|
||||
candidate.features, candidate.featureFlags, err = collectInvocationFeatures(candidate.commands)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tree := buildCanonicalTree(candidate.commands)
|
||||
if err := validateInvocationFlagCollisions(tree, candidate.featureFlags); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateCommandAliases(rules, resolver, tree); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flagAliases, discoveryFlags, err := compileFlagAliases(rules, tree, resolver)
|
||||
flagAliases, discoveryFlags, err := compileFlagAliases(rules, tree, resolver, candidate.featureFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -365,3 +376,67 @@ func acceptsOperandPrefix(command Command, count int) bool {
|
||||
}
|
||||
return maximum < 0 || count <= maximum
|
||||
}
|
||||
|
||||
// collectInvocationFeatures walks declarations in stable root, child and attachment order.
|
||||
func collectInvocationFeatures(commands map[string]*commandNode) ([]*invocationFeatureRecord, []commandmeta.Flag, error) {
|
||||
names := make([]string, 0, len(commands))
|
||||
for name := range commands {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
seen := make(map[*invocationFeatureRecord]bool)
|
||||
var features []*invocationFeatureRecord
|
||||
var flags []commandmeta.Flag
|
||||
var visit func(Command)
|
||||
visit = func(command Command) {
|
||||
if command.record == nil || command.record.absent {
|
||||
return
|
||||
}
|
||||
for _, feature := range command.record.features {
|
||||
if !seen[feature.record] {
|
||||
seen[feature.record] = true
|
||||
features = append(features, feature.record)
|
||||
flags = append(flags, feature.record.payload.bridgeFlags()...)
|
||||
}
|
||||
}
|
||||
for _, child := range command.record.children {
|
||||
visit(child)
|
||||
}
|
||||
}
|
||||
for _, name := range names {
|
||||
visit(commands[name].command)
|
||||
}
|
||||
seenFlags := helpFlagSpellings()
|
||||
for _, flag := range flags {
|
||||
for _, spelling := range featureSpellings(flag) {
|
||||
key := flagSpellingKey(spelling)
|
||||
if _, exists := seenFlags[key]; exists {
|
||||
return nil, nil, fmt.Errorf("invocation feature flag %s conflicts with another flag", spelling.token())
|
||||
}
|
||||
seenFlags[key] = spelling
|
||||
}
|
||||
}
|
||||
return features, flags, nil
|
||||
}
|
||||
|
||||
func featureSpellings(flag commandmeta.Flag) []capturedFlagSpelling {
|
||||
spellings := []capturedFlagSpelling{{name: flag.Name}}
|
||||
if flag.Short != "" {
|
||||
spellings = append(spellings, capturedFlagSpelling{name: flag.Short, short: true})
|
||||
}
|
||||
return spellings
|
||||
}
|
||||
|
||||
func validateInvocationFlagCollisions(roots map[string]*canonicalNode, flags []commandmeta.Flag) error {
|
||||
for _, node := range indexCanonicalNodes(roots) {
|
||||
local := canonicalFlagSpellings(node.command)
|
||||
for _, flag := range flags {
|
||||
for _, spelling := range featureSpellings(flag) {
|
||||
if _, exists := local[flagSpellingKey(spelling)]; exists {
|
||||
return fmt.Errorf("invocation feature flag %s conflicts with command %q", spelling.token(), node.path.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user