Skip to content

Commit a77b350

Browse files
committed
Generate subcommand error during help
1 parent 6a6af78 commit a77b350

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,22 @@ Serpent is designed for high-configurability. To us, that means providing
6666
many ways to configure the same value (env, YAML, flags, etc.) and keeping
6767
the code clean and testable as you scale the number of options.
6868

69+
Serpent's [Option](https://pkg.go.dev/github.com/coder/serpent#Option) type looks like:
70+
71+
```go
72+
type Option {
73+
Name string
74+
Flag string
75+
Env string
76+
Default string
77+
Value pflag.Value
78+
// ...
79+
}
80+
```
81+
82+
And is used by each [Cmd](https://pkg.go.dev/github.com/coder/serpent#Cmd) when
83+
passed as an array to the `Options` field.
84+
6985
## More coming...
7086
This README is a stub for now. We'll better explain the design and usage
7187
of `serpent` in the future.

cmd_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,17 @@ func TestCommand(t *testing.T) {
157157
require.Error(t, err)
158158
})
159159

160+
t.Run("NoSubcommand", func(t *testing.T) {
161+
t.Parallel()
162+
i := cmd().Invoke(
163+
"na",
164+
)
165+
io := fakeIO(i)
166+
err := i.Run()
167+
require.Error(t, err)
168+
require.Contains(t, io.Stderr.String(), "unknown subcommand")
169+
})
170+
160171
t.Run("UnknownFlags", func(t *testing.T) {
161172
t.Parallel()
162173
i := cmd().Invoke(

help.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,12 @@ var usageWantsArgRe = regexp.MustCompile(`<.*>`)
324324
// output for a given command.
325325
func defaultHelpFn() HandlerFunc {
326326
return func(inv *Invocation) error {
327+
var unknownSubcommandErr error
328+
if len(inv.Args) > 0 {
329+
// Detected unknown subcommand.
330+
unknownSubcommandErr = fmt.Errorf("error: unknown subcommand %q", strings.Join(inv.Args, " "))
331+
_, _ = fmt.Fprintf(inv.Stderr, "%v\n\n", unknownSubcommandErr)
332+
}
327333
// We use stdout for help and not stderr since there's no straightforward
328334
// way to distinguish between a user error and a help request.
329335
//
@@ -347,6 +353,7 @@ func defaultHelpFn() HandlerFunc {
347353
if len(inv.Args) > 0 && !usageWantsArgRe.MatchString(inv.Command.Use) {
348354
_, _ = fmt.Fprintf(inv.Stderr, "---\nerror: unknown subcommand %q\n", inv.Args[0])
349355
}
350-
return nil
356+
// Return an error so that exit status is non-zero.
357+
return unknownSubcommandErr
351358
}
352359
}

0 commit comments

Comments
 (0)