cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Pass arguments to the help function

Open marckhouzam opened this issue 8 months ago • 6 comments

Fixes #2154

This PR makes sure that when Cobra calls HelpFunc()(cmd, args), the proper arguments are passed to the function. With this, when the help function is overridden, the new function can choose to print the help output based on what the args are.

For example, say I write my own ls program, I could override the help function using SetHelpFunc() so that

  • ls -h would print List the content of the current directory
  • ls mydir -h would instead print List the content of the "mydir" directory

This PR fixed the two cases 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)

Another value of this fix is for programs that use plugins and want to ask the plugin what the help output should be. For instance the tanzu CLI does this, where if I type tanzu help cluster list the help function will call the cluster plugin but needs to tell it that it needs the help for the list command. This list argument needs this PR to get passed to the help function. One can see how the tanzu code had to use os.Args to work around this bug.

Unit tests have been added which also illustrate the different cases that that PR fixes. A test program is provided in #2154 to show the problem before this PR.

Please refer to a couple of comments I will add in the PR review for a concern about backwards-compatibility.

marckhouzam avatar Jun 10 '24 01:06 marckhouzam