Only display usage string on flag errors (#147)

This commit is contained in:
Pieter Noordhuis 2022-12-21 11:38:30 +01:00 committed by GitHub
parent f70a5814f6
commit a354fa1f77
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package root
import ( import (
"context" "context"
"fmt"
"log" "log"
"os" "os"
"strings" "strings"
@ -14,12 +15,20 @@ var RootCmd = &cobra.Command{
Use: "bricks", Use: "bricks",
Short: "Databricks project lifecycle management", Short: "Databricks project lifecycle management",
Long: `Where's "data"? Secured by the unity catalog. Projects build lifecycle is secured by bricks`, Long: `Where's "data"? Secured by the unity catalog. Projects build lifecycle is secured by bricks`,
// Cobra prints the usage string to stderr if a command returns an error.
// This usage string should only be displayed if an invalid combination of flags
// is specified and not when runtime errors occur (e.g. resource not found).
// The usage string is include in [flagErrorFunc] for flag errors only.
SilenceUsage: true,
PersistentPreRun: func(cmd *cobra.Command, args []string) { PersistentPreRun: func(cmd *cobra.Command, args []string) {
if Verbose { if Verbose {
logLevel = append(logLevel, "[DEBUG]") logLevel = append(logLevel, "[DEBUG]")
} }
log.SetOutput(&logLevel) log.SetOutput(&logLevel)
}, },
// Uncomment the following line if your bare application // Uncomment the following line if your bare application
// has an action associated with it: // has an action associated with it:
} }
@ -42,6 +51,11 @@ func (lw *levelWriter) Write(p []byte) (n int, err error) {
return return
} }
// Wrap flag errors to include the usage string.
func flagErrorFunc(c *cobra.Command, err error) error {
return fmt.Errorf("%w\n\n%s", err, c.UsageString())
}
// Execute adds all child commands to the root command and sets flags appropriately. // Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd. // This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() { func Execute() {
@ -54,6 +68,7 @@ func Execute() {
} }
func init() { func init() {
RootCmd.SetFlagErrorFunc(flagErrorFunc)
// flags available for every child command // flags available for every child command
RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "print debug logs") RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "print debug logs")
} }