Make the default completion command accessible #1523
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1507 as requested by @jpmcb
The ask of #1507 was to be able to make the default
completion
command hidden.I may have gone too far with this PR so I'm looking for opinions 🤷♂️
This PR goes much beyond the ask and makes the
completion
command and it's four sub-commands fully accessible so the program can set whatever field it wants before callingrootCmd.Execute()
. For example, a program could callor/and
or/and
How the new logic works:
1- the default completion command and its 4 sub-commands are now public global variables
2- at initialization the fields of these global variables that don't need special info are initialized (cmd.Use, cmd.Short, cmd.Args, cmd.ValidArgsFunction)
3- during rootCmd.Execute() the function cmd.initDefaultCompletionCmd() is called like before and initializes the remaining fields (these fields needed the program name and root command: cmd.Long, cmd.RunE and the flag)
The magic is that between point 2 and point 3, a program can modify the fields of these commands since they are accessible.
If this brings in too much complexity, we could simply offer a new option in
CompletionOptions
to allow hiding the command.I made the effort of trying to be as flexible as possible because we got PRs that needed to change the descriptions and such which were slightly off. With this PR consumers should be able to adjust anything themselves. But it is more complex. And I had to do a little bit of resetting things so that go tests, which call
rootCmd.Execute()
multiple times would continue work; this is something we already do for the help command however, as we can see here:cobra/command.go
Line 1114 in f09e947
Opinions please. 😄
P.S. No tests added yet.