Skip to content

Commit b301795

Browse files
committed
feat(cli): add cliarg package
This adds a new package called `cliarg` with tests which adds a helper function that extends cobra.Args to allow for custom error messages.
1 parent f4da5d4 commit b301795

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

cli/cliarg/cliarg.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Package cliarg extends cobra.Args to allow for custom error messages.
2+
//
3+
// Usage:
4+
//
5+
// cliarg.ExactNamedArgs("workspace", "This command requires a workspace name to be passed. Run this command with '--help' to see an example.")
6+
//
7+
// Will produce the following error message when calling
8+
//
9+
// Error: this command accepts 'workspace' as an argument, received no arguments. Pass in 'workspace' or call command with '--help' to see an example.")
10+
//
11+
package cliarg
12+
13+
import (
14+
"fmt"
15+
16+
"github.com/spf13/cobra"
17+
)
18+
19+
// Expects 1 arg based on namedArg, otherwise returns customErrorMessage
20+
func ExactNamedArg(namedArg string, customErrorMessage string) cobra.PositionalArgs {
21+
return func(cmd *cobra.Command, args []string) error {
22+
expectedNumOfArgs := 1
23+
if len(args) != expectedNumOfArgs {
24+
return fmt.Errorf("this command accepts <%s> as an argument, received no arguments. %s", namedArg, customErrorMessage)
25+
}
26+
return nil
27+
}
28+
}

cli/cliarg/cliflag_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package cliarg_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/require"
7+
8+
"github.com/coder/coder/cli/cliarg"
9+
"github.com/coder/coder/cli/clitest"
10+
)
11+
12+
func TestCliarg(t *testing.T) {
13+
t.Run("No errors", func(t *testing.T) {
14+
t.Parallel()
15+
namedArg := "workspace"
16+
customErrorMessage := "Please call with a workspace arg"
17+
fun := cliarg.ExactNamedArg(namedArg, customErrorMessage)
18+
args := []string{"myWorkspace"}
19+
cmd, _ := clitest.New(t, "delete", "myWorkspace")
20+
var want *string
21+
got := fun(cmd, args)
22+
require.Nil(t, want, got)
23+
})
24+
t.Run("Custom error message", func(t *testing.T) {
25+
t.Parallel()
26+
namedArg := "workspace"
27+
customErrorMessage := "Please call with a workspace arg"
28+
fun := cliarg.ExactNamedArg(namedArg, customErrorMessage)
29+
var args []string
30+
cmd, _ := clitest.New(t, "delete")
31+
got := fun(cmd, args)
32+
require.ErrorContains(t, got, customErrorMessage)
33+
})
34+
}

0 commit comments

Comments
 (0)