fix(cli): show error/hide help for unsupported subcommands (#10760) (#12624)

Fixes #10760 

The coder CLI quietly accepts any subcommand arguments and silently swallows them.

Currently:
```sh
❯ coder | head -n5
coder v2.3.3+e491217

USAGE:
  coder [global-flags] <subcommand>
```

```sh
❯ coder idontexist | head -n5
coder v2.3.3+e491217

USAGE:
  coder [global-flags] <subcommand>
```

Now help output will not be show when there is an unknown subcommand error. Instead users will be given the command for the help output.

```sh
❯ coder idontexist
Encountered an error running "coder", see "coder --help" for more information 
error: unrecognized subcommand "idontexist"
```
```sh
❯ coder iexistbut idontexist
Encountered an error running "coder iexistbut", see "coder iexistbut --help" for more information 
error: unrecognized subcommand "idontexist"
```

Also this stuff: `Encountered an error running "coder iexistbut"... ` gets written to `os.Stdout` in `prettyErrorFormatter{w: os.Stderr, verbose: r.verbose}`, not sure how to test that output.
This commit is contained in:
elasticspoon
2024-03-17 22:17:43 -05:00
committed by GitHub
parent c189cc93e4
commit 5011edc292
6 changed files with 69 additions and 16 deletions
+43
View File
@@ -60,6 +60,49 @@ func TestCommandHelp(t *testing.T) {
func TestRoot(t *testing.T) {
t.Parallel()
t.Run("MissingRootCommand", func(t *testing.T) {
t.Parallel()
out := new(bytes.Buffer)
inv, _ := clitest.New(t, "idontexist")
inv.Stdout = out
err := inv.Run()
assert.ErrorContains(t, err,
`unrecognized subcommand "idontexist"`)
require.Empty(t, out.String())
})
t.Run("MissingSubcommand", func(t *testing.T) {
t.Parallel()
out := new(bytes.Buffer)
inv, _ := clitest.New(t, "server", "idontexist")
inv.Stdout = out
err := inv.Run()
// subcommand error only when command has subcommands
assert.ErrorContains(t, err,
`unrecognized subcommand "idontexist"`)
require.Empty(t, out.String())
})
t.Run("BadSubcommandArgs", func(t *testing.T) {
t.Parallel()
out := new(bytes.Buffer)
inv, _ := clitest.New(t, "list", "idontexist")
inv.Stdout = out
err := inv.Run()
assert.ErrorContains(t, err,
`wanted no args but got 1 [idontexist]`)
require.Empty(t, out.String())
})
t.Run("Version", func(t *testing.T) {
t.Parallel()