Compare commits

...

85 commits
v1.6.0 ... main

Author SHA1 Message Date
Ville Skyttä e94f6d0dd9
Address golangci-lint deprecation warnings, enable some more linters (#2152)
* Address golangci-lint linter deprecation warnings

1.59.0 outputs:

WARN [lintersdb] The name "gas" is deprecated. The linter has been renamed to: gosec.
WARN [lintersdb] The linter named "megacheck" is deprecated. It has been split into: gosimple, staticcheck, unused.

* Enable some more linters, address finding
2024-06-01 06:31:11 -04:00
Nir Soffer 8003b74a10
Remove fully inactivated linters (#2148)
* Remove fully inactivated linters

Currently golangci-lint fails with these errors:

ERRO [linters_context] golint: This linter is fully inactivated: it will not produce any reports.
ERRO [linters_context] interfacer: This linter is fully inactivated: it will not produce any reports.
ERRO [linters_context] maligned: This linter is fully inactivated: it will not produce any reports.

I could not find any docs explaining what "fully inactivated" mean, but
based this PR[1] it seems that these linters do nothing now. Removing
the linters fixes this issue without changing linting, as they did not
produce any report.

Looking in the linters docs[2] I did not find a replacement for
"interfacer" and "malinged" linters. "stylecheck" seems to be a
replacement for "golint", but we need to fix the code to enable it.

[1] https://github.com/golangci/golangci-lint/pull/4436
[2] https://golangci-lint.run/usage/linters/

* Add stylecheck linter, replacement for golint

This revealed 2 capitalized error messages.

https://golangci-lint.run/usage/linters/#stylecheck
2024-05-18 22:12:02 -04:00
Nir Soffer 5c2c1d627d
Consistent annotation names (#2140)
Add `Annotation` suffix to the private annotations to allow nicer code
using the constants.

For example one can use the current annotation names as a temporary
variable instead of unclear shortcut. Instead of this:

    rag := flagsFromAnnotation(c, f, requiredAsGroup)
    me := flagsFromAnnotation(c, f, mutuallyExclusive)
    or := flagsFromAnnotation(c, f, oneRequired)

We can use now:

    requiredAsGrop := flagsFromAnnotation(c, f, requiredAsGroupAnnotation)
    mutuallyExclusive := flagsFromAnnotation(c, f, mutuallyExclusiveAnnotation)
    oneRequired := flagsFromAnnotation(c, f, oneRequiredAnnotation)

Example taken from #2105.
2024-05-18 09:41:31 -04:00
dependabot[bot] 5a1acea321
build(deps): bump github.com/cpuguy83/go-md2man/v2 from 2.0.3 to 2.0.4 (#2127) 2024-04-13 02:21:03 +00:00
Xinwei Xiong 0fc86c2ffd
docs: update user guide (#2128) 2024-04-08 06:47:35 -04:00
Ville Skyttä 6b5f577ebc
More linting (#2099)
* Address gocritic findings, enable it

* Enable gosimple, no new findings to address
2024-04-01 08:42:08 -04:00
Pedro Mota bd914e58d6
fix: remove deprecated io/ioutils package (#2120)
ioutils.ReadAll is deprecated since Go 1.16. This commit replaces it with
io.ReadAll. See https://pkg.go.dev/io/ioutil\#ReadAll for reference

Issue #2119
2024-03-12 06:42:46 -04:00
racerole 1f80fa2e23
chore: remove repetitive words (#2122)
Signed-off-by: racerole <jiangyifeng@outlook.com>
2024-03-12 06:40:19 -04:00
damas c69ae4c36b
ci: test golang 1.22 (#2113) 2024-03-12 06:40:01 -04:00
dependabot[bot] a30cee5e5a
build(deps): bump actions/cache from 3 to 4 (#2102)
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-11 19:36:37 -06:00
dependabot[bot] f34069ccf5
build(deps): bump golangci/golangci-lint-action from 3.7.0 to 4.0.0 (#2108)
Bumps [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) from 3.7.0 to 4.0.0.
- [Release notes](https://github.com/golangci/golangci-lint-action/releases)
- [Commits](https://github.com/golangci/golangci-lint-action/compare/v3.7.0...v4.0.0)

---
updated-dependencies:
- dependency-name: golangci/golangci-lint-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-11 19:35:05 -06:00
montag451 bd2655e76c
Add Incus to the list of projects using Cobra (#2118) 2024-03-07 19:36:58 -05:00
Radek Smid bcfcff729e
Add Taikun CloudWorks to list of projects (#2098) 2024-01-15 08:38:50 -05:00
Dmytro Milinevskyi 4fb0a66a34
flags: clarify documentation that LocalFlags related function do not modify the state (#2064) 2024-01-06 16:49:13 -05:00
Denis 0dec88e793
Add tests for funcs in cobra.go (#2094) 2023-12-30 08:40:15 -05:00
Case Wylie cbcf75eab9
[chore]: update projects using cobra (#2093)
Signed-off-by: Case Wylie <cmwylie19@defenseunicorns.com>
2023-12-27 21:16:29 -05:00
dependabot[bot] 199b7abe12
build(deps): bump actions/labeler from 4 to 5 (#2086)
* build(deps): bump actions/labeler from 4 to 5

Bumps [actions/labeler](https://github.com/actions/labeler) from 4 to 5.
- [Release notes](https://github.com/actions/labeler/releases)
- [Commits](https://github.com/actions/labeler/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/labeler
  dependency-type: direct:production
  update-type: version-update:semver-major
...

* Update labeler configuration for v5

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-12-23 14:52:45 -05:00
Marc Khouzam 531ce793e3 Remove extra actions/checkout
Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-12-23 13:49:43 -05:00
dependabot[bot] c054701f6a build(deps): bump actions/setup-go from 4 to 5
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 4 to 5.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-23 13:49:43 -05:00
Nir Soffer 41227856cd Document how to create a plugin
Using the new CommandDisplayNameAnnotation annotation introduced in
Cobra 1.8.0.
2023-12-17 19:58:57 -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ä e63925d321
Add env variable to suppress completion descriptions on create (#1938)
COBRA_COMPLETION_DESCRIPTIONS=0 
or 
<PROGRAM>_COMPLETION_DESCRIPTIONS=0
can now be used to disable shell completion descriptions.
2023-12-17 13:50:59 -05:00
Marcus Kohlberg 236f3c0418
Update projects_using_cobra.md (#2089)
Add Encore to the list of projects using Cobra
2023-12-12 11:26:29 -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
SwagPack 283e32d889
Add LXC to the list of projects using cobra (#2071) 2023-11-13 11:55:06 -05:00
Marc Khouzam a0a6ae020b
Improve API to get flag completion function (#2063)
The new API is simpler and matches the `c.RegisterFlagCompletionFunc()`
API.  By removing the global function `GetFlagCompletion()` we are more
future proof if we ever move from a global map of flag completion
functions to something associated with the command.

The commit also makes this API work with persistent flags by using
`c.Flag(flagName)` instead of `c.Flags().Lookup(flagName)`.

The commit also adds unit tests.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-11-02 11:23:08 -04: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
dependabot[bot] 48cea5c87b
build(deps): bump actions/checkout from 3 to 4 (#2028) 2023-10-30 10:21:48 +00:00
Ville Skyttä 22953d8845
Replace all non-alphanumerics in active help env var program prefix (#1940)
* Replace all non-alphanumerics in active help env var program prefix

There are other characters besides the dash that are fine in program
names, but are problematic in environment variable names. These include
(but are not limited to) period, space, and non-ASCII letters.

* Another change in docs to mention non-ASCII-alphanumeric instead of just dash
2023-10-29 12:06:51 -06:00
Marc Khouzam 00b68a1c26
Add tests for flag completion registration (#2053)
Different problems have been reported about flag completion registration.
These two tests are the cases that were not being verified but had been
mentioned as problematic.

Ref:
- https://github.com/spf13/cobra/issues/1320
- https://github.com/spf13/cobra/pull/1438#issuecomment-872928669

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-10-28 16:11:59 -04:00
Marc Khouzam b711e8760b
Don't complete --help flag when flag parsing disabled (#2061)
Fixes #2060

When a command sets `DisableFlagParsing = true` it requests the
responsibility of doing all the flag parsing. Therefore even the
`--help/-f/--version/-v` flags should not be automatically completed
by Cobra in such a case.

Without this change the `--help/-h/--version/-v` flags can end up being
completed twice for plugins: one time from cobra and one time from the
plugin (which has set `DisableFlagParsing = true`).

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-10-28 16:10:06 -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
dependabot[bot] 5c962a221e
build(deps): bump github.com/cpuguy83/go-md2man/v2 from 2.0.2 to 2.0.3 (#2047) 2023-10-16 10:50:33 +00:00
dependabot[bot] efe8fa3e44
build(deps): bump actions/setup-go from 3 to 4 (#1934) 2023-10-15 11:16:50 +00:00
Haoming Meng 95d8a1e45d
Add notes to doc on preRun and postRun condition (#2041) 2023-10-09 08:50:40 -04:00
Alexandru-Claudius Virtopeanu bd4d1655f6
feat: add getters for flag completions (#1943) 2023-09-25 20:04:25 -04:00
Souma 0c72800b8d
Customizable error message prefix (#2023) 2023-09-08 13:29:06 -04:00
Nuno Adrego c5dacb3ea4
ci: test golang 1.21 (#2024) 2023-09-07 20:30:51 -04:00
Unai Martinez-Corral 285460dca6
command: temporarily disable G602 due to securego/gosec#1005 (#2022) 2023-08-29 10:04:59 -04:00
dependabot[bot] 4955da7c11
build(deps): bump golangci/golangci-lint-action from 3.6.0 to 3.7.0 (#2021) 2023-08-28 18:53:34 +00:00
Jun Nishimura fd865a44e3
minor corrections to unit tests (#2003) 2023-07-23 07:31:55 -04:00
gocurr 60d056d157
doc: fix typo, Deperecated -> Deprecated (#2000) 2023-07-20 11:27:44 -04:00
Unai Martinez-Corral 66b215ba18
golangci: enable 'unused' and disable deprecated replaced by it (#1983) 2023-07-18 09:51:36 -04:00
Martijn Evers c81c46a015
Add 'one required flag' group (#1952) 2023-07-16 12:38:22 -04:00
Unai Martinez-Corral dcb405a939
Move documentation sources to site/content (#1428) 2023-06-20 17:15:36 -04:00
dependabot[bot] cbe4865373
build(deps): bump golangci/golangci-lint-action from 3.5.0 to 3.6.0 (#1976) 2023-06-20 20:46:35 +00:00
Paul Holzinger fdee73b4a0
powershell: escape variable with curly brackets (#1960)
This fixes an issue with program names that include a dot, in our case
`podman.exe`. This was caused by the change in commit 6ba7ebbc.

Fixes #1853

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
2023-06-19 12:16:18 -04:00
Branch Vincent 988bd76139
test: make fish_completions_test more robust (#1980)
Use temporary files instead of assuming the current directory is
writable. Also, if creating a temporary file still returns an error,
prevent the test from failing silently by replacing `log.Fatal` with
`t.Fatal`.
2023-06-16 10:25:30 -04:00
Taavi Väänänen 2246fa82e9
Fix grammar: 'allows to' (#1978)
The use in generated bash completion files is getting flagged by
Lintian (the Debian package linting tool).

Signed-off-by: Taavi Väänänen <hi@taavi.wtf>
2023-06-13 11:12:49 -04:00
dependabot[bot] 0e3a0bfe91
build(deps): bump golangci/golangci-lint-action from 3.4.0 to 3.5.0 (#1971) 2023-06-12 02:39:30 +00:00
Tom Payne 284f410104
Fix typo in fish completions (#1945) 2023-04-08 00:47:33 -04:00
Marc Khouzam 4dd4b25de3
Update main image to better handle dark background (#1883)
Fixes #1880

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Deleplace <deleplace2015@gmail.com>
2023-03-22 18:41:51 -04:00
Marc Khouzam 45360a55cc
Allow sourcing zsh completion script (#1917)
Although it is not the recommended approach, sourcing a completion
script is the simplest way to get people to try using shell completion.
Not allowing it for zsh has turned out to complicate shell completion
adoption.  Further, many tools modify the zsh script to allow sourcing.

This commit allows sourcing of the zsh completion script.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2023-03-22 18:41:05 -04:00
Luiz Carvalho c8a20a16ba
Document suggested layout for subcommands (#1930)
Signed-off-by: Luiz Carvalho <lucarval@redhat.com>
2023-03-16 21:03:29 -04:00
Florent Poinsard b197a24504
Update projects_using_cobra.md (#1932)
Signed-off-by: Florent Poinsard <florent.poinsard@outlook.fr>
2023-03-14 08:28:50 -04:00
Unai Martinez-Corral 9e6b58afc7
update copyright year (#1927) 2023-03-05 21:28:31 -05:00
Unai Martinez-Corral fb3652402b
ci: test Golang 1.20 (#1925) 2023-03-05 21:11:33 -05:00
Unai Martinez-Corral c7300f0bdd
ci: deprecate go 1.16 (#1926) 2023-03-05 21:07:19 -05:00
Oldřich Jedlička 567ea8ebc9
Add support for PowerShell 7.2+ (#1916)
PowerShell 7.2 has changed the way arguments are passed to executables.
This was originally an experimental feature in 7.2, but as of 7.3 it is
built-in. A simple "" is now sufficient for passing empty arguments, no
back-tick escaping is required.

Fixes #1849

Signed-off-by: Oldřich Jedlička <oldium.pro@gmail.com>
Co-authored-by: Oldřich Jedlička <oldrich.jedlicka@rohlik.cz>
2023-02-25 16:30:37 -05:00
Gyanendra Mishra 3daa4b9c36
Add keeporder to shell completion (#1903)
This allows programs to request the shell to maintain the order of completions that was returned by the program
2023-02-25 15:57:12 -05:00
John McBride a516d4132c
Removes stale bot from GitHub action (#1908)
Signed-off-by: John McBride <jpmmcbride@gmail.com>
2023-02-13 20:49:03 -07:00
dependabot[bot] e839bb342f
build(deps): bump golangci/golangci-lint-action from 3.3.1 to 3.4.0 (#1902) 2023-02-12 01:27:13 +00:00
Ggg6542 87ebcd8f98
Update shell_completions.md (#1907)
align documentation with the code : completions.go:452
2023-02-08 21:11:53 -05:00
janhn 8b8ee8754c
Improve MarkFlagsMutuallyExclusive example in User Guide (#1904) 2023-02-06 06:15:40 -05:00
Shihta Kuan d022c0fe2b
Add documentation about disabling completion descriptions (#1901) 2023-01-30 12:58:20 -05:00
dependabot[bot] 4fa4fdf5cd
build(deps): bump github.com/inconshreveable/mousetrap (#1872) 2023-01-03 02:43:06 +00: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
Seonghyeon Cho fdffa5a4c7
Update badge route (#1884)
Based on
https://github.com/badges/shields/issues/8671
2022-12-23 15:54:16 -05:00
Yash Ladha f25a3c6e0b
fix: conflict import name with variable (#1879)
`template` is an import in `cobra.go` file and also used as a variable
name, which masks the library in the scope of that function.
2022-12-15 05:39:50 -05:00
Unai Martinez-Corral 923592041e
ci: deprecate go 1.15 (#1866)
Remove testing for go 1.15 to allow CI to pass, but don't force projects to upgrade.
2022-12-09 16:57:19 -05:00
David Wertenteil a6f198b635
Update kubescape org (#1874)
Signed-off-by: David Wertenteil <dwertent@armosec.io>
2022-12-06 08:20:58 -05:00
dependabot[bot] 7bb1440003
build(deps): bump golangci/golangci-lint-action from 3.2.0 to 3.3.1 (#1851)
Bumps [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) from 3.2.0 to 3.3.1.
- [Release notes](https://github.com/golangci/golangci-lint-action/releases)
- [Commits](https://github.com/golangci/golangci-lint-action/compare/v3.2.0...v3.3.1)

---
updated-dependencies:
- dependency-name: golangci/golangci-lint-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-26 08:18:05 -05:00
Unai Martinez-Corral 6200c8e551
Makefile: add target richtest (#1865)
Don't require contributors to install richgo but keep it as an option and for CI
2022-11-25 15:55:09 -05:00
Norman Dankert c6b9971923
fix: force ForEach-Object to return array in pwsh completion (#1850)
Fixes #1847
2022-11-25 15:47:20 -05:00
Enrico Candino 430549841b
Update stale.yml (#1863) 2022-11-21 21:04:26 -05:00
Brian Pursley ad6db7f8f6
Create unit test illustrating unknown flag bug (#1854)
Created a unit test that tests the unknown flag
error message when the unknown flag is located
in different arg positions.
2022-11-14 21:46:57 -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
mike76-dev cc7e235fc2
Add Sia to projects using Cobra (#1844) 2022-11-01 09:15:28 -04: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
doniacld 4b9d00dfec
Replace deprecated ExactValidArgs with MatchAll in user_guide and shell_completions example (#1836) 2022-10-20 16:33:37 -04:00
Ville Skyttä badcce14f8
style(bash-v2): various cleanups (#1702)
* use arithmetic evaluation in numeric context

* remove unnecessary $ from array index variables

* [[ ]] over [ ], == over =, remove unnecessary quoting

* use ${foo-} rather than ${foo:-} in emptiness check

The result of the expansion is null no matter if the variable is unset
or null in both cases; the former form is arguably easier on the eye.

* remove unnecessary trailing linefeed removal

No longer needed as of f464d6c82e, saves
a subshell.

* use herestring in activehelp extraction

Herestrings read cleaner than process substitutions, and work in posix
mode (but we do and will have some process substitutions so this doesn't
matter much). Both approaches may end up using temporary files.
2022-10-17 15:24:27 -04:00
Fabian Kammel 1424b7b927
Add Constellation to projects using cobra. (#1829) 2022-10-13 09:47:58 -04:00
61 changed files with 1977 additions and 473 deletions

19
.github/labeler.yml vendored
View file

@ -1,17 +1,24 @@
# changes to documentation generation
"area/docs-generation": doc/**/*
"area/docs-generation":
- changed-files:
- any-glob-to-any-file: 'doc/**'
# changes to the core cobra command
"area/cobra-command":
- any: ['./cobra.go', './cobra_test.go', './*command*.go']
- changed-files:
- any-glob-to-any-file: ['./cobra.go', './cobra_test.go', './*command*.go']
# changes made to command flags/args
"area/flags": ./args*.go
"area/flags":
- changed-files:
- any-glob-to-any-file: './args*.go'
# changes to Github workflows
"area/github": .github/**/*
"area/github":
- changed-files:
- any-glob-to-any-file: '.github/**'
# changes to shell completions
"area/shell-completion":
- ./*completions*
- changed-files:
- any-glob-to-any-file: './*completions*'

View file

@ -12,7 +12,7 @@ jobs:
pull-requests: write # for actions/labeler to add labels to PRs
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v4
- uses: actions/labeler@v5
with:
repo-token: "${{ github.token }}"

View file

@ -1,56 +0,0 @@
name: Mark stale issues and pull requests
on:
schedule:
- cron: "0 0 * * *"
permissions:
contents: read
jobs:
stale:
permissions:
issues: write # for actions/stale to close stale issues
pull-requests: write # for actions/stale to close stale PRs
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v6
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "The Cobra project currently lacks enough contributors to adequately respond to all issues.
This bot triages issues and PRs according to the following rules:
- After 60d of inactivity, lifecycle/stale is applied.
- After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the issue is closed.
You can:
- Make a comment to remove the stale label and show your support. The 60 days reset.
- If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening"
stale-pr-message: "The Cobra project currently lacks enough contributors to adequately respond to all PRs.
This bot triages issues and PRs according to the following rules:
- After 60d of inactivity, lifecycle/stale is applied.
- After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the PR is closed.
You can:
- Make a comment to remove the stale label and show your support. The 60 days reset.
- If a PR has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening."
days-before-stale: 60
days-before-close: 30
stale-issue-label: 'lifecycle/stale'
stale-pr-label: 'lifecycle/stale'
exempt-issue-labels: 'lifecycle/frozen'
exempt-pr-labels: 'lifecycle/frozen'
close-issue-label: 'lifecycle/rotten'
close-pr-label: 'lifecycle/rotten'
# Since cobra has so many legacy issues and PRs that need to be triaged,
# only label new PRs and issues.
start-date: '2022-02-01T00:00:00Z'

View file

@ -18,14 +18,14 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- run: >-
docker run
-v $(pwd):/wrk -w /wrk
ghcr.io/google/addlicense
-c 'The Cobra Authors'
-y '2013-2022'
-y '2013-2023'
-l apache
-ignore '.github/**'
-check
@ -39,17 +39,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v3
- uses: actions/setup-go@v5
with:
go-version: '^1.19'
go-version: '^1.22'
check-latest: true
cache: true
- uses: actions/checkout@v3
- uses: golangci/golangci-lint-action@v3.2.0
- uses: golangci/golangci-lint-action@v4.0.0
with:
version: latest
args: --verbose
@ -63,32 +61,29 @@ jobs:
- ubuntu
- macOS
go:
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'
runs-on: ${{ matrix.platform }}-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v3
- uses: actions/setup-go@v5
with:
go-version: 1.${{ matrix.go }}.x
cache: true
- run: |
export GOBIN=$HOME/go/bin
case "${{ matrix.go }}" in
14|15) _version='';;
*) _version='@latest';;
esac
go install github.com/kyoh86/richgo"${_version}"
go install github.com/mitchellh/gox"${_version}"
go install github.com/kyoh86/richgo@latest
go install github.com/mitchellh/gox@latest
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make test
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make richtest
test-win:
@ -112,9 +107,9 @@ jobs:
unzip
mingw-w64-x86_64-go
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions/cache@v3
- uses: actions/cache@v4
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-${{ matrix.go }}-${{ hashFiles('**/go.sum') }}
@ -125,4 +120,4 @@ jobs:
go install github.com/kyoh86/richgo@latest
go install github.com/mitchellh/gox@latest
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make test
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make richtest

View file

@ -1,4 +1,4 @@
# Copyright 2013-2022 The Cobra Authors
# Copyright 2013-2023 The Cobra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -19,44 +19,39 @@ linters:
disable-all: true
enable:
#- bodyclose
- deadcode
# - deadcode ! deprecated since v1.49.0; replaced by 'unused'
#- depguard
#- dogsled
#- dupl
- errcheck
#- exhaustive
#- funlen
- gas
#- gochecknoinits
- goconst
#- gocritic
- gocritic
#- gocyclo
#- gofmt
- gofmt
- goimports
- golint
#- gomnd
#- goprintffuncname
#- gosec
#- gosimple
- gosec
- gosimple
- govet
- ineffassign
- interfacer
#- lll
- maligned
- megacheck
#- misspell
- misspell
#- nakedret
#- noctx
#- nolintlint
- nolintlint
#- rowserrcheck
#- scopelint
#- staticcheck
- structcheck
#- stylecheck
- staticcheck
#- structcheck ! deprecated since v1.49.0; replaced by 'unused'
- stylecheck
#- typecheck
- unconvert
#- unparam
#- unused
- varcheck
- unused
# - varcheck ! deprecated since v1.49.0; replaced by 'unused'
#- whitespace
fast: false

View file

@ -5,10 +5,6 @@ ifeq (, $(shell which golangci-lint))
$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")
endif
ifeq (, $(shell which richgo))
$(warning "could not find richgo in $(PATH), run: go install github.com/kyoh86/richgo@latest")
endif
.PHONY: fmt lint test install_deps clean
default: all
@ -25,6 +21,10 @@ lint:
test: install_deps
$(info ******************** running tests ********************)
go test -v ./...
richtest: install_deps
$(info ******************** running tests with kyoh86/richgo ********************)
richgo test -v ./...
install_deps:

View file

@ -1,12 +1,12 @@
![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
![cobra logo](assets/CobraMain.png)
Cobra is a library for creating powerful modern CLI applications.
Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.
[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
@ -80,7 +80,7 @@ which maintains the same interface while adding POSIX compliance.
# Installing
Using Cobra is easy. First, use `go get` to install the latest version
of the library.
of the library.
```
go get -u github.com/spf13/cobra@latest
@ -105,8 +105,8 @@ go install github.com/spf13/cobra-cli@latest
For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).
For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md).
# License
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -17,15 +17,14 @@ package cobra
import (
"fmt"
"os"
"strings"
)
const (
activeHelpMarker = "_activeHelp_ "
// The below values should not be changed: programs will be using them explicitly
// in their user documentation, and users will be using them explicitly.
activeHelpEnvVarSuffix = "_ACTIVE_HELP"
activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
activeHelpEnvVarSuffix = "ACTIVE_HELP"
activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix
activeHelpGlobalDisable = "0"
)
@ -42,7 +41,7 @@ func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
// case, with all - replaced by _.
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
// is set to "0".
func GetActiveHelpConfig(cmd *Command) string {
@ -55,9 +54,7 @@ func GetActiveHelpConfig(cmd *Command) string {
// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
// variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
// root command in upper case, with all - replaced by _.
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
func activeHelpEnvVar(name string) string {
// This format should not be changed: users will be using it explicitly.
activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
return strings.ReplaceAll(activeHelpEnvVar, "-", "_")
return configEnvVar(name, activeHelpEnvVarSuffix)
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -21,7 +21,7 @@ import (
type PositionalArgs func(cmd *Command, args []string) error
// Legacy arg validation has the following behaviour:
// legacyArgs validation has the following behaviour:
// - root commands with no subcommands can take arbitrary arguments
// - root commands with subcommands will do subcommand validity checking
// - subcommands will always accept arbitrary arguments
@ -52,9 +52,9 @@ func OnlyValidArgs(cmd *Command, args []string) error {
if len(cmd.ValidArgs) > 0 {
// Remove any description that may be included in ValidArgs.
// A description is following a tab character.
var validArgs []string
validArgs := make([]string, 0, len(cmd.ValidArgs))
for _, v := range cmd.ValidArgs {
validArgs = append(validArgs, strings.Split(v, "\t")[0])
validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0])
}
for _, v := range args {
if !stringInSlice(v, validArgs) {

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

BIN
assets/CobraMain.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -85,7 +85,7 @@ __%[1]s_handle_go_custom_completion()
local out requestComp lastParam lastChar comp directive args
# Prepare the command to request completions for the program.
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
args=("${words[@]:1}")
# Disable ActiveHelp which is not supported for bash completion v1
requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"
@ -532,7 +532,7 @@ func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
}
}
// Setup annotations for go completions for registered flags
// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags
func prepareCustomAnnotationsForFlags(cmd *Command) {
flagCompletionMutex.RLock()
defer flagCompletionMutex.RUnlock()
@ -597,19 +597,16 @@ func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
if nonCompletableFlag(flag) {
return
}
for key := range flag.Annotations {
switch key {
case BashCompOneRequiredFlag:
format := " must_have_one_flag+=(\"--%s"
if flag.Value.Type() != "bool" {
format += "="
}
format += cbn
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok {
format := " must_have_one_flag+=(\"--%s"
if flag.Value.Type() != "bool" {
format += "="
}
format += cbn
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
if len(flag.Shorthand) > 0 {
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
}
if len(flag.Shorthand) > 0 {
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
}
}
})
@ -621,7 +618,7 @@ func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
for _, value := range cmd.ValidArgs {
// Remove any description that may be included following a tab character.
// Descriptions are not supported by bash completion.
value = strings.Split(value, "\t")[0]
value = strings.SplitN(value, "\t", 2)[0]
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
}
if cmd.ValidArgsFunction != nil {

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -38,7 +38,7 @@ func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
__%[1]s_debug()
{
if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
fi
}
@ -57,7 +57,7 @@ __%[1]s_get_completion_results() {
local requestComp lastParam lastChar args
# Prepare the command to request completions for the program.
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
args=("${words[@]:1}")
requestComp="${words[0]} %[2]s ${args[*]}"
@ -65,7 +65,7 @@ __%[1]s_get_completion_results() {
lastChar=${lastParam:$((${#lastParam}-1)):1}
__%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"
if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
if [[ -z ${cur} && ${lastChar} != = ]]; then
# If the last parameter is complete (there is a space following it)
# We add an extra empty parameter so we can indicate this to the go method.
__%[1]s_debug "Adding extra empty parameter"
@ -75,7 +75,7 @@ __%[1]s_get_completion_results() {
# When completing a flag with an = (e.g., %[1]s -n=<TAB>)
# bash focuses on the part after the =, so we need to remove
# the flag part from $cur
if [[ "${cur}" == -*=* ]]; then
if [[ ${cur} == -*=* ]]; then
cur="${cur#*=}"
fi
@ -87,7 +87,7 @@ __%[1]s_get_completion_results() {
directive=${out##*:}
# Remove the directive
out=${out%%:*}
if [ "${directive}" = "${out}" ]; then
if [[ ${directive} == "${out}" ]]; then
# There is not directive specified
directive=0
fi
@ -101,22 +101,36 @@ __%[1]s_process_completion_results() {
local shellCompDirectiveNoFileComp=%[5]d
local shellCompDirectiveFilterFileExt=%[6]d
local shellCompDirectiveFilterDirs=%[7]d
local shellCompDirectiveKeepOrder=%[8]d
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
if (((directive & shellCompDirectiveError) != 0)); then
# Error code. No completion.
__%[1]s_debug "Received error from custom completion go code"
return
else
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
if [[ $(type -t compopt) = "builtin" ]]; then
if (((directive & shellCompDirectiveNoSpace) != 0)); then
if [[ $(type -t compopt) == builtin ]]; then
__%[1]s_debug "Activating no space"
compopt -o nospace
else
__%[1]s_debug "No space directive not supported in this version of bash"
fi
fi
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
if [[ $(type -t compopt) = "builtin" ]]; then
if (((directive & shellCompDirectiveKeepOrder) != 0)); then
if [[ $(type -t compopt) == builtin ]]; then
# no sort isn't supported for bash less than < 4.4
if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then
__%[1]s_debug "No sort directive not supported in this version of bash"
else
__%[1]s_debug "Activating keep order"
compopt -o nosort
fi
else
__%[1]s_debug "No sort directive not supported in this version of bash"
fi
fi
if (((directive & shellCompDirectiveNoFileComp) != 0)); then
if [[ $(type -t compopt) == builtin ]]; then
__%[1]s_debug "Activating no file completion"
compopt +o default
else
@ -130,7 +144,7 @@ __%[1]s_process_completion_results() {
local activeHelp=()
__%[1]s_extract_activeHelp
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
# File extension filtering
local fullFilter filter filteringCmd
@ -143,13 +157,12 @@ __%[1]s_process_completion_results() {
filteringCmd="_filedir $fullFilter"
__%[1]s_debug "File filtering command: $filteringCmd"
$filteringCmd
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
elif (((directive & shellCompDirectiveFilterDirs) != 0)); then
# File completion for directories only
# Use printf to strip any trailing newline
local subdir
subdir=$(printf "%%s" "${completions[0]}")
if [ -n "$subdir" ]; then
subdir=${completions[0]}
if [[ -n $subdir ]]; then
__%[1]s_debug "Listing directories in $subdir"
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
else
@ -164,7 +177,7 @@ __%[1]s_process_completion_results() {
__%[1]s_handle_special_char "$cur" =
# Print the activeHelp statements before we finish
if [ ${#activeHelp[*]} -ne 0 ]; then
if ((${#activeHelp[*]} != 0)); then
printf "\n";
printf "%%s\n" "${activeHelp[@]}"
printf "\n"
@ -184,21 +197,21 @@ __%[1]s_process_completion_results() {
# Separate activeHelp lines from real completions.
# Fills the $activeHelp and $completions arrays.
__%[1]s_extract_activeHelp() {
local activeHelpMarker="%[8]s"
local activeHelpMarker="%[9]s"
local endIndex=${#activeHelpMarker}
while IFS='' read -r comp; do
if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then
if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
comp=${comp:endIndex}
__%[1]s_debug "ActiveHelp found: $comp"
if [ -n "$comp" ]; then
if [[ -n $comp ]]; then
activeHelp+=("$comp")
fi
else
# Not an activeHelp line but a normal completion
completions+=("$comp")
fi
done < <(printf "%%s\n" "${out}")
done <<<"${out}"
}
__%[1]s_handle_completion_types() {
@ -254,7 +267,7 @@ __%[1]s_handle_standard_completion_case() {
done < <(printf "%%s\n" "${completions[@]}")
# If there is a single completion left, remove the description text
if [ ${#COMPREPLY[*]} -eq 1 ]; then
if ((${#COMPREPLY[*]} == 1)); then
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
comp="${COMPREPLY[0]%%%%$tab*}"
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
@ -271,8 +284,8 @@ __%[1]s_handle_special_char()
if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
local word=${comp%%"${comp##*${char}}"}
local idx=${#COMPREPLY[*]}
while [[ $((--idx)) -ge 0 ]]; do
COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"}
while ((--idx >= 0)); do
COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}
done
fi
}
@ -298,7 +311,7 @@ __%[1]s_format_comp_descriptions()
# Make sure we can fit a description of at least 8 characters
# if we are to align the descriptions.
if [[ $maxdesclength -gt 8 ]]; then
if ((maxdesclength > 8)); then
# Add the proper number of spaces to align the descriptions
for ((i = ${#comp} ; i < longest ; i++)); do
comp+=" "
@ -310,8 +323,8 @@ __%[1]s_format_comp_descriptions()
# If there is enough space for any description text,
# truncate the descriptions that are too long for the shell width
if [ $maxdesclength -gt 0 ]; then
if [ ${#desc} -gt $maxdesclength ]; then
if ((maxdesclength > 0)); then
if ((${#desc} > maxdesclength)); then
desc=${desc:0:$(( maxdesclength - 1 ))}
desc+="…"
fi
@ -332,9 +345,9 @@ __start_%[1]s()
# Call _init_completion from the bash-completion package
# to prepare the arguments properly
if declare -F _init_completion >/dev/null 2>&1; then
_init_completion -n "=:" || return
_init_completion -n =: || return
else
__%[1]s_init_completion -n "=:" || return
__%[1]s_init_completion -n =: || return
fi
__%[1]s_debug
@ -361,7 +374,7 @@ fi
# ex: ts=4 sw=4 et filetype=sh
`, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
activeHelpMarker))
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -43,12 +43,13 @@ var initializers []func()
var finalizers []func()
const (
defaultPrefixMatching = false
defaultCommandSorting = true
defaultCaseInsensitive = false
defaultPrefixMatching = false
defaultCommandSorting = true
defaultCaseInsensitive = false
defaultTraverseRunHooks = false
)
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing
// to automatically enable in CLI tools.
// Set this to true to enable it.
var EnablePrefixMatching = defaultPrefixMatching
@ -60,6 +61,10 @@ var EnableCommandSorting = defaultCommandSorting
// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
var EnableCaseInsensitive = defaultCaseInsensitive
// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.
// By default this is disabled, which means only the first run hook to be found is executed.
var EnableTraverseRunHooks = defaultTraverseRunHooks
// MousetrapHelpText enables an information splash screen on Windows
// if the CLI is started from explorer.exe.
// To disable the mousetrap, just set this variable to blank string ("").
@ -167,8 +172,8 @@ func appendIfNotPresent(s, stringToAppend string) string {
// rpad adds padding to the right of a string.
func rpad(s string, padding int) string {
template := fmt.Sprintf("%%-%ds", padding)
return fmt.Sprintf(template, s)
formattedString := fmt.Sprintf("%%-%ds", padding)
return fmt.Sprintf(formattedString, s)
}
// tmpl executes the given template text on data, writing the result to w.
@ -188,8 +193,6 @@ func ld(s, t string, ignoreCase bool) int {
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -40,3 +40,185 @@ func TestAddTemplateFunctions(t *testing.T) {
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
}
}
func TestLevenshteinDistance(t *testing.T) {
tests := []struct {
name string
s string
t string
ignoreCase bool
expected int
}{
{
name: "Equal strings (case-sensitive)",
s: "hello",
t: "hello",
ignoreCase: false,
expected: 0,
},
{
name: "Equal strings (case-insensitive)",
s: "Hello",
t: "hello",
ignoreCase: true,
expected: 0,
},
{
name: "Different strings (case-sensitive)",
s: "kitten",
t: "sitting",
ignoreCase: false,
expected: 3,
},
{
name: "Different strings (case-insensitive)",
s: "Kitten",
t: "Sitting",
ignoreCase: true,
expected: 3,
},
{
name: "Empty strings",
s: "",
t: "",
ignoreCase: false,
expected: 0,
},
{
name: "One empty string",
s: "abc",
t: "",
ignoreCase: false,
expected: 3,
},
{
name: "Both empty strings",
s: "",
t: "",
ignoreCase: true,
expected: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Act
got := ld(tt.s, tt.t, tt.ignoreCase)
// Assert
if got != tt.expected {
t.Errorf("Expected ld: %v\nGot: %v", tt.expected, got)
}
})
}
}
func TestStringInSlice(t *testing.T) {
tests := []struct {
name string
a string
list []string
expected bool
}{
{
name: "String in slice (case-sensitive)",
a: "apple",
list: []string{"orange", "banana", "apple", "grape"},
expected: true,
},
{
name: "String not in slice (case-sensitive)",
a: "pear",
list: []string{"orange", "banana", "apple", "grape"},
expected: false,
},
{
name: "String in slice (case-insensitive)",
a: "APPLE",
list: []string{"orange", "banana", "apple", "grape"},
expected: false,
},
{
name: "Empty slice",
a: "apple",
list: []string{},
expected: false,
},
{
name: "Empty string",
a: "",
list: []string{"orange", "banana", "apple", "grape"},
expected: false,
},
{
name: "Empty strings match",
a: "",
list: []string{"orange", ""},
expected: true,
},
{
name: "Empty string in empty slice",
a: "",
list: []string{},
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Act
got := stringInSlice(tt.a, tt.list)
// Assert
if got != tt.expected {
t.Errorf("Expected stringInSlice: %v\nGot: %v", tt.expected, got)
}
})
}
}
func TestRpad(t *testing.T) {
tests := []struct {
name string
inputString string
padding int
expected string
}{
{
name: "Padding required",
inputString: "Hello",
padding: 10,
expected: "Hello ",
},
{
name: "No padding required",
inputString: "World",
padding: 5,
expected: "World",
},
{
name: "Empty string",
inputString: "",
padding: 8,
expected: " ",
},
{
name: "Zero padding",
inputString: "cobra",
padding: 0,
expected: "cobra",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Act
got := rpad(tt.inputString, tt.padding)
// Assert
if got != tt.expected {
t.Errorf("Expected rpad: %v\nGot: %v", tt.expected, got)
}
})
}
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -30,12 +30,15 @@ import (
flag "github.com/spf13/pflag"
)
const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
const (
FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
)
// FParseErrWhitelist configures Flag parse errors to be ignored
type FParseErrWhitelist flag.ParseErrorsWhitelist
// Structure to manage groups for commands
// Group Structure to manage groups for commands
type Group struct {
ID string
Title string
@ -47,7 +50,7 @@ type Group struct {
// definition to ensure usability.
type Command struct {
// Use is the one-line usage message.
// Recommended syntax is as follow:
// Recommended syntax is as follows:
// [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
// ... indicates that you can specify multiple values for the previous argument.
// | indicates mutually exclusive information. You can use the argument to the left of the separator or the
@ -99,7 +102,7 @@ type Command struct {
Deprecated string
// Annotations are key/value pairs that can be used by applications to identify or
// group commands.
// group commands or set special options.
Annotations map[string]string
// Version defines the version for this command. If this value is non-empty and the command does not
@ -115,6 +118,8 @@ type Command struct {
// * PostRun()
// * PersistentPostRun()
// All functions get the same args, the arguments after the command name.
// The *PreRun and *PostRun functions will only be executed if the Run function of the current
// command has been declared.
//
// PersistentPreRun: children of this command will inherit and execute.
PersistentPreRun func(cmd *Command, args []string)
@ -149,8 +154,10 @@ type Command struct {
// pflags contains persistent flags.
pflags *flag.FlagSet
// lflags contains local flags.
// This field does not represent internal state, it's used as a cache to optimise LocalFlags function call
lflags *flag.FlagSet
// iflags contains inherited flags.
// This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call
iflags *flag.FlagSet
// parentsPflags is all persistent flags of cmd's parents.
parentsPflags *flag.FlagSet
@ -181,6 +188,9 @@ type Command struct {
// versionTemplate is the version template defined by user.
versionTemplate string
// errPrefix is the error message prefix defined by user.
errPrefix string
// inReader is a reader defined by the user that replaces stdin
inReader io.Reader
// outWriter is a writer defined by the user that replaces stdout
@ -321,7 +331,7 @@ func (c *Command) SetHelpCommand(cmd *Command) {
c.helpCommand = cmd
}
// SetHelpCommandGroup sets the group id of the help command.
// SetHelpCommandGroupID sets the group id of the help command.
func (c *Command) SetHelpCommandGroupID(groupID string) {
if c.helpCommand != nil {
c.helpCommand.GroupID = groupID
@ -330,7 +340,7 @@ func (c *Command) SetHelpCommandGroupID(groupID string) {
c.helpCommandGroupID = groupID
}
// SetCompletionCommandGroup sets the group id of the completion command.
// SetCompletionCommandGroupID sets the group id of the completion command.
func (c *Command) SetCompletionCommandGroupID(groupID string) {
// completionCommandGroupID is used if no completion command is defined by the user
c.Root().completionCommandGroupID = groupID
@ -346,6 +356,11 @@ func (c *Command) SetVersionTemplate(s string) {
c.versionTemplate = s
}
// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.
func (c *Command) SetErrPrefix(s string) {
c.errPrefix = s
}
// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
// The user should not have a cyclic dependency on commands.
func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
@ -595,6 +610,18 @@ func (c *Command) VersionTemplate() string {
`
}
// ErrPrefix return error message prefix for the command
func (c *Command) ErrPrefix() string {
if c.errPrefix != "" {
return c.errPrefix
}
if c.HasParent() {
return c.parent.ErrPrefix()
}
return "Error:"
}
func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
flag := fs.Lookup(name)
if flag == nil {
@ -655,20 +682,44 @@ Loop:
// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
func argsMinusFirstX(args []string, x string) []string {
for i, y := range args {
if x == y {
ret := []string{}
ret = append(ret, args[:i]...)
ret = append(ret, args[i+1:]...)
return ret
// Special care needs to be taken not to remove a flag value.
func (c *Command) argsMinusFirstX(args []string, x string) []string {
if len(args) == 0 {
return args
}
c.mergePersistentFlags()
flags := c.Flags()
Loop:
for pos := 0; pos < len(args); pos++ {
s := args[pos]
switch {
case s == "--":
// -- means we have reached the end of the parseable args. Break out of the loop now.
break Loop
case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
fallthrough
case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
// This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip
// over the next arg, because that is the value of this flag.
pos++
continue
case !strings.HasPrefix(s, "-"):
// This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,
// return the args, excluding the one at this position.
if s == x {
ret := make([]string, 0, len(args)-1)
ret = append(ret, args[:pos]...)
ret = append(ret, args[pos+1:]...)
return ret
}
}
}
return args
}
func isFlagArg(arg string) bool {
return ((len(arg) >= 3 && arg[1] == '-') ||
return ((len(arg) >= 3 && arg[0:2] == "--") ||
(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
}
@ -686,7 +737,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) {
cmd := c.findNext(nextSubCmd)
if cmd != nil {
return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))
}
return c, innerArgs
}
@ -705,14 +756,14 @@ func (c *Command) findSuggestions(arg string) string {
if c.SuggestionsMinimumDistance <= 0 {
c.SuggestionsMinimumDistance = 2
}
suggestionsString := ""
var sb strings.Builder
if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
suggestionsString += "\n\nDid you mean this?\n"
sb.WriteString("\n\nDid you mean this?\n")
for _, s := range suggestions {
suggestionsString += fmt.Sprintf("\t%v\n", s)
_, _ = fmt.Fprintf(&sb, "\t%v\n", s)
}
}
return suggestionsString
return sb.String()
}
func (c *Command) findNext(next string) *Command {
@ -728,7 +779,9 @@ func (c *Command) findNext(next string) *Command {
}
if len(matches) == 1 {
return matches[0]
// Temporarily disable gosec G602, which produces a false positive.
// See https://github.com/securego/gosec/issues/1005.
return matches[0] // #nosec G602
}
return nil
@ -822,7 +875,7 @@ func (c *Command) ArgsLenAtDash() int {
func (c *Command) execute(a []string) (err error) {
if c == nil {
return fmt.Errorf("Called Execute() on a nil Command")
return fmt.Errorf("called Execute() on a nil Command")
}
if len(c.Deprecated) > 0 {
@ -886,15 +939,31 @@ func (c *Command) execute(a []string) (err error) {
return err
}
parents := make([]*Command, 0, 5)
for p := c; p != nil; p = p.Parent() {
if EnableTraverseRunHooks {
// When EnableTraverseRunHooks is set:
// - Execute all persistent pre-runs from the root parent till this command.
// - Execute all persistent post-runs from this command till the root parent.
parents = append([]*Command{p}, parents...)
} else {
// Otherwise, execute only the first found persistent hook.
parents = append(parents, p)
}
}
for _, p := range parents {
if p.PersistentPreRunE != nil {
if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
return err
}
break
if !EnableTraverseRunHooks {
break
}
} else if p.PersistentPreRun != nil {
p.PersistentPreRun(c, argWoFlags)
break
if !EnableTraverseRunHooks {
break
}
}
}
if c.PreRunE != nil {
@ -931,10 +1000,14 @@ func (c *Command) execute(a []string) (err error) {
if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
return err
}
break
if !EnableTraverseRunHooks {
break
}
} else if p.PersistentPostRun != nil {
p.PersistentPostRun(c, argWoFlags)
break
if !EnableTraverseRunHooks {
break
}
}
}
@ -998,6 +1071,10 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// initialize completion at the last point to allow for user overriding
c.InitDefaultCompletionCmd()
// Now that all commands have been created, let's make sure all groups
// are properly created also
c.checkCommandGroups()
args := c.args
// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
@ -1020,7 +1097,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
c = cmd
}
if !c.SilenceErrors {
c.PrintErrln("Error:", err.Error())
c.PrintErrln(c.ErrPrefix(), err.Error())
c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
}
return c, err
@ -1049,7 +1126,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// If root command has SilenceErrors flagged,
// all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors {
c.PrintErrln("Error:", err.Error())
c.PrintErrln(cmd.ErrPrefix(), err.Error())
}
// If root command has SilenceUsage flagged,
@ -1092,6 +1169,19 @@ func (c *Command) ValidateRequiredFlags() error {
return nil
}
// checkCommandGroups checks if a command has been added to a group that does not exists.
// If so, we panic because it indicates a coding error that should be corrected.
func (c *Command) checkCommandGroups() {
for _, sub := range c.commands {
// if Group is not defined let the developer know right away
if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {
panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))
}
sub.checkCommandGroups()
}
}
// InitDefaultHelpFlag adds default help flag to c.
// It is called automatically by executing the c or by calling help and usage.
// If c already has help flag, it will do nothing.
@ -1099,10 +1189,11 @@ func (c *Command) InitDefaultHelpFlag() {
c.mergePersistentFlags()
if c.Flags().Lookup("help") == nil {
usage := "help for "
if c.Name() == "" {
name := c.displayName()
if name == "" {
usage += "this command"
} else {
usage += c.Name()
usage += name
}
c.Flags().BoolP("help", "h", false, usage)
_ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
@ -1148,7 +1239,7 @@ func (c *Command) InitDefaultHelpCmd() {
Use: "help [command]",
Short: "Help about any command",
Long: `Help provides help for any command in the application.
Simply type ` + c.Name() + ` help [path to command] for full details.`,
Simply type ` + c.displayName() + ` help [path to command] for full details.`,
ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
var completions []string
cmd, _, e := c.Root().Find(args)
@ -1218,10 +1309,6 @@ func (c *Command) AddCommand(cmds ...*Command) {
panic("Command can't be a child of itself")
}
cmds[i].parent = c
// if Group is not defined let the developer know right away
if x.GroupID != "" && !c.ContainsGroup(x.GroupID) {
panic(fmt.Sprintf("Group id '%s' is not defined for subcommand '%s'", x.GroupID, cmds[i].CommandPath()))
}
// update max lengths
usageLen := len(x.Use)
if usageLen > c.commandsMaxUseLen {
@ -1259,7 +1346,7 @@ func (c *Command) AllChildCommandsHaveGroup() bool {
return true
}
// ContainGroups return if groupID exists in the list of command groups.
// ContainsGroup return if groupID exists in the list of command groups.
func (c *Command) ContainsGroup(groupID string) bool {
for _, x := range c.commandgroups {
if x.ID == groupID {
@ -1343,16 +1430,24 @@ func (c *Command) CommandPath() string {
if c.HasParent() {
return c.Parent().CommandPath() + " " + c.Name()
}
return c.displayName()
}
func (c *Command) displayName() string {
if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
return displayName
}
return c.Name()
}
// UseLine puts out the full usage for a given command (including parents).
func (c *Command) UseLine() string {
var useline string
use := strings.Replace(c.Use, c.Name(), c.displayName(), 1)
if c.HasParent() {
useline = c.parent.CommandPath() + " " + c.Use
useline = c.parent.CommandPath() + " " + use
} else {
useline = c.Use
useline = use
}
if c.DisableFlagsInUseLine {
return useline
@ -1554,7 +1649,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f
// to this command (local and persistent declared here and by all parents).
func (c *Command) Flags() *flag.FlagSet {
if c.flags == nil {
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
@ -1565,10 +1660,11 @@ func (c *Command) Flags() *flag.FlagSet {
}
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
persistentFlags := c.PersistentFlags()
out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.LocalFlags().VisitAll(func(f *flag.Flag) {
if persistentFlags.Lookup(f.Name) == nil {
out.AddFlag(f)
@ -1578,11 +1674,12 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
}
// LocalFlags returns the local FlagSet specifically set in the current command.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) LocalFlags() *flag.FlagSet {
c.mergePersistentFlags()
if c.lflags == nil {
c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
@ -1605,11 +1702,12 @@ func (c *Command) LocalFlags() *flag.FlagSet {
}
// InheritedFlags returns all flags which were inherited from parent commands.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) InheritedFlags() *flag.FlagSet {
c.mergePersistentFlags()
if c.iflags == nil {
c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
@ -1630,6 +1728,7 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
}
// NonInheritedFlags returns all flags which were not inherited from parent commands.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) NonInheritedFlags() *flag.FlagSet {
return c.LocalFlags()
}
@ -1637,7 +1736,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet {
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
func (c *Command) PersistentFlags() *flag.FlagSet {
if c.pflags == nil {
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
@ -1650,9 +1749,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
func (c *Command) ResetFlags() {
c.flagErrorBuf = new(bytes.Buffer)
c.flagErrorBuf.Reset()
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.flags.SetOutput(c.flagErrorBuf)
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.pflags.SetOutput(c.flagErrorBuf)
c.lflags = nil
@ -1769,7 +1868,7 @@ func (c *Command) mergePersistentFlags() {
// If c.parentsPflags == nil, it makes new.
func (c *Command) updateParentsPflags() {
if c.parentsPflags == nil {
c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.parentsPflags.SetOutput(c.flagErrorBuf)
c.parentsPflags.SortFlags = false
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -18,7 +18,7 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"io"
"os"
"reflect"
"strings"
@ -366,6 +366,67 @@ func TestAliasPrefixMatching(t *testing.T) {
EnablePrefixMatching = defaultPrefixMatching
}
// TestPlugin checks usage as plugin for another command such as kubectl. The
// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help
// text should reflect the way we run the command.
func TestPlugin(t *testing.T) {
cmd := &Command{
Use: "kubectl-plugin",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Run: emptyRun,
}
cmdHelp, err := executeCommand(cmd, "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, cmdHelp, "kubectl plugin [flags]")
checkStringContains(t, cmdHelp, "help for kubectl plugin")
}
// TestPlugin checks usage as plugin with sub commands.
func TestPluginWithSubCommands(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
}
subCmd := &Command{Use: "sub [flags]", Args: NoArgs, Run: emptyRun}
rootCmd.AddCommand(subCmd)
rootHelp, err := executeCommand(rootCmd, "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, rootHelp, "kubectl plugin [command]")
checkStringContains(t, rootHelp, "help for kubectl plugin")
checkStringContains(t, rootHelp, "kubectl plugin [command] --help")
childHelp, err := executeCommand(rootCmd, "sub", "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, childHelp, "kubectl plugin sub [flags]")
checkStringContains(t, childHelp, "help for sub")
helpHelp, err := executeCommand(rootCmd, "help", "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, helpHelp, "kubectl plugin help [path to command]")
checkStringContains(t, helpHelp, "kubectl plugin help [command]")
}
// TestChildSameName checks the correct behaviour of cobra in cases,
// when an application with name "foo" and with subcommand "foo"
// is executed with args "foo foo".
@ -438,7 +499,7 @@ func TestFlagLong(t *testing.T) {
output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")
if output != "" {
t.Errorf("Unexpected output: %v", err)
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
@ -475,7 +536,7 @@ func TestFlagShort(t *testing.T) {
output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", err)
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
@ -504,7 +565,7 @@ func TestChildFlag(t *testing.T) {
output, err := executeCommand(rootCmd, "child", "-i7")
if output != "" {
t.Errorf("Unexpected output: %v", err)
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
@ -1099,6 +1160,39 @@ func TestShorthandVersionTemplate(t *testing.T) {
checkStringContains(t, output, "customized version: 1.0.0")
}
func TestRootErrPrefixExecutedOnSubcommand(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.SetErrPrefix("root error prefix:")
rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})
output, err := executeCommand(rootCmd, "sub", "--unknown-flag")
if err == nil {
t.Errorf("Expected error")
}
checkStringContains(t, output, "root error prefix: unknown flag: --unknown-flag")
}
func TestRootAndSubErrPrefix(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
subCmd := &Command{Use: "sub", Run: emptyRun}
rootCmd.AddCommand(subCmd)
rootCmd.SetErrPrefix("root error prefix:")
subCmd.SetErrPrefix("sub error prefix:")
if output, err := executeCommand(rootCmd, "--unknown-root-flag"); err == nil {
t.Errorf("Expected error")
} else {
checkStringContains(t, output, "root error prefix: unknown flag: --unknown-root-flag")
}
if output, err := executeCommand(rootCmd, "sub", "--unknown-sub-flag"); err == nil {
t.Errorf("Expected error")
} else {
checkStringContains(t, output, "sub error prefix: unknown flag: --unknown-sub-flag")
}
}
func TestVersionFlagExecutedOnSubcommand(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0"}
rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})
@ -1497,57 +1591,73 @@ func TestHooks(t *testing.T) {
}
func TestPersistentHooks(t *testing.T) {
var (
parentPersPreArgs string
parentPreArgs string
parentRunArgs string
parentPostArgs string
parentPersPostArgs string
)
EnableTraverseRunHooks = true
testPersistentHooks(t, []string{
"parent PersistentPreRun",
"child PersistentPreRun",
"child PreRun",
"child Run",
"child PostRun",
"child PersistentPostRun",
"parent PersistentPostRun",
})
var (
childPersPreArgs string
childPreArgs string
childRunArgs string
childPostArgs string
childPersPostArgs string
)
EnableTraverseRunHooks = false
testPersistentHooks(t, []string{
"child PersistentPreRun",
"child PreRun",
"child Run",
"child PostRun",
"child PersistentPostRun",
})
}
func testPersistentHooks(t *testing.T, expectedHookRunOrder []string) {
var hookRunOrder []string
validateHook := func(args []string, hookName string) {
hookRunOrder = append(hookRunOrder, hookName)
got := strings.Join(args, " ")
if onetwo != got {
t.Errorf("Expected %s %q, got %q", hookName, onetwo, got)
}
}
parentCmd := &Command{
Use: "parent",
PersistentPreRun: func(_ *Command, args []string) {
parentPersPreArgs = strings.Join(args, " ")
validateHook(args, "parent PersistentPreRun")
},
PreRun: func(_ *Command, args []string) {
parentPreArgs = strings.Join(args, " ")
validateHook(args, "parent PreRun")
},
Run: func(_ *Command, args []string) {
parentRunArgs = strings.Join(args, " ")
validateHook(args, "parent Run")
},
PostRun: func(_ *Command, args []string) {
parentPostArgs = strings.Join(args, " ")
validateHook(args, "parent PostRun")
},
PersistentPostRun: func(_ *Command, args []string) {
parentPersPostArgs = strings.Join(args, " ")
validateHook(args, "parent PersistentPostRun")
},
}
childCmd := &Command{
Use: "child",
PersistentPreRun: func(_ *Command, args []string) {
childPersPreArgs = strings.Join(args, " ")
validateHook(args, "child PersistentPreRun")
},
PreRun: func(_ *Command, args []string) {
childPreArgs = strings.Join(args, " ")
validateHook(args, "child PreRun")
},
Run: func(_ *Command, args []string) {
childRunArgs = strings.Join(args, " ")
validateHook(args, "child Run")
},
PostRun: func(_ *Command, args []string) {
childPostArgs = strings.Join(args, " ")
validateHook(args, "child PostRun")
},
PersistentPostRun: func(_ *Command, args []string) {
childPersPostArgs = strings.Join(args, " ")
validateHook(args, "child PersistentPostRun")
},
}
parentCmd.AddCommand(childCmd)
@ -1560,41 +1670,13 @@ func TestPersistentHooks(t *testing.T) {
t.Errorf("Unexpected error: %v", err)
}
for _, v := range []struct {
name string
got string
}{
// TODO: currently PersistentPreRun* defined in parent does not
// run if the matching child subcommand has PersistentPreRun.
// If the behavior changes (https://github.com/spf13/cobra/issues/252)
// this test must be fixed.
{"parentPersPreArgs", parentPersPreArgs},
{"parentPreArgs", parentPreArgs},
{"parentRunArgs", parentRunArgs},
{"parentPostArgs", parentPostArgs},
// TODO: currently PersistentPostRun* defined in parent does not
// run if the matching child subcommand has PersistentPostRun.
// If the behavior changes (https://github.com/spf13/cobra/issues/252)
// this test must be fixed.
{"parentPersPostArgs", parentPersPostArgs},
} {
if v.got != "" {
t.Errorf("Expected blank %s, got %q", v.name, v.got)
}
}
for _, v := range []struct {
name string
got string
}{
{"childPersPreArgs", childPersPreArgs},
{"childPreArgs", childPreArgs},
{"childRunArgs", childRunArgs},
{"childPostArgs", childPostArgs},
{"childPersPostArgs", childPersPostArgs},
} {
if v.got != onetwo {
t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)
for idx, exp := range expectedHookRunOrder {
if len(hookRunOrder) > idx {
if act := hookRunOrder[idx]; act != exp {
t.Errorf("Expected %q at %d, got %q", exp, idx, act)
}
} else {
t.Errorf("Expected %q at %d, got nothing", exp, idx)
}
}
}
@ -1862,6 +1944,84 @@ func TestAddGroup(t *testing.T) {
checkStringContains(t, output, "\nTest group\n cmd")
}
func TestWrongGroupFirstLevel(t *testing.T) {
var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}
rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"})
// Use the wrong group ID
rootCmd.AddCommand(&Command{Use: "cmd", GroupID: "wrong", Run: emptyRun})
defer func() {
if recover() == nil {
t.Errorf("The code should have panicked due to a missing group")
}
}()
_, err := executeCommand(rootCmd, "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestWrongGroupNestedLevel(t *testing.T) {
var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}
var childCmd = &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
childCmd.AddGroup(&Group{ID: "group", Title: "Test group"})
// Use the wrong group ID
childCmd.AddCommand(&Command{Use: "cmd", GroupID: "wrong", Run: emptyRun})
defer func() {
if recover() == nil {
t.Errorf("The code should have panicked due to a missing group")
}
}()
_, err := executeCommand(rootCmd, "child", "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestWrongGroupForHelp(t *testing.T) {
var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}
var childCmd = &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"})
// Use the wrong group ID
rootCmd.SetHelpCommandGroupID("wrong")
defer func() {
if recover() == nil {
t.Errorf("The code should have panicked due to a missing group")
}
}()
_, err := executeCommand(rootCmd, "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestWrongGroupForCompletion(t *testing.T) {
var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}
var childCmd = &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"})
// Use the wrong group ID
rootCmd.SetCompletionCommandGroupID("wrong")
defer func() {
if recover() == nil {
t.Errorf("The code should have panicked due to a missing group")
}
}()
_, err := executeCommand(rootCmd, "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestSetOutput(t *testing.T) {
c := &Command{}
c.SetOutput(nil)
@ -1932,12 +2092,12 @@ func TestCommandPrintRedirection(t *testing.T) {
t.Error(err)
}
gotErrBytes, err := ioutil.ReadAll(errBuff)
gotErrBytes, err := io.ReadAll(errBuff)
if err != nil {
t.Error(err)
}
gotOutBytes, err := ioutil.ReadAll(outBuff)
gotOutBytes, err := io.ReadAll(outBuff)
if err != nil {
t.Error(err)
}
@ -2525,3 +2685,135 @@ func TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) {
checkStringContains(t, output, HelpFlag)
checkStringOmits(t, output, VersionFlag)
}
func TestFind(t *testing.T) {
var foo, bar string
root := &Command{
Use: "root",
}
root.PersistentFlags().StringVarP(&foo, "foo", "f", "", "")
root.PersistentFlags().StringVarP(&bar, "bar", "b", "something", "")
child := &Command{
Use: "child",
}
root.AddCommand(child)
testCases := []struct {
args []string
expectedFoundArgs []string
}{
{
[]string{"child"},
[]string{},
},
{
[]string{"child", "child"},
[]string{"child"},
},
{
[]string{"child", "foo", "child", "bar", "child", "baz", "child"},
[]string{"foo", "child", "bar", "child", "baz", "child"},
},
{
[]string{"-f", "child", "child"},
[]string{"-f", "child"},
},
{
[]string{"child", "-f", "child"},
[]string{"-f", "child"},
},
{
[]string{"-b", "child", "child"},
[]string{"-b", "child"},
},
{
[]string{"child", "-b", "child"},
[]string{"-b", "child"},
},
{
[]string{"child", "-b"},
[]string{"-b"},
},
{
[]string{"-b", "-f", "child", "child"},
[]string{"-b", "-f", "child"},
},
{
[]string{"-f", "child", "-b", "something", "child"},
[]string{"-f", "child", "-b", "something"},
},
{
[]string{"-f", "child", "child", "-b"},
[]string{"-f", "child", "-b"},
},
{
[]string{"-f=child", "-b=something", "child"},
[]string{"-f=child", "-b=something"},
},
{
[]string{"--foo", "child", "--bar", "something", "child"},
[]string{"--foo", "child", "--bar", "something"},
},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%v", tc.args), func(t *testing.T) {
cmd, foundArgs, err := root.Find(tc.args)
if err != nil {
t.Fatal(err)
}
if cmd != child {
t.Fatal("Expected cmd to be child, but it was not")
}
if !reflect.DeepEqual(tc.expectedFoundArgs, foundArgs) {
t.Fatalf("Wrong args\nExpected: %v\nGot: %v", tc.expectedFoundArgs, foundArgs)
}
})
}
}
func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {
testCases := [][]string{
// {"--unknown", "--namespace", "foo", "child", "--bar"}, // FIXME: This test case fails, returning the error `unknown command "foo" for "root"` instead of the expected error `unknown flag: --unknown`
{"--namespace", "foo", "--unknown", "child", "--bar"},
{"--namespace", "foo", "child", "--unknown", "--bar"},
{"--namespace", "foo", "child", "--bar", "--unknown"},
{"--unknown", "--namespace=foo", "child", "--bar"},
{"--namespace=foo", "--unknown", "child", "--bar"},
{"--namespace=foo", "child", "--unknown", "--bar"},
{"--namespace=foo", "child", "--bar", "--unknown"},
{"--unknown", "--namespace=foo", "child", "--bar=true"},
{"--namespace=foo", "--unknown", "child", "--bar=true"},
{"--namespace=foo", "child", "--unknown", "--bar=true"},
{"--namespace=foo", "child", "--bar=true", "--unknown"},
}
root := &Command{
Use: "root",
Run: emptyRun,
}
root.PersistentFlags().String("namespace", "", "a string flag")
c := &Command{
Use: "child",
Run: emptyRun,
}
c.Flags().Bool("bar", false, "a boolean flag")
root.AddCommand(c)
for _, tc := range testCases {
t.Run(strings.Join(tc, " "), func(t *testing.T) {
output, err := executeCommand(root, tc...)
if err == nil {
t.Error("expected unknown flag error")
}
checkStringContains(t, output, "unknown flag: --unknown")
})
}
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -17,6 +17,8 @@ package cobra
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sync"
@ -77,6 +79,10 @@ const (
// obtain the same behavior but only for flags.
ShellCompDirectiveFilterDirs
// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
// in which the completions are provided
ShellCompDirectiveKeepOrder
// ===========================================================================
// All directives using iota should be above this one.
@ -141,6 +147,20 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman
return nil
}
// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.
func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) {
flag := c.Flag(flagName)
if flag == nil {
return nil, false
}
flagCompletionMutex.RLock()
defer flagCompletionMutex.RUnlock()
completionFunc, exists := flagCompletionFunctions[flag]
return completionFunc, exists
}
// Returns a string listing the different directive enabled in the specified parameter
func (d ShellCompDirective) string() string {
var directives []string
@ -159,6 +179,9 @@ func (d ShellCompDirective) string() string {
if d&ShellCompDirectiveFilterDirs != 0 {
directives = append(directives, "ShellCompDirectiveFilterDirs")
}
if d&ShellCompDirectiveKeepOrder != 0 {
directives = append(directives, "ShellCompDirectiveKeepOrder")
}
if len(directives) == 0 {
directives = append(directives, "ShellCompDirectiveDefault")
}
@ -169,7 +192,7 @@ func (d ShellCompDirective) string() string {
return strings.Join(directives, ", ")
}
// Adds a special hidden command that can be used to request custom completions.
// initCompleteCmd adds a special hidden command that can be used to request custom completions.
func (c *Command) initCompleteCmd(args []string) {
completeCmd := &Command{
Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
@ -190,24 +213,29 @@ func (c *Command) initCompleteCmd(args []string) {
// 2- Even without completions, we need to print the directive
}
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd
if !noDescriptions {
if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {
noDescriptions = !doDescriptions
}
}
noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable
out := finalCmd.OutOrStdout()
for _, comp := range completions {
if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
// Remove all activeHelp entries in this case
if strings.HasPrefix(comp, activeHelpMarker) {
continue
}
if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {
// Remove all activeHelp entries if it's disabled.
continue
}
if noDescriptions {
// Remove any description that may be included following a tab character.
comp = strings.Split(comp, "\t")[0]
comp = strings.SplitN(comp, "\t", 2)[0]
}
// Make sure we only write the first line to the output.
// This is needed if a description contains a linebreak.
// Otherwise the shell scripts will interpret the other lines as new flags
// and could therefore provide a wrong completion.
comp = strings.Split(comp, "\n")[0]
comp = strings.SplitN(comp, "\n", 2)[0]
// Finally trim the completion. This is especially important to get rid
// of a trailing tab when there are no description following it.
@ -216,14 +244,14 @@ func (c *Command) initCompleteCmd(args []string) {
// although there is no description).
comp = strings.TrimSpace(comp)
// Print each possible completion to stdout for the completion script to consume.
fmt.Fprintln(finalCmd.OutOrStdout(), comp)
// Print each possible completion to the output for the completion script to consume.
fmt.Fprintln(out, comp)
}
// As the last printout, print the completion directive for the completion script to parse.
// The directive integer must be that last character following a single colon (:).
// The completion script expects :<directive>
fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
fmt.Fprintf(out, ":%d\n", directive)
// Print some helpful info to stderr for the user to understand.
// Output from stderr must be ignored by the completion script.
@ -270,15 +298,19 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
}
if err != nil {
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)
}
finalCmd.ctx = c.ctx
// These flags are normally added when `execute()` is called on `finalCmd`,
// however, when doing completion, we don't call `finalCmd.execute()`.
// Let's add the --help and --version flag ourselves.
finalCmd.InitDefaultHelpFlag()
finalCmd.InitDefaultVersionFlag()
// Let's add the --help and --version flag ourselves but only if the finalCmd
// has not disabled flag parsing; if flag parsing is disabled, it is up to the
// finalCmd itself to handle the completion of *all* flags.
if !finalCmd.DisableFlagParsing {
finalCmd.InitDefaultHelpFlag()
finalCmd.InitDefaultVersionFlag()
}
// Check if we are doing flag value completion before parsing the flags.
// This is important because if we are completing a flag value, we need to also
@ -382,6 +414,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
doCompleteFlags(flag)
})
// Try to complete non-inherited flags even if DisableFlagParsing==true.
// This allows programs to tell Cobra about flags for completion even
// if the actual parsing of flags is not done by Cobra.
// For instance, Helm uses this to provide flag name completion for
// some of its plugins.
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
doCompleteFlags(flag)
})
@ -727,7 +764,7 @@ to enable it. You can execute the following once:
To load completions in your current shell session:
source <(%[1]s completion zsh); compdef _%[1]s %[1]s
source <(%[1]s completion zsh)
To load completions for every new session, execute once:
@ -869,3 +906,34 @@ func CompError(msg string) {
func CompErrorln(msg string) {
CompError(fmt.Sprintf("%s\n", msg))
}
// These values should not be changed: users will be using them explicitly.
const (
configEnvVarGlobalPrefix = "COBRA"
configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"
)
var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
// configEnvVar returns the name of the program-specific configuration environment
// variable. It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
func configEnvVar(name, suffix string) string {
// This format should not be changed: users will be using it explicitly.
v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))
v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")
return v
}
// getEnvConfig returns the value of the configuration environment variable
// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
// If the value is empty or not set, the value of the environment variable
// COBRA_<SUFFIX> is returned instead.
func getEnvConfig(cmd *Command, suffix string) string {
v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))
if v == "" {
v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))
}
return v
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -17,7 +17,10 @@ package cobra
import (
"bytes"
"context"
"fmt"
"os"
"strings"
"sync"
"testing"
)
@ -2040,6 +2043,114 @@ func TestFlagCompletionWorksRootCommandAddedAfterFlags(t *testing.T) {
}
}
func TestFlagCompletionForPersistentFlagsCalledFromSubCmd(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.PersistentFlags().String("string", "", "test string flag")
_ = rootCmd.RegisterFlagCompletionFunc("string", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"myval"}, ShellCompDirectiveDefault
})
childCmd := &Command{
Use: "child",
Run: emptyRun,
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"--validarg", "test"}, ShellCompDirectiveDefault
},
}
childCmd.Flags().Bool("bool", false, "test bool flag")
rootCmd.AddCommand(childCmd)
// Test that persistent flag completion works for the subcmd
output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "--string", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
"myval",
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
// This test tries to register flag completion concurrently to make sure the
// code handles concurrency properly.
// This was reported as a problem when tests are run concurrently:
// https://github.com/spf13/cobra/issues/1320
//
// NOTE: this test can sometimes pass even if the code were to not handle
// concurrency properly. This is not great but the important part is that
// it should never fail. Therefore, if the tests fails sometimes, we will
// still be able to know there is a problem.
func TestFlagCompletionConcurrentRegistration(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
const maxFlags = 50
for i := 1; i < maxFlags; i += 2 {
flagName := fmt.Sprintf("flag%d", i)
rootCmd.Flags().String(flagName, "", fmt.Sprintf("test %s flag on root", flagName))
}
childCmd := &Command{
Use: "child",
Run: emptyRun,
}
for i := 2; i <= maxFlags; i += 2 {
flagName := fmt.Sprintf("flag%d", i)
childCmd.Flags().String(flagName, "", fmt.Sprintf("test %s flag on child", flagName))
}
rootCmd.AddCommand(childCmd)
// Register completion in different threads to test concurrency.
var wg sync.WaitGroup
for i := 1; i <= maxFlags; i++ {
index := i
flagName := fmt.Sprintf("flag%d", i)
wg.Add(1)
go func() {
defer wg.Done()
cmd := rootCmd
if index%2 == 0 {
cmd = childCmd
}
_ = cmd.RegisterFlagCompletionFunc(flagName, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{fmt.Sprintf("flag%d", index)}, ShellCompDirectiveDefault
})
}()
}
wg.Wait()
// Test that flag completion works for each flag
for i := 1; i <= 6; i++ {
var output string
var err error
flagName := fmt.Sprintf("flag%d", i)
if i%2 == 1 {
output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--"+flagName, "")
} else {
output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--"+flagName, "")
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
flagName,
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
}
func TestFlagCompletionInGoWithDesc(t *testing.T) {
rootCmd := &Command{
Use: "root",
@ -2622,8 +2733,6 @@ func TestCompleteWithDisableFlagParsing(t *testing.T) {
expected := strings.Join([]string{
"--persistent",
"-p",
"--help",
"-h",
"--nonPersistent",
"-n",
"--flag",
@ -2830,6 +2939,104 @@ func TestCompletionForGroupedFlags(t *testing.T) {
}
}
func TestCompletionForOneRequiredGroupFlags(t *testing.T) {
getCmd := func() *Command {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "child",
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"subArg"}, ShellCompDirectiveNoFileComp
},
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
rootCmd.PersistentFlags().Int("ingroup1", -1, "ingroup1")
rootCmd.PersistentFlags().String("ingroup2", "", "ingroup2")
childCmd.Flags().Bool("ingroup3", false, "ingroup3")
childCmd.Flags().Bool("nogroup", false, "nogroup")
// Add flags to a group
childCmd.MarkFlagsOneRequired("ingroup1", "ingroup2", "ingroup3")
return rootCmd
}
// Each test case uses a unique command from the function above.
testcases := []struct {
desc string
args []string
expectedOutput string
}{
{
desc: "flags in group suggested without - prefix",
args: []string{"child", ""},
expectedOutput: strings.Join([]string{
"--ingroup1",
"--ingroup2",
"--ingroup3",
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "flags in group suggested with - prefix",
args: []string{"child", "-"},
expectedOutput: strings.Join([]string{
"--ingroup1",
"--ingroup2",
"--ingroup3",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "when any flag in group present, other flags in group not suggested without - prefix",
args: []string{"child", "--ingroup2", "value", ""},
expectedOutput: strings.Join([]string{
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "when all flags in group present, flags not suggested without - prefix",
args: []string{"child", "--ingroup1", "8", "--ingroup2", "value2", "--ingroup3", ""},
expectedOutput: strings.Join([]string{
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "group ignored if some flags not applicable",
args: []string{"--ingroup2", "value", ""},
expectedOutput: strings.Join([]string{
"child",
"completion",
"help",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
}
for _, tc := range testcases {
t.Run(tc.desc, func(t *testing.T) {
c := getCmd()
args := []string{ShellCompNoDescRequestCmd}
args = append(args, tc.args...)
output, err := executeCommand(c, args...)
switch {
case err == nil && output != tc.expectedOutput:
t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)
case err != nil:
t.Errorf("Unexpected error %q", err)
}
})
}
}
func TestCompletionForMutuallyExclusiveFlags(t *testing.T) {
getCmd := func() *Command {
rootCmd := &Command{
@ -2955,8 +3162,26 @@ func TestCompletionCobraFlags(t *testing.T) {
return []string{"extra3"}, ShellCompDirectiveNoFileComp
},
}
childCmd4 := &Command{
Use: "child4",
Version: "1.1.1",
Run: emptyRun,
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"extra4"}, ShellCompDirectiveNoFileComp
},
DisableFlagParsing: true,
}
childCmd5 := &Command{
Use: "child5",
Version: "1.1.1",
Run: emptyRun,
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"extra5"}, ShellCompDirectiveNoFileComp
},
DisableFlagParsing: true,
}
rootCmd.AddCommand(childCmd, childCmd2, childCmd3)
rootCmd.AddCommand(childCmd, childCmd2, childCmd3, childCmd4, childCmd5)
_ = childCmd.Flags().Bool("bool", false, "A bool flag")
_ = childCmd.MarkFlagRequired("bool")
@ -2968,6 +3193,10 @@ func TestCompletionCobraFlags(t *testing.T) {
// Have a command that only adds its own -v flag
_ = childCmd3.Flags().BoolP("verbose", "v", false, "Not a version flag")
// Have a command that DisablesFlagParsing but that also adds its own help and version flags
_ = childCmd5.Flags().BoolP("help", "h", false, "My own help")
_ = childCmd5.Flags().BoolP("version", "v", false, "My own version")
return rootCmd
}
@ -3098,6 +3327,26 @@ func TestCompletionCobraFlags(t *testing.T) {
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "no completion for --help/-h and --version/-v flags when DisableFlagParsing=true",
args: []string{"child4", "-"},
expectedOutput: strings.Join([]string{
"extra4",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "completions for program-defined --help/-h and --version/-v flags even when DisableFlagParsing=true",
args: []string{"child5", "-"},
expectedOutput: strings.Join([]string{
"--help",
"-h",
"--version",
"-v",
"extra5",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
}
for _, tc := range testcases {
@ -3115,3 +3364,348 @@ func TestCompletionCobraFlags(t *testing.T) {
})
}
}
func TestArgsNotDetectedAsFlagsCompletionInGo(t *testing.T) {
// Regression test that ensures the bug described in
// https://github.com/spf13/cobra/issues/1816 does not occur anymore.
root := Command{
Use: "root",
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"service", "1-123", "11-123"}, ShellCompDirectiveNoFileComp
},
}
completion := `service
1-123
11-123
:4
Completion ended with directive: ShellCompDirectiveNoFileComp
`
testcases := []struct {
desc string
args []string
expectedOutput string
}{
{
desc: "empty",
args: []string{""},
expectedOutput: completion,
},
{
desc: "service only",
args: []string{"service", ""},
expectedOutput: completion,
},
{
desc: "service last",
args: []string{"1-123", "service", ""},
expectedOutput: completion,
},
{
desc: "two digit prefixed dash last",
args: []string{"service", "11-123", ""},
expectedOutput: completion,
},
{
desc: "one digit prefixed dash last",
args: []string{"service", "1-123", ""},
expectedOutput: completion,
},
}
for _, tc := range testcases {
t.Run(tc.desc, func(t *testing.T) {
args := []string{ShellCompNoDescRequestCmd}
args = append(args, tc.args...)
output, err := executeCommand(&root, args...)
switch {
case err == nil && output != tc.expectedOutput:
t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)
case err != nil:
t.Errorf("Unexpected error %q", err)
}
})
}
}
func TestGetFlagCompletion(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.Flags().String("rootflag", "", "root flag")
_ = rootCmd.RegisterFlagCompletionFunc("rootflag", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"rootvalue"}, ShellCompDirectiveKeepOrder
})
rootCmd.PersistentFlags().String("persistentflag", "", "persistent flag")
_ = rootCmd.RegisterFlagCompletionFunc("persistentflag", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"persistentvalue"}, ShellCompDirectiveDefault
})
childCmd := &Command{Use: "child", Run: emptyRun}
childCmd.Flags().String("childflag", "", "child flag")
_ = childCmd.RegisterFlagCompletionFunc("childflag", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"childvalue"}, ShellCompDirectiveNoFileComp | ShellCompDirectiveNoSpace
})
rootCmd.AddCommand(childCmd)
testcases := []struct {
desc string
cmd *Command
flagName string
exists bool
comps []string
directive ShellCompDirective
}{
{
desc: "get flag completion function for command",
cmd: rootCmd,
flagName: "rootflag",
exists: true,
comps: []string{"rootvalue"},
directive: ShellCompDirectiveKeepOrder,
},
{
desc: "get persistent flag completion function for command",
cmd: rootCmd,
flagName: "persistentflag",
exists: true,
comps: []string{"persistentvalue"},
directive: ShellCompDirectiveDefault,
},
{
desc: "get flag completion function for child command",
cmd: childCmd,
flagName: "childflag",
exists: true,
comps: []string{"childvalue"},
directive: ShellCompDirectiveNoFileComp | ShellCompDirectiveNoSpace,
},
{
desc: "get persistent flag completion function for child command",
cmd: childCmd,
flagName: "persistentflag",
exists: true,
comps: []string{"persistentvalue"},
directive: ShellCompDirectiveDefault,
},
{
desc: "cannot get flag completion function for local parent flag",
cmd: childCmd,
flagName: "rootflag",
exists: false,
},
}
for _, tc := range testcases {
t.Run(tc.desc, func(t *testing.T) {
compFunc, exists := tc.cmd.GetFlagCompletionFunc(tc.flagName)
if tc.exists != exists {
t.Errorf("Unexpected result looking for flag completion function")
}
if exists {
comps, directive := compFunc(tc.cmd, []string{}, "")
if strings.Join(tc.comps, " ") != strings.Join(comps, " ") {
t.Errorf("Unexpected completions %q", comps)
}
if tc.directive != directive {
t.Errorf("Unexpected directive %q", directive)
}
}
})
}
}
func TestGetEnvConfig(t *testing.T) {
testCases := []struct {
desc string
use string
suffix string
cmdVar string
globalVar string
cmdVal string
globalVal string
expected string
}{
{
desc: "Command envvar overrides global",
use: "root",
suffix: "test",
cmdVar: "ROOT_TEST",
globalVar: "COBRA_TEST",
cmdVal: "cmd",
globalVal: "global",
expected: "cmd",
},
{
desc: "Missing/empty command envvar falls back to global",
use: "root",
suffix: "test",
cmdVar: "ROOT_TEST",
globalVar: "COBRA_TEST",
cmdVal: "",
globalVal: "global",
expected: "global",
},
{
desc: "Missing/empty command and global envvars fall back to empty",
use: "root",
suffix: "test",
cmdVar: "ROOT_TEST",
globalVar: "COBRA_TEST",
cmdVal: "",
globalVal: "",
expected: "",
},
{
desc: "Periods in command use transform to underscores in env var name",
use: "foo.bar",
suffix: "test",
cmdVar: "FOO_BAR_TEST",
globalVar: "COBRA_TEST",
cmdVal: "cmd",
globalVal: "global",
expected: "cmd",
},
{
desc: "Dashes in command use transform to underscores in env var name",
use: "quux-BAZ",
suffix: "test",
cmdVar: "QUUX_BAZ_TEST",
globalVar: "COBRA_TEST",
cmdVal: "cmd",
globalVal: "global",
expected: "cmd",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Could make env handling cleaner with t.Setenv with Go >= 1.17
err := os.Setenv(tc.cmdVar, tc.cmdVal)
defer func() {
assertNoErr(t, os.Unsetenv(tc.cmdVar))
}()
assertNoErr(t, err)
err = os.Setenv(tc.globalVar, tc.globalVal)
defer func() {
assertNoErr(t, os.Unsetenv(tc.globalVar))
}()
assertNoErr(t, err)
cmd := &Command{Use: tc.use}
got := getEnvConfig(cmd, tc.suffix)
if got != tc.expected {
t.Errorf("expected: %q, got: %q", tc.expected, got)
}
})
}
}
func TestDisableDescriptions(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "thechild",
Short: "The child command",
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
specificDescriptionsEnvVar := configEnvVar(rootCmd.Name(), configEnvVarSuffixDescriptions)
globalDescriptionsEnvVar := configEnvVar(configEnvVarGlobalPrefix, configEnvVarSuffixDescriptions)
const (
descLineWithDescription = "first\tdescription"
descLineWithoutDescription = "first"
)
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := []string{descLineWithDescription}
return comps, ShellCompDirectiveDefault
}
testCases := []struct {
desc string
globalEnvValue string
specificEnvValue string
expectedLine string
}{
{
"No env variables set",
"",
"",
descLineWithDescription,
},
{
"Global value false",
"false",
"",
descLineWithoutDescription,
},
{
"Specific value false",
"",
"false",
descLineWithoutDescription,
},
{
"Both values false",
"false",
"false",
descLineWithoutDescription,
},
{
"Both values true",
"true",
"true",
descLineWithDescription,
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
if err := os.Setenv(specificDescriptionsEnvVar, tc.specificEnvValue); err != nil {
t.Errorf("Unexpected error setting %s: %v", specificDescriptionsEnvVar, err)
}
if err := os.Setenv(globalDescriptionsEnvVar, tc.globalEnvValue); err != nil {
t.Errorf("Unexpected error setting %s: %v", globalDescriptionsEnvVar, err)
}
var run = func() {
output, err := executeCommand(rootCmd, ShellCompRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
tc.expectedLine,
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
run()
// For empty cases, test also unset state
if tc.specificEnvValue == "" {
if err := os.Unsetenv(specificDescriptionsEnvVar); err != nil {
t.Errorf("Unexpected error unsetting %s: %v", specificDescriptionsEnvVar, err)
}
run()
}
if tc.globalEnvValue == "" {
if err := os.Unsetenv(globalDescriptionsEnvVar); err != nil {
t.Errorf("Unexpected error unsetting %s: %v", globalDescriptionsEnvVar, err)
}
run()
}
})
}
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -133,7 +133,7 @@ func fillHeader(header *GenManHeader, name string, disableAutoGen bool) error {
}
header.Date = &now
}
header.date = (*header.Date).Format("Jan 2006")
header.date = header.Date.Format("Jan 2006")
if header.Source == "" && !disableAutoGen {
header.Source = "Auto generated by spf13/cobra"
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -150,7 +150,7 @@ func TestGenManSeeAlso(t *testing.T) {
}
}
func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
c := &cobra.Command{}
c.Flags().StringP("foo", "f", "default", "Foo flag")
assertNoErr(t, c.Flags().MarkShorthandDeprecated("foo", "don't use it no more"))

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -27,6 +27,8 @@ import (
"github.com/spf13/cobra"
)
const markdownExtension = ".md"
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
flags := cmd.NonInheritedFlags()
flags.SetOutput(buf)
@ -83,7 +85,7 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string)
if cmd.HasParent() {
parent := cmd.Parent()
pname := parent.CommandPath()
link := pname + ".md"
link := pname + markdownExtension
link = strings.ReplaceAll(link, " ", "_")
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
cmd.VisitParents(func(c *cobra.Command) {
@ -101,7 +103,7 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string)
continue
}
cname := name + " " + child.Name()
link := cname + ".md"
link := cname + markdownExtension
link = strings.ReplaceAll(link, " ", "_")
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
}
@ -126,7 +128,7 @@ func GenMarkdownTree(cmd *cobra.Command, dir string) error {
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
}
// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
// GenMarkdownTreeCustom is the same as GenMarkdownTree, but
// with custom filePrepender and linkHandler.
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
for _, c := range cmd.Commands() {
@ -138,7 +140,7 @@ func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHa
}
}
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".md"
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + markdownExtension
filename := filepath.Join(dir, basename)
f, err := os.Create(filename)
if err != nil {

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -48,7 +48,7 @@ func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error
return nil
}
// linkHandler for default ReST hyperlink markup
// defaultLinkHandler for default ReST hyperlink markup
func defaultLinkHandler(name, ref string) string {
return fmt.Sprintf("`%s <%s.rst>`_", name, ref)
}
@ -140,7 +140,7 @@ func GenReSTTree(cmd *cobra.Command, dir string) error {
return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
}
// GenReSTTreeCustom is the the same as GenReSTTree, but
// GenReSTTreeCustom is the same as GenReSTTree, but
// with custom filePrepender and linkHandler.
func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
for _, c := range cmd.Commands() {
@ -169,7 +169,7 @@ func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string
return nil
}
// adapted from: https://github.com/kr/text/blob/main/indent.go
// indentString adapted from: https://github.com/kr/text/blob/main/indent.go
func indentString(s, p string) string {
var res []byte
b := []byte(s)

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -40,7 +40,7 @@ func hasSeeAlso(cmd *cobra.Command) bool {
// that do not contain \n.
func forceMultiLine(s string) string {
if len(s) > 60 && !strings.Contains(s, "\n") {
s = s + "\n"
s += "\n"
}
return s
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -53,7 +53,7 @@ function __%[1]s_perform_completion
__%[1]s_debug "last arg: $lastArg"
# Disable ActiveHelp which is not supported for fish shell
set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
__%[1]s_debug "Calling $requestComp"
set -l results (eval $requestComp 2> /dev/null)
@ -89,6 +89,60 @@ function __%[1]s_perform_completion
printf "%%s\n" "$directiveLine"
end
# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result
function __%[1]s_perform_completion_once
__%[1]s_debug "Starting __%[1]s_perform_completion_once"
if test -n "$__%[1]s_perform_completion_once_result"
__%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion"
return 0
end
set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion)
if test -z "$__%[1]s_perform_completion_once_result"
__%[1]s_debug "No completions, probably due to a failure"
return 1
end
__%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result"
return 0
end
# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run
function __%[1]s_clear_perform_completion_once_result
__%[1]s_debug ""
__%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable =========="
set --erase __%[1]s_perform_completion_once_result
__%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result"
end
function __%[1]s_requires_order_preservation
__%[1]s_debug ""
__%[1]s_debug "========= checking if order preservation is required =========="
__%[1]s_perform_completion_once
if test -z "$__%[1]s_perform_completion_once_result"
__%[1]s_debug "Error determining if order preservation is required"
return 1
end
set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])
__%[1]s_debug "Directive is: $directive"
set -l shellCompDirectiveKeepOrder %[9]d
set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2)
__%[1]s_debug "Keeporder is: $keeporder"
if test $keeporder -ne 0
__%[1]s_debug "This does require order preservation"
return 0
end
__%[1]s_debug "This doesn't require order preservation"
return 1
end
# This function does two things:
# - Obtain the completions and store them in the global __%[1]s_comp_results
# - Return false if file completion should be performed
@ -99,17 +153,17 @@ function __%[1]s_prepare_completions
# Start fresh
set --erase __%[1]s_comp_results
set -l results (__%[1]s_perform_completion)
__%[1]s_debug "Completion results: $results"
__%[1]s_perform_completion_once
__%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result"
if test -z "$results"
if test -z "$__%[1]s_perform_completion_once_result"
__%[1]s_debug "No completion, probably due to a failure"
# Might as well do file completion, in case it helps
return 1
end
set -l directive (string sub --start 2 $results[-1])
set --global __%[1]s_comp_results $results[1..-2]
set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])
set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2]
__%[1]s_debug "Completions are: $__%[1]s_comp_results"
__%[1]s_debug "Directive is: $directive"
@ -205,13 +259,17 @@ end
# Remove any pre-existing completions for the program since we will be handling all of them.
complete -c %[2]s -e
# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global
complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result'
# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results
# which provides the program's completion choices.
complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
# If this doesn't require order preservation, we don't use the -k flag
complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
# otherwise we use the -k flag
complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
`, nameForVar, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
}
// GenFishCompletion generates fish completion file and writes to the passed writer.

View file

@ -1,4 +0,0 @@
## Generating Fish Completions For Your cobra.Command
Please refer to [Shell Completions](shell_completions.md) for details.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -16,9 +16,10 @@ package cobra
import (
"bytes"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"testing"
)
@ -98,12 +99,12 @@ func TestFishCompletionNoActiveHelp(t *testing.T) {
}
func TestGenFishCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0755)
tmpFile, err := os.CreateTemp("", "cobra-test")
if err != nil {
log.Fatal(err.Error())
t.Fatal(err.Error())
}
defer os.RemoveAll("./tmp")
defer os.Remove(tmpFile.Name())
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child := &Command{
@ -113,18 +114,18 @@ func TestGenFishCompletionFile(t *testing.T) {
}
rootCmd.AddCommand(child)
assertNoErr(t, rootCmd.GenFishCompletionFile("./tmp/test", false))
assertNoErr(t, rootCmd.GenFishCompletionFile(tmpFile.Name(), false))
}
func TestFailGenFishCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0755)
tmpDir, err := os.MkdirTemp("", "cobra-test")
if err != nil {
log.Fatal(err.Error())
t.Fatal(err.Error())
}
defer os.RemoveAll("./tmp")
defer os.RemoveAll(tmpDir)
f, _ := os.OpenFile("./tmp/test", os.O_CREATE, 0400)
f, _ := os.OpenFile(filepath.Join(tmpDir, "test"), os.O_CREATE, 0400)
defer f.Close()
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
@ -135,18 +136,8 @@ func TestFailGenFishCompletionFile(t *testing.T) {
}
rootCmd.AddCommand(child)
got := rootCmd.GenFishCompletionFile("./tmp/test", false)
if got == nil {
t.Error("should raise permission denied error")
}
if os.Getenv("MSYSTEM") == "MINGW64" {
if got.Error() != "open ./tmp/test: Access is denied." {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: Access is denied.")
}
} else {
if got.Error() != "open ./tmp/test: permission denied" {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: permission denied")
}
got := rootCmd.GenFishCompletionFile(f.Name(), false)
if !errors.Is(got, os.ErrPermission) {
t.Errorf("got: %s, want: %s", got.Error(), os.ErrPermission.Error())
}
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -23,8 +23,9 @@ import (
)
const (
requiredAsGroup = "cobra_annotation_required_if_others_set"
mutuallyExclusive = "cobra_annotation_mutually_exclusive"
requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set"
oneRequiredAnnotation = "cobra_annotation_one_required"
mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive"
)
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
@ -36,7 +37,23 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
if f == nil {
panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))
}
if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil {
if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil {
// Only errs if the flag isn't found.
panic(err)
}
}
}
// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors
// if the command is invoked without at least one flag from the given set of flags.
func (c *Command) MarkFlagsOneRequired(flagNames ...string) {
c.mergePersistentFlags()
for _, v := range flagNames {
f := c.Flags().Lookup(v)
if f == nil {
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v))
}
if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil {
// Only errs if the flag isn't found.
panic(err)
}
@ -53,13 +70,13 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))
}
// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.
if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {
if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil {
panic(err)
}
}
}
// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the
// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the
// first error encountered.
func (c *Command) ValidateFlagGroups() error {
if c.DisableFlagParsing {
@ -71,15 +88,20 @@ func (c *Command) ValidateFlagGroups() error {
// groupStatus format is the list of flags as a unique ID,
// then a map of each flag name and whether it is set or not.
groupStatus := map[string]map[string]bool{}
oneRequiredGroupStatus := map[string]map[string]bool{}
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
flags.VisitAll(func(pflag *flag.Flag) {
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
})
if err := validateRequiredFlagGroups(groupStatus); err != nil {
return err
}
if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {
return err
}
if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
return err
}
@ -108,7 +130,7 @@ func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annota
continue
}
groupStatus[group] = map[string]bool{}
groupStatus[group] = make(map[string]bool, len(flagnames))
for _, name := range flagnames {
groupStatus[group][name] = false
}
@ -142,6 +164,27 @@ func validateRequiredFlagGroups(data map[string]map[string]bool) error {
return nil
}
func validateOneRequiredFlagGroups(data map[string]map[string]bool) error {
keys := sortedKeys(data)
for _, flagList := range keys {
flagnameAndStatus := data[flagList]
var set []string
for flagname, isSet := range flagnameAndStatus {
if isSet {
set = append(set, flagname)
}
}
if len(set) >= 1 {
continue
}
// Sort values, so they can be tested/scripted against consistently.
sort.Strings(set)
return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList)
}
return nil
}
func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
keys := sortedKeys(data)
for _, flagList := range keys {
@ -176,6 +219,7 @@ func sortedKeys(m map[string]map[string]bool) []string {
// enforceFlagGroupsForCompletion will do the following:
// - when a flag in a group is present, other flags in the group will be marked required
// - when none of the flags in a one-required group are present, all flags in the group will be marked required
// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
// This allows the standard completion logic to behave appropriately for flag groups
func (c *Command) enforceFlagGroupsForCompletion() {
@ -185,10 +229,12 @@ func (c *Command) enforceFlagGroupsForCompletion() {
flags := c.Flags()
groupStatus := map[string]map[string]bool{}
oneRequiredGroupStatus := map[string]map[string]bool{}
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
c.Flags().VisitAll(func(pflag *flag.Flag) {
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
})
// If a flag that is part of a group is present, we make all the other flags
@ -204,6 +250,26 @@ func (c *Command) enforceFlagGroupsForCompletion() {
}
}
// If none of the flags of a one-required group are present, we make all the flags
// of that group required so that the shell completion suggests them automatically
for flagList, flagnameAndStatus := range oneRequiredGroupStatus {
isSet := false
for _, isSet = range flagnameAndStatus {
if isSet {
break
}
}
// None of the flags of the group are set, mark all flags in the group
// as required
if !isSet {
for _, fName := range strings.Split(flagList, " ") {
_ = c.MarkFlagRequired(fName)
}
}
}
// If a flag that is mutually exclusive to others is present, we hide the other
// flags of that group so the shell completion does not suggest them
for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -43,13 +43,15 @@ func TestValidateFlagGroups(t *testing.T) {
// Each test case uses a unique command from the function above.
testcases := []struct {
desc string
flagGroupsRequired []string
flagGroupsExclusive []string
subCmdFlagGroupsRequired []string
subCmdFlagGroupsExclusive []string
args []string
expectErr string
desc string
flagGroupsRequired []string
flagGroupsOneRequired []string
flagGroupsExclusive []string
subCmdFlagGroupsRequired []string
subCmdFlagGroupsOneRequired []string
subCmdFlagGroupsExclusive []string
args []string
expectErr string
}{
{
desc: "No flags no problem",
@ -62,6 +64,11 @@ func TestValidateFlagGroups(t *testing.T) {
flagGroupsRequired: []string{"a b c"},
args: []string{"--a=foo"},
expectErr: "if any flags in the group [a b c] are set they must all be set; missing [b c]",
}, {
desc: "One-required flag group not satisfied",
flagGroupsOneRequired: []string{"a b"},
args: []string{"--c=foo"},
expectErr: "at least one of the flags in the group [a b] is required",
}, {
desc: "Exclusive flag group not satisfied",
flagGroupsExclusive: []string{"a b c"},
@ -72,6 +79,11 @@ func TestValidateFlagGroups(t *testing.T) {
flagGroupsRequired: []string{"a b c", "a d"},
args: []string{"--c=foo", "--d=foo"},
expectErr: `if any flags in the group [a b c] are set they must all be set; missing [a b]`,
}, {
desc: "Multiple one-required flag group not satisfied returns first error",
flagGroupsOneRequired: []string{"a b", "d e"},
args: []string{"--c=foo", "--f=foo"},
expectErr: `at least one of the flags in the group [a b] is required`,
}, {
desc: "Multiple exclusive flag group not satisfied returns first error",
flagGroupsExclusive: []string{"a b c", "a d"},
@ -82,32 +94,57 @@ func TestValidateFlagGroups(t *testing.T) {
flagGroupsRequired: []string{"a d", "a b", "a c"},
args: []string{"--a=foo"},
expectErr: `if any flags in the group [a b] are set they must all be set; missing [b]`,
}, {
desc: "Validation of one-required groups occurs on groups in sorted order",
flagGroupsOneRequired: []string{"d e", "a b", "f g"},
args: []string{"--c=foo"},
expectErr: `at least one of the flags in the group [a b] is required`,
}, {
desc: "Validation of exclusive groups occurs on groups in sorted order",
flagGroupsExclusive: []string{"a d", "a b", "a c"},
args: []string{"--a=foo", "--b=foo", "--c=foo"},
expectErr: `if any flags in the group [a b] are set none of the others can be; [a b] were all set`,
}, {
desc: "Persistent flags utilize both features and can fail required groups",
desc: "Persistent flags utilize required and exclusive groups and can fail required groups",
flagGroupsRequired: []string{"a e", "e f"},
flagGroupsExclusive: []string{"f g"},
args: []string{"--a=foo", "--f=foo", "--g=foo"},
expectErr: `if any flags in the group [a e] are set they must all be set; missing [e]`,
}, {
desc: "Persistent flags utilize both features and can fail mutually exclusive groups",
desc: "Persistent flags utilize one-required and exclusive groups and can fail one-required groups",
flagGroupsOneRequired: []string{"a b", "e f"},
flagGroupsExclusive: []string{"e f"},
args: []string{"--e=foo"},
expectErr: `at least one of the flags in the group [a b] is required`,
}, {
desc: "Persistent flags utilize required and exclusive groups and can fail mutually exclusive groups",
flagGroupsRequired: []string{"a e", "e f"},
flagGroupsExclusive: []string{"f g"},
args: []string{"--a=foo", "--e=foo", "--f=foo", "--g=foo"},
expectErr: `if any flags in the group [f g] are set none of the others can be; [f g] were all set`,
}, {
desc: "Persistent flags utilize both features and can pass",
desc: "Persistent flags utilize required and exclusive groups and can pass",
flagGroupsRequired: []string{"a e", "e f"},
flagGroupsExclusive: []string{"f g"},
args: []string{"--a=foo", "--e=foo", "--f=foo"},
}, {
desc: "Persistent flags utilize one-required and exclusive groups and can pass",
flagGroupsOneRequired: []string{"a e", "e f"},
flagGroupsExclusive: []string{"f g"},
args: []string{"--a=foo", "--e=foo", "--f=foo"},
}, {
desc: "Subcmds can use required groups using inherited flags",
subCmdFlagGroupsRequired: []string{"e subonly"},
args: []string{"subcmd", "--e=foo", "--subonly=foo"},
}, {
desc: "Subcmds can use one-required groups using inherited flags",
subCmdFlagGroupsOneRequired: []string{"e subonly"},
args: []string{"subcmd", "--e=foo", "--subonly=foo"},
}, {
desc: "Subcmds can use one-required groups using inherited flags and fail one-required groups",
subCmdFlagGroupsOneRequired: []string{"e subonly"},
args: []string{"subcmd"},
expectErr: "at least one of the flags in the group [e subonly] is required",
}, {
desc: "Subcmds can use exclusive groups using inherited flags",
subCmdFlagGroupsExclusive: []string{"e subonly"},
@ -130,12 +167,18 @@ func TestValidateFlagGroups(t *testing.T) {
for _, flagGroup := range tc.flagGroupsRequired {
c.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)
}
for _, flagGroup := range tc.flagGroupsOneRequired {
c.MarkFlagsOneRequired(strings.Split(flagGroup, " ")...)
}
for _, flagGroup := range tc.flagGroupsExclusive {
c.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)
}
for _, flagGroup := range tc.subCmdFlagGroupsRequired {
sub.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)
}
for _, flagGroup := range tc.subCmdFlagGroupsOneRequired {
sub.MarkFlagsOneRequired(strings.Split(flagGroup, " ")...)
}
for _, flagGroup := range tc.subCmdFlagGroupsExclusive {
sub.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)
}

4
go.mod
View file

@ -3,8 +3,8 @@ module github.com/spf13/cobra
go 1.15
require (
github.com/cpuguy83/go-md2man/v2 v2.0.2
github.com/inconshreveable/mousetrap v1.0.1
github.com/cpuguy83/go-md2man/v2 v2.0.4
github.com/inconshreveable/mousetrap v1.1.0
github.com/spf13/pflag v1.0.5
gopkg.in/yaml.v3 v3.0.1
)

8
go.sum
View file

@ -1,7 +1,7 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -28,8 +28,8 @@ import (
func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
// Variables should not contain a '-' or ':' character
nameForVar := name
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
nameForVar = strings.Replace(nameForVar, ":", "_", -1)
nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
compCmd := ShellCompRequestCmd
if !includeDesc {
@ -47,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
}
[scriptblock]$__%[2]sCompleterBlock = {
[scriptblock]${__%[2]sCompleterBlock} = {
param(
$WordToComplete,
$CommandAst,
@ -77,6 +77,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
$ShellCompDirectiveNoFileComp=%[6]d
$ShellCompDirectiveFilterFileExt=%[7]d
$ShellCompDirectiveFilterDirs=%[8]d
$ShellCompDirectiveKeepOrder=%[9]d
# Prepare the command to request completions for the program.
# Split the command at the first space to separate the program and arguments.
@ -106,13 +107,22 @@ filter __%[1]s_escapeStringWithSpecialChars {
# If the last parameter is complete (there is a space following it)
# We add an extra empty parameter so we can indicate this to the go method.
__%[1]s_debug "Adding extra empty parameter"
`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+`
`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
# PowerShell 7.2+ changed the way how the arguments are passed to executables,
# so for pre-7.2 or when Legacy argument passing is enabled we need to use
`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+`
if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
(($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
$PSNativeCommandArgumentPassing -eq 'Legacy')) {
`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
} else {
$RequestComp="$RequestComp" + ' ""'
}
}
__%[1]s_debug "Calling $RequestComp"
# First disable ActiveHelp which is not supported for Powershell
$env:%[9]s=0
${env:%[10]s}=0
#call the command store the output in $out and redirect stderr and stdout to null
# $Out is an array contains each line per element
@ -137,7 +147,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
}
$Longest = 0
$Values = $Out | ForEach-Object {
[Array]$Values = $Out | ForEach-Object {
#Split the output in name and description
`+" $Name, $Description = $_.Split(\"`t\",2)"+`
__%[1]s_debug "Name: $Name Description: $Description"
@ -182,6 +192,11 @@ filter __%[1]s_escapeStringWithSpecialChars {
}
}
# we sort the values in ascending order by name if keep order isn't passed
if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
$Values = $Values | Sort-Object -Property Name
}
if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
__%[1]s_debug "ShellCompDirectiveNoFileComp is called"
@ -264,10 +279,10 @@ filter __%[1]s_escapeStringWithSpecialChars {
}
}
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock}
`, name, nameForVar, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
}
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {

View file

@ -1,3 +0,0 @@
# Generating PowerShell Completions For Your Own cobra.Command
Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -29,5 +29,5 @@ func TestPwshCompletionNoActiveHelp(t *testing.T) {
// check that active help is being disabled
activeHelpVar := activeHelpEnvVar(c.Name())
check(t, output, fmt.Sprintf("%s=0", activeHelpVar))
check(t, output, fmt.Sprintf("${env:%s}=0", activeHelpVar))
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View file

@ -92,7 +92,7 @@ Allowing to configure Active Help is entirely optional; you can use Active Help
The way to configure Active Help is to use the program's Active Help environment
variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your
program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever
program in uppercase with any non-ASCII-alphanumeric characters replaced by an `_`. The variable should be set by the user to whatever
Active Help configuration values are supported by the program.
For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user
@ -140,7 +140,7 @@ details for your users.
Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details.
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any non-ASCII-alphanumeric characters are replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
```
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
bitnami/haproxy

View file

@ -71,7 +71,7 @@ PowerShell:
`,cmd.Root().Name()),
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.ExactValidArgs(1),
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
@ -162,16 +162,7 @@ cmd := &cobra.Command{
}
```
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
the completion algorithm if entered manually, e.g. in:
```bash
$ kubectl get rc [tab][tab]
backend frontend database
```
Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of
replication controllers following `rc`.
The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.
### Dynamic completion of nouns
@ -237,6 +228,10 @@ ShellCompDirectiveFilterFileExt
// return []string{"themes"}, ShellCompDirectiveFilterDirs
//
ShellCompDirectiveFilterDirs
// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
// in which the completions are provided
ShellCompDirectiveKeepOrder
```
***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
@ -385,6 +380,22 @@ or
```go
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
```
If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:
```bash
$ source <(helm completion bash)
$ helm completion [tab][tab]
bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell)
fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh)
$ source <(helm completion bash --no-descriptions)
$ helm completion [tab][tab]
bash fish powershell zsh
```
Setting the `<PROGRAM>_COMPLETION_DESCRIPTIONS` environment variable (falling back to `COBRA_COMPLETION_DESCRIPTIONS` if empty or not set) to a [falsey value](https://pkg.go.dev/strconv#ParseBool) achieves the same. `<PROGRAM>` is the name of your program with all non-ASCII-alphanumeric characters replaced by `_`.
## Bash completions
### Dependencies
@ -408,7 +419,7 @@ completion firstcommand secondcommand
### Bash legacy dynamic completions
For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
Please refer to [Bash Completions](bash_completions.md) for details.
Please refer to [Bash Completions](bash.md) for details.
### Bash completion V2
@ -417,13 +428,13 @@ Cobra provides two versions for bash completion. The original bash completion (
A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or
`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion
(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion
(see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion
solution described in this document.
Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash
completion V2 solution which provides the following extra features:
- Supports completion descriptions (like the other shells)
- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)
- Streamlined user experience thanks to a completion behavior aligned with the other shells
- Streamlined user experience thanks to a completion behavior aligned with the other shells
`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`
you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra
@ -440,7 +451,7 @@ show (show information of a chart)
$ helm s[tab][tab]
search show status
```
**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
## Zsh completions
Cobra supports native zsh completion generated from the root `cobra.Command`.
@ -474,7 +485,7 @@ search show status
### Zsh completions standardization
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
Please refer to [Zsh Completions](zsh_completions.md) for details.
Please refer to [Zsh Completions](zsh.md) for details.
## fish completions
@ -527,7 +538,7 @@ search (search for a keyword in charts) show (show information of a chart) s
# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
$ helm s[tab]
search show status
search show status
search for a keyword in charts

View file

@ -1,6 +1,6 @@
# Generating Bash Completions For Your cobra.Command
Please refer to [Shell Completions](shell_completions.md) for details.
Please refer to [Shell Completions](_index.md) for details.
## Bash legacy dynamic completions

View file

@ -0,0 +1,4 @@
## Generating Fish Completions For Your cobra.Command
Please refer to [Shell Completions](_index.md) for details.

View file

@ -0,0 +1,3 @@
# Generating PowerShell Completions For Your Own cobra.Command
Please refer to [Shell Completions](_index.md#powershell-completions) for details.

View file

@ -1,6 +1,6 @@
## Generating Zsh Completion For Your cobra.Command
Please refer to [Shell Completions](shell_completions.md) for details.
Please refer to [Shell Completions](_index.md) for details.
## Zsh completions standardization

View file

@ -1,9 +1,9 @@
# Documentation generation
- [Man page docs](./man_docs.md)
- [Markdown docs](./md_docs.md)
- [Rest docs](./rest_docs.md)
- [Yaml docs](./yaml_docs.md)
- [Man page docs](man.md)
- [Markdown docs](md.md)
- [Rest docs](rest.md)
- [Yaml docs](yaml.md)
## Options
### `DisableAutoGenTag`

View file

@ -1,15 +1,18 @@
## Projects using Cobra
- [Allero](https://github.com/allero-io/allero)
- [Arewefastyet](https://benchmark.vitess.io)
- [Arduino CLI](https://github.com/arduino/arduino-cli)
- [Bleve](https://blevesearch.com/)
- [Cilium](https://cilium.io/)
- [CloudQuery](https://github.com/cloudquery/cloudquery)
- [CockroachDB](https://www.cockroachlabs.com/)
- [Constellation](https://github.com/edgelesssys/constellation)
- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)
- [Datree](https://github.com/datreeio/datree)
- [Delve](https://github.com/derekparker/delve)
- [Docker (distribution)](https://github.com/docker/distribution)
- [Encore](https://encore.dev)
- [Etcd](https://etcd.io/)
- [Gardener](https://github.com/gardener/gardenctl)
- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)
@ -21,13 +24,15 @@
- [GoReleaser](https://goreleaser.com)
- [Helm](https://helm.sh)
- [Hugo](https://gohugo.io)
- [Incus](https://linuxcontainers.org/incus/)
- [Infracost](https://github.com/infracost/infracost)
- [Istio](https://istio.io)
- [Kool](https://github.com/kool-dev/kool)
- [Kubernetes](https://kubernetes.io/)
- [Kubescape](https://github.com/armosec/kubescape)
- [Kubescape](https://github.com/kubescape/kubescape)
- [KubeVirt](https://github.com/kubevirt/kubevirt)
- [Linkerd](https://linkerd.io/)
- [LXC](https://github.com/canonical/lxd)
- [Mattermost-server](https://github.com/mattermost/mattermost-server)
- [Mercure](https://mercure.rocks/)
- [Meroxa CLI](https://github.com/meroxa/cli)
@ -51,10 +56,14 @@
- [Random](https://github.com/erdaltsksn/random)
- [Rclone](https://rclone.org/)
- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)
- [Sia](https://github.com/SiaFoundation/siad)
- [Skaffold](https://skaffold.dev/)
- [Taikun](https://taikun.cloud/)
- [Tendermint](https://github.com/tendermint/tendermint)
- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)
- [Vitess](https://vitess.io)
- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)
- [Werf](https://werf.io/)
- [Zarf](https://github.com/defenseunicorns/zarf)
- [ZITADEL](https://github.com/zitadel/zitadel)

View file

@ -3,7 +3,7 @@
While you are welcome to provide your own organization, typically a Cobra-based
application will follow the following organizational structure:
```
```test
▾ appName/
▾ cmd/
add.go
@ -29,8 +29,8 @@ func main() {
## Using the Cobra Generator
Cobra-CLI is its own program that will create your application and add any
commands you want. It's the easiest way to incorporate Cobra into your application.
Cobra-CLI is its own program that will create your application and add any commands you want.
It's the easiest way to incorporate Cobra into your application.
For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
@ -188,6 +188,37 @@ var versionCmd = &cobra.Command{
}
```
### Organizing subcommands
A command may have subcommands which in turn may have other subcommands. This is achieved by using
`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in
its own go package.
The suggested approach is for the parent command to use `AddCommand` to add its most immediate
subcommands. For example, consider the following directory structure:
```text
├── cmd
│   ├── root.go
│   └── sub1
│   ├── sub1.go
│   └── sub2
│   ├── leafA.go
│   ├── leafB.go
│   └── sub2.go
└── main.go
```
In this case:
* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.
* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.
* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the
sub2 command.
This approach ensures the subcommands are always included at compile time while avoiding cyclic
references.
### Returning and handling errors
If you wish to return an error to the caller of a command, `RunE` can be used.
@ -270,6 +301,7 @@ command := cobra.Command{
### Bind Flags with Config
You can also bind your flags with [viper](https://github.com/spf13/viper):
```go
var author string
@ -289,12 +321,14 @@ More in [viper documentation](https://github.com/spf13/viper#working-with-flags)
Flags are optional by default. If instead you wish your command to report an error
when a flag has not been set, mark it as required:
```go
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkFlagRequired("region")
```
Or, for persistent flags:
```go
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkPersistentFlagRequired("region")
@ -304,6 +338,7 @@ rootCmd.MarkPersistentFlagRequired("region")
If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then
Cobra can enforce that requirement:
```go
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
@ -312,13 +347,24 @@ rootCmd.MarkFlagsRequiredTogether("username", "password")
You can also prevent different flags from being provided together if they represent mutually
exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
```go
rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")
rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
```
In both of these cases:
If you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`.
This can be combined with `MarkFlagsMutuallyExclusive` to enforce exactly one flag from a given group:
```go
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
rootCmd.MarkFlagsOneRequired("json", "yaml")
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
```
In these cases:
- both local and persistent flags can be used
- **NOTE:** the group is only enforced on commands where every flag is defined
- a flag may appear in multiple groups
@ -349,7 +395,7 @@ shown below:
```go
var cmd = &cobra.Command{
Short: "hello",
Args: MatchAll(ExactArgs(2), OnlyValidArgs),
Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
@ -388,7 +434,7 @@ by not providing a 'Run' for the 'rootCmd'.
We have only defined one flag for a single command.
More documentation about flags is available at https://github.com/spf13/pflag
More documentation about flags is available at https://github.com/spf13/pflag.
```go
package main
@ -492,10 +538,11 @@ around it. In fact, you can provide your own if you want.
### Grouping commands in help
Cobra supports grouping of available commands. Groups must be explicitly defined by `AddGroup` and set by
the `GroupId` element of a subcommand. The groups will appear in the same order as they are defined.
If you use the generated `help` or `completion` commands, you can set the group ids by `SetHelpCommandGroupId`
and `SetCompletionCommandGroupId`, respectively.
Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly
defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element
of that subcommand. The groups will appear in the help output in the same order as they are defined using different
calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using
`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.
### Defining your own help
@ -555,9 +602,15 @@ Running an application with the '--version' flag will print the version to stdou
the version template. The template can be customized using the
`cmd.SetVersionTemplate(s string)` function.
## Error Message Prefix
Cobra prints an error message when receiving a non-nil error value.
The default error message is `Error: <error contents>`.
The Prefix, `Error:` can be customized using the `cmd.SetErrPrefix(s string)` function.
## PreRun and PostRun Hooks
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. The `*PreRun` and `*PostRun` functions will only be executed if the `Run` function of the current command has been declared. These functions are run in the following order:
- `PersistentPreRun`
- `PreRun`
@ -640,6 +693,10 @@ Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun with args: [arg1 arg2]
```
By default, only the first persistent hook found in the command chain is executed.
That is why in the above output, the `rootCmd PersistentPostRun` was not called for a child command.
Set `EnableTraverseRunHooks` global variable to `true` if you want to execute all parents' persistent hooks.
## Suggestions when "unknown command" happens
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
@ -671,7 +728,7 @@ command.SuggestionsMinimumDistance = 1
You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which
you don't want aliases. Example:
```
```bash
$ kubectl remove
Error: unknown command "remove" for "kubectl"
@ -683,12 +740,71 @@ Run 'kubectl help' for usage.
## Generating documentation for your command
Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
Cobra can generate documentation based on subcommands, flags, etc.
Read more about it in the [docs generation documentation](docgen/_index.md).
## Generating shell completions
Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).
Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell.
If you add more information to your commands, these completions can be amazingly powerful and flexible.
Read more about it in [Shell Completions](completions/_index.md).
## Providing Active Help
Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md).
Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users.
Active Help are messages (hints, warnings, etc) printed as the program is being used.
Read more about it in [Active Help](active_help.md).
## Creating a plugin
When creating a plugin for tools like *kubectl*, the executable is named
`kubectl-myplugin`, but it is used as `kubectl myplugin`. To fix help
messages and completions, annotate the root command with the
`cobra.CommandDisplayNameAnnotation` annotation.
### Example kubectl plugin
```go
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "kubectl-myplugin",
Annotations: map[string]string{
cobra.CommandDisplayNameAnnotation: "kubectl myplugin",
},
}
subCmd := &cobra.Command{
Use: "subcmd",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("kubectl myplugin subcmd")
},
}
rootCmd.AddCommand(subCmd)
rootCmd.Execute()
}
```
Example run as a kubectl plugin:
```bash
$ kubectl myplugin
Usage:
kubectl myplugin [command]
Available Commands:
completion Generate the autocompletion script for the specified shell
help Help about any command
subcmd
Flags:
-h, --help help for kubectl myplugin
Use "kubectl myplugin [command] --help" for more information about a command.
```

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -90,6 +90,7 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
compCmd = ShellCompNoDescRequestCmd
}
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
compdef _%[1]s %[1]s
# zsh completion for %-36[1]s -*- shell-script -*-
@ -108,8 +109,9 @@ _%[1]s()
local shellCompDirectiveNoFileComp=%[5]d
local shellCompDirectiveFilterFileExt=%[6]d
local shellCompDirectiveFilterDirs=%[7]d
local shellCompDirectiveKeepOrder=%[8]d
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
local -a completions
__%[1]s_debug "\n========= starting completion logic =========="
@ -177,7 +179,7 @@ _%[1]s()
return
fi
local activeHelpMarker="%[8]s"
local activeHelpMarker="%[9]s"
local endIndex=${#activeHelpMarker}
local startIndex=$((${#activeHelpMarker}+1))
local hasActiveHelp=0
@ -227,6 +229,11 @@ _%[1]s()
noSpace="-S ''"
fi
if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
__%[1]s_debug "Activating keep order."
keepOrder="-V"
fi
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
# File extension filtering
local filteringCmd
@ -262,7 +269,7 @@ _%[1]s()
return $result
else
__%[1]s_debug "Calling _describe"
if eval _describe "completions" completions $flagPrefix $noSpace; then
if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then
__%[1]s_debug "_describe found some completions"
# Return the success of having called _describe
@ -296,6 +303,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then
fi
`, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
activeHelpMarker))
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2022 The Cobra Authors
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.