diff --git a/app.go b/app.go index bf2b764..e28d9b5 100644 --- a/app.go +++ b/app.go @@ -24,6 +24,7 @@ type App struct { type routingSnapshot struct { metadata *commandmeta.Command runners map[commandmeta.Key]commandPayload + builtins map[commandmeta.Key]bool aliases *alias.Resolver canonical map[string]*canonicalNode commandAliases []commandmeta.CommandAlias diff --git a/builtins.go b/builtins.go index 25c3c39..d594ab2 100644 --- a/builtins.go +++ b/builtins.go @@ -58,6 +58,8 @@ func (a *App) builtinCommands() []Declaration { return renderVersionOutcome(identity, invocation.Reporter()) }, }) + help.record.builtin = true + version.record.builtin = true return []Declaration{help, version} } diff --git a/command.go b/command.go index 5dcca77..a3de019 100644 --- a/command.go +++ b/command.go @@ -76,6 +76,7 @@ type commandRecord struct { issues []error rootOnly bool completion bool + builtin bool absent bool invalid bool } @@ -260,6 +261,7 @@ func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrenc return classifyInputError(err) } } + current.startFeatures() if c.privateRun != nil { return c.privateRun(current.commandContext(), input) } diff --git a/completion.go b/completion.go index 73b15ce..9ce47b3 100644 --- a/completion.go +++ b/completion.go @@ -28,8 +28,12 @@ func Completion(executable string) Command { }, })) } + for _, child := range children { + child.record.builtin = true + } command := RootGroup("completion", "Generate shell completion scripts.", children...) command.record.completion = true + command.record.builtin = true if !validCompletionExecutable(executable) { return WithError(command, fmt.Errorf("unsupported completion executable basename %q", executable)) } diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 146a0a1..3be568c 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -196,6 +196,10 @@ boundary already owns the behavior rather than duplicating every grammar case. ## Stage 3: Run features at the input boundary and finalize diagnostic reports +**Complete.** Core lifecycle tests verify input and context ordering, builtin and +preflight exclusions, deferred/summary/terminal ordering, quiet rendering, and +diagnostic failures with preserved domain outcomes. Go 1.27.4 core tests pass. + 1. Refactor the prepared command closure so feature startup occurs after input construction and successful `CommandSpec.CheckInput`, immediately before `Run`. Preserve existing input/classification behavior. Integration validation inside diff --git a/execute.go b/execute.go index 2ef5328..fa3e2ca 100644 --- a/execute.go +++ b/execute.go @@ -72,6 +72,7 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco outcome = classifyInputError(err) } else { handlerRan = true + current.featureEnabled = !routedSnapshot.builtins[parsed.Key] outcome = run(current) } } @@ -100,14 +101,31 @@ func (current *execution) prepareFeatures(parsed commandmeta.Result, required bo } type execution struct { - app *App - ctx context.Context - reporter *Reporter - featureStarts []func(Invocation) (context.Context, func() Report) - debugEvents []string - snapshot *routingSnapshot - session *internalcobra.Session - route routeResult + app *App + ctx context.Context + reporter *Reporter + featureStarts []func(Invocation) (context.Context, func() Report) + featureEnabled bool + featureReports []func() Report + debugEvents []string + snapshot *routingSnapshot + session *internalcobra.Session + route routeResult +} + +func (current *execution) startFeatures() { + if !current.featureEnabled { + return + } + for _, start := range current.featureStarts { + ctx, report := start(current.invocation()) + if ctx != nil { + current.ctx = ctx + } + if report != nil { + current.featureReports = append(current.featureReports, report) + } + } } type commandExecution struct { @@ -363,7 +381,7 @@ func (current *execution) finalize(outcome Outcome, path []string, handlerRan bo _ = reporter.Debug(fmt.Sprintf("handler completed for %q with %s outcome and status %d", path, kind, outcome.Status)) } } - return current.reporter.finalize(outcome, completion) + return current.reporter.finalize(outcome, completion, current.featureReports...) } func (current *execution) usageText(path []string) string { diff --git a/invocation_feature_test.go b/invocation_feature_test.go index 4ee1c84..5971dd9 100644 --- a/invocation_feature_test.go +++ b/invocation_feature_test.go @@ -1,10 +1,14 @@ 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" @@ -106,8 +110,7 @@ func TestInvocationFeatureFlagsParseAndDiscover(t *testing.T) { 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 + return inv.Context, nil }, }) type localInput struct{ name string } @@ -126,8 +129,8 @@ func TestInvocationFeatureFlagsParseAndDiscover(t *testing.T) { 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") + if constructed != 1 { + t.Fatal("help or invalid input constructed feature input") } snapshot := app.routeSnapshot() for _, path := range [][]string{nil, {"run"}, {"short"}} { @@ -151,3 +154,103 @@ func TestInvocationFeatureFlagsParseAndDiscover(t *testing.T) { } } } + +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) + } + }) + } +} diff --git a/parser.go b/parser.go index 0195ede..09e33f9 100644 --- a/parser.go +++ b/parser.go @@ -75,6 +75,7 @@ func (a *App) buildRoutingSnapshot() *routingSnapshot { snapshot := &routingSnapshot{ metadata: root, runners: make(map[commandmeta.Key]commandPayload), + builtins: make(map[commandmeta.Key]bool), aliases: a.aliases, canonical: buildCanonicalTree(a.commands), flagAliases: a.flagAliases, @@ -121,6 +122,7 @@ func bridgeCommand(node *canonicalNode, snapshot *routingSnapshot, next *command InvocationFlags: snapshot.featureFlags, } node.metadata = declaration + snapshot.builtins[declaration.Key] = record.builtin if record.payload != nil { snapshot.runners[declaration.Key] = record.payload declaration.Runnable = record.payload.hasRun() diff --git a/reporter.go b/reporter.go index 9c44107..216bfe6 100644 --- a/reporter.go +++ b/reporter.go @@ -203,6 +203,32 @@ func (r *Reporter) RenderOutput(write func(io.Writer) error) error { return finishRenderLocked(state, destinationOutput, renderErr, writer.writeError) } +// renderDiagnosticReport uses the same delivery bookkeeping as output reports, +// while always rendering text and treating quiet as delivery suppression only. +func (r *Reporter) renderDiagnosticReport(report Report) error { + if r == nil || r.state == nil { + return ErrReporterClosed + } + state := r.state + state.mu.Lock() + defer state.mu.Unlock() + if state.closed { + return ErrReporterClosed + } + destination := state.destination(destinationDiagnostics) + destination.submitted = true + if state.mode == ReportingModeQuiet { + destination.suppressed = true + return finishRenderLocked(state, destinationDiagnostics, RenderReport(io.Discard, report, FormatText), nil) + } + writer := &coordinatedWriter{state: state, destination: destinationDiagnostics} + err := RenderReport(writer, report, FormatText) + if err == nil && writer.writeError == nil { + destination.delivered = true + } + return finishRenderLocked(state, destinationDiagnostics, err, writer.writeError) +} + // Info submits an informational message to the diagnostic destination. Its // visibility follows the selected reporting mode. func (r *Reporter) Info(message string, details ...Detail) error { @@ -287,7 +313,7 @@ func (r DeferredReporter) enqueue(category messageCategory, message string, deta return nil } -func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter)) Outcome { +func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter), producers ...func() Report) Outcome { if r == nil || r.state == nil { return normalizeOutcome(outcome) } @@ -314,6 +340,12 @@ func (r *Reporter) finalize(outcome Outcome, completion func(*Reporter)) Outcome completion(r) } + for _, produce := range producers { + if produce != nil { + _ = r.renderDiagnosticReport(produce()) + } + } + state.mu.Lock() if presentationFailedLocked(state) { if outcome.Status == 0 && !hasExplanation(outcome.Explanation) {