package commandkit import ( "bytes" "context" "errors" "io" "reflect" "strings" "testing" "text/template" internalcobra "go.maximumdirect.net/commandkit/internal/cobra" commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta" ) 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) } } 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) { return inv.Context, 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 != 1 { t.Fatal("help or invalid input constructed feature input") } 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) } } } func TestInvocationFeatureLifecycleAndFinalization(t *testing.T) { type key struct{} type input struct{ on bool } var events []string feature := NewInvocationFeature(InvocationFeatureSpec[input]{ NewInput: func() input { events = append(events, "feature input"); return input{} }, Flags: []Flag[input]{BoolFlag(FlagMeta{Name: "observe"}, false, func(i *input, v Supplied[bool]) { i.on = v.Value })}, Start: func(inv Invocation, i input) (context.Context, func() Report) { events = append(events, "start") if !i.on { return nil, nil } return context.WithValue(inv.Context, key{}, "value"), func() Report { events = append(events, "report"); return Report{Value: "summary"} } }, }) var reject bool cmd := NewCommand(CommandSpec[struct{}]{Name: "run", NewInput: func() struct{} { events = append(events, "input"); return struct{}{} }, CheckInput: func(struct{}) error { events = append(events, "check") if reject { return errors.New("rejected") } return nil }, Run: func(inv Invocation, _ struct{}) Outcome { events = append(events, "run") if inv.Context.Value(key{}) != "value" { t.Error("missing context") } _ = inv.Reporter().AtEnd().Warn("deferred") return Failure("failed") }}) app, err := New(Identity{Name: "test"}, WithInvocationFeature(cmd, feature), Completion("test")) if err != nil { t.Fatal(err) } var output, diagnostics bytes.Buffer outcome := app.Execute(context.Background(), []string{"run", "--observe", "--verbose", "--format=json"}, Streams{Out: &output, Err: &diagnostics}) if outcome.Kind != OutcomeOperational || !reflect.DeepEqual(events, []string{"input", "check", "feature input", "start", "run", "report"}) { t.Fatalf("events=%v outcome=%#v", events, outcome) } if !strings.Contains(diagnostics.String(), "WARN: deferred\nsummary\nERROR: failed") { t.Fatalf("ordering: %q", diagnostics.String()) } events = nil reject = true diagnostics.Reset() app.Execute(context.Background(), []string{"run", "--observe"}, Streams{Err: &diagnostics}) if !reflect.DeepEqual(events, []string{"input", "check"}) || strings.Contains(diagnostics.String(), "summary") { t.Fatalf("check rejection: %v %q", events, diagnostics.String()) } reject = false for _, args := range [][]string{{"run", "--help"}, {"version", "--observe"}, {"completion", "bash", "--observe"}, {"missing", "--observe"}, {"run", "--observe=invalid"}} { events = nil app.Execute(context.Background(), args, Streams{}) if len(events) != 0 { t.Fatalf("builtin or error %v: %v", args, events) } } events = nil diagnostics.Reset() app.Execute(context.Background(), []string{"run", "--observe", "--quiet"}, Streams{Err: &diagnostics}) if !strings.Contains(diagnostics.String(), "ERROR: failed") || strings.Contains(diagnostics.String(), "summary") || events[len(events)-1] != "report" { t.Fatalf("quiet: %v %q", events, diagnostics.String()) } } func TestInvocationFeatureDiagnosticFailures(t *testing.T) { cause := errors.New("domain cause") failTemplate := template.Must(template.New("bad").Parse("{{call .}}")) for _, tc := range []struct { name string report Report writer io.Writer quiet bool render, write bool }{ {name: "render", report: Report{Value: func() (string, error) { return "", errors.New("bad template") }, TextTemplate: failTemplate}, render: true}, {name: "quiet render", report: Report{Value: func() (string, error) { return "", errors.New("bad template") }, TextTemplate: failTemplate}, quiet: true, render: true}, {name: "short write", report: Report{Value: "summary"}, writer: &reporterTestWriter{n: 1}, write: true}, } { t.Run(tc.name, func(t *testing.T) { feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return nil, func() Report { return tc.report } }}) cmd := WithInvocationFeature(NewCommand(CommandSpec[struct{}]{Name: "run", Run: func(Invocation, struct{}) Outcome { return Domain("domain", 7).WithCause(cause) }}), feature) app, err := New(Identity{Name: "test"}, cmd) if err != nil { t.Fatal(err) } args := []string{"run"} if tc.quiet { args = append(args, "--quiet") } out := app.Execute(context.Background(), args, Streams{Err: tc.writer}) if out.Kind != OutcomeDomain || out.Status != 7 || !errors.Is(out.Cause, cause) || (out.Presentation.Diagnostics.RenderError != nil) != tc.render || (out.Presentation.Diagnostics.WriteError != nil) != tc.write { t.Fatalf("outcome=%#v", out) } }) } } func TestRequiredInvocationFlagDoesNotBlockBuiltinsOrGroupHelp(t *testing.T) { feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe", Required: true}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { t.Fatal("feature started") return nil, nil }}) app, err := New(Identity{Name: "test"}, WithInvocationFeature(Group("group", ""), feature)) if err != nil { t.Fatal(err) } for _, args := range [][]string{{"version"}, {"help"}, {"group"}, {"group", "--help"}} { if out := app.Execute(context.Background(), args, Streams{}); out.Status != 0 { t.Fatalf("%v: %#v", args, out) } } } func TestInvocationFeaturesChainContextsAndReports(t *testing.T) { type chainKey struct{} var order []string first := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { order = append(order, "first start") return context.WithValue(inv.Context, chainKey{}, "first"), func() Report { order = append(order, "first report"); return Report{Value: "first"} } }}) second := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { if inv.Context.Value(chainKey{}) != "first" { t.Error("feature context not propagated") } order = append(order, "second start") return nil, func() Report { order = append(order, "second report"); return Report{Value: "second"} } }}) cmd := NewCommand(CommandSpec[struct{}]{Name: "run", Run: func(inv Invocation, _ struct{}) Outcome { if inv.Context.Value(chainKey{}) != "first" { t.Error("nil context did not preserve previous context") } order = append(order, "run") return Success() }}) cmd = WithInvocationFeature(WithInvocationFeature(cmd, first), second) app, err := New(Identity{Name: "test"}, cmd) if err != nil { t.Fatal(err) } var diag bytes.Buffer out := app.Execute(context.Background(), []string{"run"}, Streams{Err: &diag}) if out.Status != 0 || !reflect.DeepEqual(order, []string{"first start", "second start", "run", "first report", "second report"}) || diag.String() != "first\nsecond\n" { t.Fatalf("%#v %v %q", out, order, diag.String()) } }