Skip to content

Arguments not passed to the help function  #2154

Open
@marckhouzam

Description

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()
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    area/cobra-commandCore `cobra.Command` implementationskind/bugA bug in cobra; unintended behavior

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions