Skip to content

Commit

Permalink
feat: Display CLI usage on user error (#819)
Browse files Browse the repository at this point in the history
  • Loading branch information
orpheuslummis committed Sep 20, 2022
1 parent 1363cce commit c967b9b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
5 changes: 1 addition & 4 deletions cli/blocks_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ var getCmd = &cobra.Command{
Short: "Get a block by its CID from the blockstore.",
RunE: func(cmd *cobra.Command, args []string) (err error) {
if len(args) != 1 {
if err = cmd.Usage(); err != nil {
return err
}
return errors.New("get requires a CID argument")
return errors.New("missing argument: CID")
}
cid := args[0]

Expand Down
21 changes: 20 additions & 1 deletion cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ import (

const badgerDatastoreName = "badger"

// List of cobra errors indicating an error occurred in the way the command was invoked.
// They are subject to change with new versions of cobra.
var usageErrors = []string{
"flag needs an argument",
"invalid syntax",
"unknown flag",
"unknown shorthand flag",
"missing argument", // custom to defradb
}

var log = logging.MustNewLogger("defra.cli")

var cfg = config.DefaultConfig()
Expand All @@ -45,7 +55,16 @@ func Execute() {
rootCmd.SetOut(os.Stdout)
err := rootCmd.ExecuteContext(ctx)
if err != nil {
log.FeedbackError(ctx, fmt.Sprintf("%s", err))
for _, cobraError := range usageErrors {
if strings.HasPrefix(err.Error(), cobraError) {
log.FeedbackErrorE(ctx, "Usage error", err)
if usageErr := rootCmd.Usage(); usageErr != nil {
log.FeedbackFatalE(ctx, "error displaying usage help", usageErr)
}
os.Exit(1)
}
}
log.FeedbackFatalE(ctx, "Execution error", err)
}
}

Expand Down

0 comments on commit c967b9b

Please sign in to comment.