Skip to content

fix: show --help message for CLI errors, add tests for delete #1403

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 19, 2022
Prev Previous commit
Next Next commit
refactor(cli): handle err with FormatCobraError
This adds a new helper function called `FormatCobraError` to `root.go`
so that we can colorize and add "--help" message to cobra command errors
like calling `delete`.
  • Loading branch information
jsjoeio committed May 19, 2022
commit c28e93a7890da08ef8393a6d66eb60de2fe6e131
7 changes: 7 additions & 0 deletions cli/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"fmt"
"net/url"
"os"
"time"
Expand Down Expand Up @@ -259,3 +260,9 @@ func versionTemplate() string {
template += "\r\n"
return template
}

// FormatCobraError colorizes and adds "--help" docs to cobra commands.
func FormatCobraError(err error, cmd *cobra.Command) string {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extracted into function to make it easier to test

helpErrMsg := fmt.Sprintf("Run '%s %s --help' for usage.", cmd.Root().Name(), cmd.Name())
return cliui.Styles.Error.Render(err.Error() + "\n" + helpErrMsg)
}
4 changes: 2 additions & 2 deletions cmd/coder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ func main() {
if errors.Is(err, cliui.Canceled) {
os.Exit(1)
}
helpErrMsg := fmt.Sprintf("Run '%s %s --help' for usage.", cmd.Root().Name(), cmd.Name())
_, _ = fmt.Fprintln(os.Stderr, cliui.Styles.Error.Render(err.Error()+"/n"+helpErrMsg))
cobraErr := cli.FormatCobraError(err, cmd)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: this behavior mimics what SilenceErrors: true does, which prints the --help message below any errors. See this comment from @mafredri for more context: #1403 (comment)

_, _ = fmt.Fprintln(os.Stderr, cobraErr)
os.Exit(1)
}
}
Expand Down