cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Arguments not passed to the help function

Open marckhouzam opened this issue 8 months ago • 0 comments

I can override the help function using:

  • cmd.SetHelpFunc(func(c *cobra.Command, args []string)).

Notice that the new help function I will define takes a command and its arguments as parameters, just like we have in many cobra functions.

I may choose to print a different help text based on what args the user has typed. However, my help function does not get passed the correct args.

There are two situations where the help function is called:

  1. when using the --help/-h flag (e.g., prog sub arg1 -h)
  2. when using the help command (e.g., prog help sub arg1)

The below test shows that both cases are problematic (see program below). Try it on playground: https://go.dev/play/p/UvaMTHq5Mqp

# Notice that the "args" should be "arg1 arg2" but are not
Calling: prog sub arg1 arg2 -h
parameter cmd: sub
param args: [sub arg1 arg2 -h]

# Notice that the "args" should be "arg1 arg2" but are not
Calling: prog help sub arg1 arg2
parameter cmd: sub
param args: []
Test program
import (
	"fmt"
	"strings"

	"github.com/spf13/cobra"
)

func main() {
	var rootCmd = &cobra.Command{Use: "root"}
	rootCmd.AddCommand(&cobra.Command{Use: "sub"})

	rootCmd.SetHelpFunc(func(c *cobra.Command, args []string) {
		fmt.Printf("parameter cmd: %s\nparam args: %v\n", c.Name(), args)
	})

	args := []string{"sub", "arg1", "arg2", "-h"}
	fmt.Printf("Calling: prog %s\n", strings.Join(args, " "))
	rootCmd.SetArgs(args)
	rootCmd.Execute()

	args = []string{"help", "sub", "arg1", "arg2"}
	fmt.Printf("\nCalling: prog %s\n", strings.Join(args, " "))
	rootCmd.SetArgs(args)
	rootCmd.Execute()
}

marckhouzam avatar Jun 08 '24 18:06 marckhouzam