Skip to content

Commit

Permalink
cmd/root: Use string template instead of function for usage
Browse files Browse the repository at this point in the history
In version 1.1.2 of Cobra has been included a change[0] that changes the
behaviour of how custom usage functions are printed. The change prepends
"Error: " to the text. This is not desired since the usage text is not
an error text.

Example of the wrong behaviour:

$ toolbox --foo
Error: unknown flag: --foo
Error: Run 'toolbox --help' for usage.

Desired behaviour:

$ toolbox --foo
Error: unknown flag: --foo
Run 'toolbox --help' for usage.

A workaround is to define a template string for the usage instead. The
template uses the templating language of Go[1]. See the default template
string in version 1.2.1[2].

Because the template is set only once, the executableBase needs to be
set before the template is applied. That required the move of
setUpGlobals() into init() of the cmd package. This is a better place
for the function call as init() is called earlier than Execute()[3].

Upstream issue: spf13/cobra#1532

[0] spf13/cobra#1044
[1] https://pkg.go.dev/text/template
[2] https://github.com/spf13/cobra/blob/v1.2.1/command.go#L491
[3] https://golang.org/doc/effective_go#init

containers#917
  • Loading branch information
HarryMichal committed Nov 21, 2021
1 parent 20681da commit c36b34a
Showing 1 changed file with 8 additions and 14 deletions.
22 changes: 8 additions & 14 deletions src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,6 @@ var (
)

func Execute() {
if err := setUpGlobals(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}

if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
Expand All @@ -75,6 +70,11 @@ func Execute() {
}

func init() {
if err := setUpGlobals(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}

persistentFlags := rootCmd.PersistentFlags()

persistentFlags.BoolVarP(&rootFlags.assumeYes,
Expand All @@ -96,12 +96,12 @@ func init() {
persistentFlags.CountVarP(&rootFlags.verbose, "verbose", "v", "Set log-level to 'debug'")

rootCmd.SetHelpFunc(rootHelp)
rootCmd.SetUsageFunc(rootUsage)

usageTemplate := fmt.Sprintf(`Run '%s --help' for usage.`, executableBase)
rootCmd.SetUsageTemplate(usageTemplate)
}

func preRun(cmd *cobra.Command, args []string) error {
cmd.Root().SilenceUsage = true

if err := setUpLoggers(); err != nil {
return err
}
Expand Down Expand Up @@ -244,12 +244,6 @@ func rootRun(cmd *cobra.Command, args []string) error {
return nil
}

func rootUsage(cmd *cobra.Command) error {
err := fmt.Errorf("Run '%s --help' for usage.", executableBase)
fmt.Fprintf(os.Stderr, "%s", err)
return err
}

func migrate() error {
logrus.Debug("Migrating to newer Podman")

Expand Down

0 comments on commit c36b34a

Please sign in to comment.