Honor help-only input checks before starting features
This commit is contained in:
13
command.go
13
command.go
@@ -17,6 +17,10 @@ import (
|
||||
// before changing an App registry.
|
||||
type Command struct{ record *commandRecord }
|
||||
|
||||
// ErrHelpRequested may be returned by CommandSpec.CheckInput to display command
|
||||
// help without starting invocation features or enforcing their required flags.
|
||||
var ErrHelpRequested = errors.New("command help requested")
|
||||
|
||||
// Declaration is a captured canonical command or application routing rule
|
||||
// accepted by New and App.Register. Use []Declaration when collecting both
|
||||
// kinds. Group and RootGroup children remain Commands; install routing rules
|
||||
@@ -189,7 +193,8 @@ type CommandSpec[I any] struct {
|
||||
Flags []Flag[I]
|
||||
// Arguments declares the command's positional inputs.
|
||||
Arguments []Argument[I]
|
||||
// CheckInput validates declared combinations of parsed inputs.
|
||||
// CheckInput validates declared combinations of parsed inputs. Returning
|
||||
// ErrHelpRequested displays help without running the command or its features.
|
||||
CheckInput func(I) error
|
||||
// Run handles an invocation. It may be nil for a command used as a group.
|
||||
Run func(Invocation, I) Outcome
|
||||
@@ -258,9 +263,15 @@ func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrenc
|
||||
input := prepared.build()
|
||||
if c.spec.CheckInput != nil {
|
||||
if err := c.spec.CheckInput(input); err != nil {
|
||||
if errors.Is(err, ErrHelpRequested) {
|
||||
return current.renderHelp(current.route.canonicalPath)
|
||||
}
|
||||
return classifyInputError(err)
|
||||
}
|
||||
}
|
||||
if current.featureEnabled && current.featureRequiredError != nil {
|
||||
return classifyInputError(current.featureRequiredError)
|
||||
}
|
||||
current.startFeatures()
|
||||
if c.privateRun != nil {
|
||||
return c.privateRun(current.commandContext(), input)
|
||||
|
||||
@@ -401,7 +401,11 @@ An empty suite adds nothing. The flag defaults to false; explicit false and
|
||||
repeated selections use the ordinary Boolean rules. Applications pass
|
||||
`Invocation.Context` into PromptKit and wait for their own work before returning.
|
||||
The observer starts after command input construction and successful `CheckInput`,
|
||||
before `Run`; validation or acquisition inside `Run` is included. Help, version,
|
||||
before `Run`; validation or acquisition inside `Run` is included.
|
||||
`CommandSpec.CheckInput` may return `commandkit.ErrHelpRequested` for a
|
||||
help-only preflight result; core renders help without starting features or
|
||||
requiring execution-only invocation flags. ckconfig uses this for bare
|
||||
`config explain`. Help, version,
|
||||
completion, parse errors, and rejected command inputs do not start observation.
|
||||
|
||||
The requested summary is text on diagnostics after deferred messages and before
|
||||
|
||||
@@ -81,7 +81,12 @@ upstream-domain test suite.
|
||||
|
||||
## R2: Honor ckconfig's help-only fallback before starting invocation features
|
||||
|
||||
**Priority:** P2. **Status:** open. **Plan coverage:** Stages 2–4 and 7–8.
|
||||
**Priority:** P2. **Status:** complete. **Plan coverage:** Stages 2–4 and 7–8.
|
||||
|
||||
Added the CheckInput help signal and deferred feature requiredness until real
|
||||
execution. Regression checks cover implicit/explicit/aliased help, malformed
|
||||
values, real operations, and normal ckprompt installation. All three workspace
|
||||
suites passed on Go 1.27.4.
|
||||
|
||||
**Relevant code and contracts:**
|
||||
|
||||
|
||||
@@ -93,10 +93,13 @@ func (current *execution) prepareFeatures(parsed commandmeta.Result, required bo
|
||||
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)
|
||||
start, err := feature.payload.prepare(parsed.InvocationFlagValues[offset:offset+count], parsed.InvocationFlagSpellings[offset:offset+count], parsed.FlagOccurrences, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if required && current.featureRequiredError == nil {
|
||||
current.featureRequiredError = feature.payload.requiredError(parsed.InvocationFlagValues[offset : offset+count])
|
||||
}
|
||||
current.featureStarts = append(current.featureStarts, start)
|
||||
offset += count
|
||||
}
|
||||
@@ -108,6 +111,7 @@ type execution struct {
|
||||
ctx context.Context
|
||||
reporter *Reporter
|
||||
featureStarts []func(Invocation) (context.Context, func() Report)
|
||||
featureRequiredError error
|
||||
featureEnabled bool
|
||||
featureReports []func() Report
|
||||
debugEvents []string
|
||||
|
||||
52
integrations/ckconfig/help_feature_test.go
Normal file
52
integrations/ckconfig/help_feature_test.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package ckconfig_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
ck "go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExplainHelpExemptsInvocationFeatures(t *testing.T) {
|
||||
starts, inputs, loads := 0, 0, 0
|
||||
feature := ck.NewInvocationFeature(ck.InvocationFeatureSpec[struct{}]{
|
||||
NewInput: func() struct{} { inputs++; return struct{}{} },
|
||||
Flags: []ck.Flag[struct{}]{ck.BoolFlag(ck.FlagMeta{Name: "observe", Required: true}, false, func(*struct{}, ck.Supplied[bool]) {})},
|
||||
Start: func(ck.Invocation, struct{}) (context.Context, func() ck.Report) {
|
||||
starts++
|
||||
return nil, func() ck.Report { return ck.Report{Value: "summary"} }
|
||||
},
|
||||
})
|
||||
config := ckconfig.AppCommand(func(context.Context, ckconfig.Selection) (*configkit.Result[struct{}], error) {
|
||||
loads++
|
||||
return nil, errors.New("load failed")
|
||||
})
|
||||
app, err := ck.New(ck.Identity{Name: "test"}, config, ck.WithInvocationFeature(ck.Group("feature", ""), feature), ck.Alias("why", "config explain"), ck.NewCommand(ck.CommandSpec[struct{}]{Name: "run", Run: func(ck.Invocation, struct{}) ck.Outcome { return ck.Success() }}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{{"config", "explain"}, {"config", "explain", "--help"}, {"why", "--observe"}} {
|
||||
var out, diag bytes.Buffer
|
||||
result := app.Execute(context.Background(), args, ck.Streams{Out: &out, Err: &diag})
|
||||
if result.Status != 0 || !strings.Contains(out.String(), "Usage:") || diag.Len() != 0 || starts != 0 || inputs != 0 || loads != 0 {
|
||||
t.Fatalf("%v: %#v %q %q starts=%d inputs=%d loads=%d", args, result, out.String(), diag.String(), starts, inputs, loads)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]string{{"config", "explain", "--path=/"}, {"run"}, {"config", "explain", "--observe=bad"}} {
|
||||
if r := app.Execute(context.Background(), args, ck.Streams{}); r.Kind != ck.OutcomeUsage {
|
||||
t.Fatalf("%v: %#v", args, r)
|
||||
}
|
||||
}
|
||||
var diag bytes.Buffer
|
||||
if r := app.Execute(context.Background(), []string{"run", "--observe"}, ck.Streams{Err: &diag}); r.Status != 0 || starts != 1 || !strings.Contains(diag.String(), "summary") {
|
||||
t.Fatalf("%#v %q", r, diag.String())
|
||||
}
|
||||
app.Execute(context.Background(), []string{"config", "explain", "--path=/", "--observe"}, ck.Streams{})
|
||||
if starts != 2 || loads != 1 {
|
||||
t.Fatalf("starts=%d loads=%d", starts, loads)
|
||||
}
|
||||
}
|
||||
@@ -150,7 +150,13 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio
|
||||
if input == nil {
|
||||
return fmt.Errorf("configuration input must not be nil")
|
||||
}
|
||||
return prepareConfigOperation(prepared, operation, input)
|
||||
if err := prepareConfigOperation(prepared, operation, input); err != nil {
|
||||
return err
|
||||
}
|
||||
if input.plan.help {
|
||||
return commandkit.ErrHelpRequested
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Run: func(invocation commandkit.Invocation, input *configCommandInput[I, S]) commandkit.Outcome {
|
||||
return runConfigOperation(invocation, operation, input)
|
||||
|
||||
@@ -1024,3 +1024,17 @@ func TestNarrowSuiteReportsReturnedCancellation(t *testing.T) {
|
||||
t.Fatalf("%#v %q", out, diag.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplainHelpDoesNotReportUsage(t *testing.T) {
|
||||
app, err := newApp()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{{"config", "explain", "--show-tokens"}, {"config", "explain", "--help", "--show-tokens"}} {
|
||||
var out, diag bytes.Buffer
|
||||
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag})
|
||||
if result.Status != 0 || !strings.Contains(out.String(), "Usage:") || diag.Len() != 0 {
|
||||
t.Fatalf("%v: %#v %q %q", args, result, out.String(), diag.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ type InvocationFeatureSpec[I any] struct {
|
||||
|
||||
type invocationFeaturePayload interface {
|
||||
bridgeFlags() []commandmeta.Flag
|
||||
requiredError([][]string) error
|
||||
prepare([][]string, [][]string, []commandmeta.FlagOccurrence, bool) (func(Invocation) (context.Context, func() Report), error)
|
||||
}
|
||||
|
||||
@@ -39,6 +40,15 @@ func (f typedInvocationFeature[I]) bridgeFlags() []commandmeta.Flag {
|
||||
return (typedCommand[I]{spec: CommandSpec[I]{Flags: f.spec.Flags}}).bridgeFlags()
|
||||
}
|
||||
|
||||
func (f typedInvocationFeature[I]) requiredError(values [][]string) error {
|
||||
for i, flag := range f.spec.Flags {
|
||||
if flag.binding.meta.Required && !flag.binding.deferredRequired && len(values[i]) == 0 {
|
||||
return fmt.Errorf("required flag --%s was not supplied", flag.binding.meta.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user