Skip to content

Commit

Permalink
Fix help for Cobra commands
Browse files Browse the repository at this point in the history
* The help function was shadowing the root command via 'cmd'
* Cobra-defined commands probably have no legacy CLI help so we print their
  usage string
  • Loading branch information
pjcdawkins committed Jan 3, 2025
1 parent 99278e3 commit e8e217c
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func newRootCommand(cnf *config.Config, assets *vendorization.VendorAssets) *cob
}()
}
},
Run: func(cmd *cobra.Command, _ []string) {
Run: func(cmd *cobra.Command, args []string) {
c := &legacy.CLIWrapper{
Config: cnf,
Version: config.Version,
Expand All @@ -93,7 +93,7 @@ func newRootCommand(cnf *config.Config, assets *vendorization.VendorAssets) *cob
return
}

if err := c.Exec(cmd.Context(), os.Args[1:]...); err != nil {
if err := c.Exec(cmd.Context(), args...); err != nil {
debugLog("%s\n", color.RedString(err.Error()))
exitCode := 1
var execErr *exec.ExitError
Expand All @@ -113,16 +113,22 @@ func newRootCommand(cnf *config.Config, assets *vendorization.VendorAssets) *cob
},
}

cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
if cmd.Context() == nil {
cmd.SetContext(context.Background())
cmd.SetHelpFunc(func(innerCmd *cobra.Command, args []string) {
if innerCmd.Use != cmd.Use {
// For real (Cobra) commands, print the usage string.
innerCmd.Println(innerCmd.UsageString())
return
}

// Others will be passed to the legacy CLI's help command.
if !slices.Contains(args, "--help") && !slices.Contains(args, "-h") {
args = append([]string{"help"}, args...)
}
if len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
args = []string{"help"}
}

cmd.Run(cmd, args)
cmd.Run(innerCmd, args)
})

cmd.PersistentFlags().BoolP("version", "V", false, fmt.Sprintf("Displays the %s version", cnf.Application.Name))
Expand Down

0 comments on commit e8e217c

Please sign in to comment.