Commit graph

252 commits

Author SHA1 Message Date
Dmytro Milinevskyi
4fb0a66a34
flags: clarify documentation that LocalFlags related function do not modify the state (#2064) 2024-01-06 16:49:13 -05:00
Nir Soffer
a73b9c391a Fix help text for runnable plugin command
When creating a plugin without sub commands, the help text included the
command name (kubectl-plugin) instead of the display name (kubectl plugin):

    Usage:
      kubectl-plugin [flags]

The issue is that the usage line for this case does not use the
command path but the raw `Use` string, and this case was not tested.

Add a test for this case and fix UsageLine() to replace the command name
with the display name.

Tested using https://github.com/nirs/kubernetes/tree/sample-cli-plugin-help
2023-12-17 19:58:57 -05:00
Nir Soffer
df547f5fc6 Fix help text for plugins
When using `CommandDisplayNameAnnotation` we want to use it instead of
the command name in `--help` message or in the default help command.

With current code we get the wrong text in the --help usage text:

    Flags:
      -h, --help   help for kubectl-plugin

And in the long description of the default help command:

    $ kubectl cobraplugin help -h
    Help provides help for any command in the application.
    Simply type kubectl-plugin help [path to command] for full details.

The issue was hidden since the test checked only the Usage line.

Fixed by extracting a displayName() function and use it when creating
FlagSet and when formatting the default help flag usage and the help
command long description.

Enhance the TestPlugin to check all the lines including the command
name.
2023-12-17 19:58:57 -05:00
Ville Skyttä
3d8ac432bd
Micro-optimizations (#1957)
* Avoid redundant string splits

There likely isn't actually more than once to split in the source
strings in these cases, but avoid doing so anyway as we're only
interested in the first.

* Avoid redundant completion output target evaluations

The target is not to be changed while outputting completions, so resolve
it only once.

* Avoid redundant active help enablement evaluations

The enablement state is not to be changed during completion output, so
evaluate it only once.

* Preallocate some slices and maps with known size

* Avoid some unnecessary looping

* Use strings.Builder to construct suggestions
2023-11-23 12:24:33 -05:00
Nir Soffer
890302a35f
Support usage as plugin for tools like kubectl (#2018)
In this case the executable is `kubectl-plugin`, but we run it as:

    kubectl plugin

And the help text should reflect the actual usage of the command.

To create a plugin, add the cobra.CommandDisplayNameAnnotation:

    rootCmd := &cobra.Command{
        Use: "plugin",
        Annotations: map[string]string{
            cobra.CommandDisplayNameAnnotation: "kubectl plugin",
        }
    }

Internally this change modifies CommandPath() for the root command to
return the command display name instead of the command name. This is
used for error messages, help text generation, and completions.

CommandPath() is expected to have spaces and code using it already
handle spaces (e.g replacing with _), so hopefully this does not break
anything.

Fixes: #2017

Signed-off-by: Nir Soffer <nsoffer@redhat.com>
2023-11-02 08:15:26 -04:00
Marc Khouzam
8b1eba4761
Fix linter errors (#2052)
When using golangci-lint v1.55.0 some new errors were being reported.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-10-27 06:23:45 -04:00
vkhoroz
4cafa37bc4
Allow running persistent run hooks of all parents (#2044)
Currently, only one of the persistent pre-runs and post-runs is executed.
It is always the first one found in the parents chain, starting at this command.
Expected behavior is to execute all parents' persistent pre-runs and post-runs.

Dependent projects implemented various workarounds for this:
- manually building persistent hook chains (in every hook).
- applying some kind of monkey-patching on top of Cobra.

This change eliminates the necessity for such workarounds
by allowing to set a global variable EnableTraverseRunHooks.

Tickets:
- https://github.com/spf13/cobra/issues/216
- https://github.com/spf13/cobra/issues/252

Signed-off-by: Volodymyr Khoroz <volodymyr.khoroz@foundries.io>
2023-10-21 20:36:12 -04:00
Haoming Meng
95d8a1e45d
Add notes to doc on preRun and postRun condition (#2041) 2023-10-09 08:50:40 -04:00
Souma
0c72800b8d
Customizable error message prefix (#2023) 2023-09-08 13:29:06 -04:00
Unai Martinez-Corral
285460dca6
command: temporarily disable G602 due to securego/gosec#1005 (#2022) 2023-08-29 10:04:59 -04:00
Unai Martinez-Corral
9e6b58afc7
update copyright year (#1927) 2023-03-05 21:28:31 -05:00
Dominik Roos
b4f979ae35
completions: do not detect arguments with dash as 2nd char as flag (#1817)
Fixes #1816

Previously, arguments with a dash as the second character (e.g., 1-ff00:0:1)
were detected as a flag by mistake. This resulted in auto completion misbehaving
if such an argument was last in the argument list during invocation.
2023-01-02 19:58:36 -05:00
Yash Ladha
bf11ab6321
fix: func name in doc strings (#1885)
Corrected the function name at the start of doc strings, as per the convention
outlined in official go documentation: https://go.dev/blog/godoc
2022-12-25 15:08:39 -05:00
Brian Pursley
6b0bd3076c
fix: don't remove flag value that matches subcommand name (#1781)
When the command searches args to find the arg matching a
particular subcommand name, it needs to ignore flag values,
as it is possible that the value for a flag might match
the name of the sub command.

This change improves argsMinusFirstX() to ignore flag values
when it searches for the X to exclude from the result.
2022-11-07 23:12:02 -05:00
Marc Khouzam
10cf7be997
Check for group presence after full initialization (#1839)
Fixes #1831

By moving the check for help group existence to "ExecuteC()" we no
longer need groups to be added before AddCommand() is called.  This
provides more flexibility to developers and works better with the use
of "init()" for command creation.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2022-10-24 11:11:57 -04:00
Gustavo Bazan
860791844e
feat: make InitDefaultCompletionCmd public (#1467)
* feat: make InitDefaultCompletionCmd public

* PR comments

* Update man_docs_test.go

* Update README.md
2022-10-10 19:06:30 -04:00
aawsome
2169adb574
Add groups for commands in help (#1003)
* Add tests for grouping commands
* Adds Additional Command section in help

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2022-10-10 14:59:11 -06:00
Marc Khouzam
212ea40783
Include --help and --version flag in completion (#1813)
Fixes #1786

The --help, -h, --version and -v flags are normally added when the
`execute()` function is called on a command.  When doing completion
we don't call `execute()` so we need to add these flags explicitly to
the command being completed.

Also, we disable all further completions if the 'help' or 'version'
flags are present on the command-line.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2022-10-04 16:41:30 -06:00
Yann Soubeyrand
93d1913fb0
Add OnFinalize method (#1788)
This method is the OnInitialize counterpart. Like OnInitialize which allows
loading the configuration before each command is executed, OnFinalize allows
saving the configuration after each command has been executed.
2022-10-03 08:52:50 -06:00
Francis Nickels III
7039e1fa21
Add '--version' flag to Help output (#1707) 2022-09-30 14:26:05 -04:00
Skeet WU
fce8d8aeb0
Expose ValidateRequiredFlags and ValidateFlagGroups (#1760) 2022-09-27 06:27:48 -04:00
Unai Martinez-Corral
6d978a911e
add missing license headers (#1809) 2022-09-16 07:55:56 -04:00
Yuval Goldberg
d689184a42
Support for case-insensitive command names (#1802)
Add a global `EnableCaseInsensitive` variable to allow
case-insensitive command names.

The variable supports commands names and aliases globally.

Resolves #1382
2022-09-11 08:25:22 -04:00
Paul Meyer
2a7647ff46
Clarify SetContext documentation (#1748) 2022-08-29 22:12:56 -04:00
Brian Pursley
22b617914c
fix: show flags that shadow parent persistent flag in child help (#1776)
This fixes a bug where a child flag that shadows (has the same
name as) a parent persistent flag would not be shown in the
child command's help output and the parent flag would be shown
instead under the global flags section.

This change makes the help output consistent with the
observed behavior during execution, where the child flag is
the one that is actually used.
2022-08-28 12:46:39 -04:00
Paul Holzinger
b9ca5949e2
use errors.Is() to check for errors (#1730)
Since go 1.13 you can wrap errors. This make it no longer possible to
compare with `==`, instead you have to compare with `errors.Is()`.

I noticed this problem because -h was no longer working after I stared
wrapping the errors in my custom FlagErrorFunc function.
Note that this is only a problem when a custom help flag is defined.

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
2022-06-20 20:02:33 -06:00
Unai Martinez-Corral
ea94a3db55
undefined or nil Args default to ArbitraryArgs (#1612) 2022-06-20 20:00:50 -06:00
John Schnake
68b6b24f0c
Add ability to mark flags as required or exclusive as a group (#1654)
This change adds two features for dealing with flags:
 - requiring flags be provided as a group (or not at all)
 - requiring flags be mutually exclusive of each other

By utilizing the flag annotations we can mark which flag groups
a flag is a part of and during the parsing process we track which
ones we have seen or not.

A flag may be a part of multiple groups. The list of flags and the
type of group (required together or exclusive) make it a unique group.

Signed-off-by: John Schnake <jschnake@vmware.com>
2022-04-17 16:04:57 -05:00
Paul Meyer
3a1795bc25
Fix Command.Context comment (#1639) 2022-03-21 13:35:35 -04:00
Joshua Carpeggiani
f848943afd
Add Command.SetContext (#1551)
Increases flexibility in how Contexts can be used with Cobra.
2022-03-18 06:01:58 -04:00
Paul Holzinger
de187e874d
Fix flag completion (#1438)
* Fix flag completion

The flag completion functions should not be stored in the root cmd.
There is no requirement that the root cmd should be the same when
`RegisterFlagCompletionFunc` was called. Storing the flags there does
not work when you add the the flags to your cmd struct before you add the
cmd to the parent/root cmd. The flags can no longer be found in the rigth
place when the completion command is called and thus the flag completion
does not work.

Also #1423 claims that this would be thread safe but we still have a map
which will fail when accessed concurrently. To truly fix this issue use a
RWMutex.

Fixes #1437
Fixes #1320

Signed-off-by: Paul Holzinger <pholzing@redhat.com>

* Fix trailing whitespaces in fish comp scripts

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
2021-07-02 09:25:47 -06:00
silenceshell
3c8a19ecd3
fix RegisterFlagCompletionFunc concurrent map writes error (#1423)
* fix-RegisterFlagCompletionFunc-concurrent
* set to root command
* move to non-public fields
2021-06-30 15:49:30 -06:00
Marc Khouzam
b36196066e
Bash completion V2 with completion descriptions (#1146)
* Bash completion v2

This v2 version of bash completion is based on Go completions.
It also supports descriptions like the other shells.

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>

* Only consider matching completions for formatting

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>

* Use bash compV2 for the default completion command

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>

* Update comments that still referred to bash completion

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
2021-06-30 15:24:58 -06:00
Lukas Malkmus
6d00909120
Pass context to completion (#1265) 2021-05-03 10:33:57 -06:00
Marc Khouzam
b312f0a8ef
Create 'completion' command automatically (#1192)
Make it easier for programs to provide shell completion by creating
the 'completion' command automatically.

If a 'completion' command is already provided by the program, Cobra
will use that one instead.

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
2021-02-15 10:47:01 -07:00
Unai Martinez-Corral
652c755d37
Use golangci-lint (#1044)
Use golangci-lint. Repair warnings and errors resulting from linting.
2021-02-07 17:08:50 -07:00
namusyaka
7df62f7668
fix typos (#1274) 2020-12-04 12:34:11 -07:00
Alessio Treglia
40d34bca1b
Fix stderr printing functions (#894)
* Fix stderr printing functions

Follow-up of #822

* Errors go to stderr as per POSIX

* use PrintErrf() instead of extra call to Sprintf()

* Error messages should always be printed to os.Stderr.

* add test case for Print* redirection

Thanks: @bukowa for the patch.
2020-10-01 09:28:00 -06:00
Michael Muré
8cfa4b4acf
Add documentation for Use (#1188) 2020-08-18 14:14:09 -06:00
Marc Khouzam
04318720db
Add completion for help command (#1136)
* Don't exclude 'help' from bash completions

Fixes #1000.

* Provide completion for the help command

1- Show 'help' as a possible completion
2- Provide completions for the help command itself

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>

Co-authored-by: Zaven Muradyan <voithos@google.com>
2020-06-16 14:49:26 -06:00
Marc Khouzam
5155946348
Ignore required flags when DisableFlagParsing (#1095)
When a command request to DisableFlagParsing, it should not fail due
to a missing required flag.  In fact, such a check will always fail
since flags weren't parsed!

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
2020-05-07 19:18:16 -06:00
Marc Khouzam
b84ef40338
Rename BashCompDirectives to ShellCompDirectives (#1082)
Since the completion directives will be used for all shells, and that
these names will be consumed by users, this is a more appropriate name.

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
2020-04-06 11:28:44 -06:00
Marc Khouzam
b80aeb17fc
Add support for custom completions in Go (#1035)
This commit allows programs using Cobra to code their custom completions
in Go instead of Bash.

The new ValidArgsFunction field is added for commands, similarly to
ValidArgs.  For flags, the new function
Command.RegisterFlagCompletionFunc() is added.

When either of the above functions is used, the bash completion script
will call the new hidden command '__complete', passing it all
command-line arguments. The '__complete' command will call
the function specified by Command.ValidArgsFunction or by
Command.RegisterFlagCompletionFunc to obtain completions from the
program itself.

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
2020-04-03 13:43:43 -06:00
Joshua Harshman
6607e6b860
Partial Revert of #922 (#1068)
Issue Reference: https://github.com/spf13/cobra/issues/1056

https://github.com/spf13/cobra/pull/922 introduced a new error
type that emitted when a command was not runnable. This caused
all commands w/o a run function set to error w/ that message and a status code of 1.

This change reverts the addition of that new error. Similar
functionality can be accomplished by leveraging RunE.
2020-03-27 14:38:32 -06:00
Dave Henderson
95f2f73ed9
Add short version flag -v when not otherwise set (#996)
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
2020-02-28 11:13:40 -07:00
Daniel Esponda
3c2624538b
Correct documentation for InOrStdin (#929)
Documentation on function is incorrect
2020-02-20 11:42:29 -07:00
Alexandr Burdiyan
0da0687426
Add support for context.Context 2020-02-20 07:29:50 +01:00
Marc Khouzam
0d9d2d46f3 Revert change so help is printed on stdout again (#1004)
Fixes #1002
For backwards compatibility reasons, and to follow the need of
https://github.com/kubernetes/kubernetes/pull/26077#issuecomment-230818900
the help message should be printed on stdout.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2019-12-23 13:38:24 -05:00
Bruce Downs
993cc5372a Adjustments per PR review feedback from @bogem 2019-08-02 01:25:21 +05:00
Bruce Downs
51f06c7dd1 Correct all complaints from golint
* i.e.
* go get golang.org/x/lint/golint
* go list ./... | xargs golint
2019-08-02 01:25:21 +05:00