Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arguments not passed to the help function #2154

Open
marckhouzam opened this issue Jun 8, 2024 · 0 comments · May be fixed by #2158
Open

Arguments not passed to the help function #2154

marckhouzam opened this issue Jun 8, 2024 · 0 comments · May be fixed by #2158
Labels
area/cobra-command Core `cobra.Command` implementations kind/bug A bug in cobra; unintended behavior

Comments

@marckhouzam
Copy link
Collaborator

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 marckhouzam added kind/bug A bug in cobra; unintended behavior area/cobra-command Core `cobra.Command` implementations labels Jun 8, 2024
@marckhouzam marckhouzam linked a pull request Jun 10, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/cobra-command Core `cobra.Command` implementations kind/bug A bug in cobra; unintended behavior
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant