1
0
Fork 0
mirror of https://github.com/spf13/cobra synced 2025-04-01 12:29:12 +00:00
Commit graph

1079 commits

Author SHA1 Message Date
John McBride
ceb39aba25
chore: Rm GitHub Action PR size labeler ()
Signed-off-by: John McBirde <jpmmcbride@gmail.com>
2025-03-11 06:56:36 -06:00
John McBride
c25b598345
feat: Add security policy ()
Signed-off-by: John McBirde <jpmmcbride@gmail.com>
2025-03-10 16:46:30 -06:00
styee
4f9ef8cdbb
Update command.go ()
Fix spelling in the help output.

topcis -> topics
2025-03-07 09:53:22 -05:00
Fraser Waters
1995054b00
Flow context to command in SetHelpFunc ()
Fixes https://github.com/spf13/cobra/issues/2240
2025-02-21 07:46:14 -05:00
Yedaya Katsman
f98cf4216d
Remove traling curlybrace () 2025-02-17 14:16:17 -05:00
Chongyi Zheng
0d417d8f77
Test with Go 1.24 () 2025-02-17 13:59:07 -05:00
Marc Khouzam
40b5bc1437
Revert "Make detection for test-binary more universal ()" ()
This reverts commit d1e9d85fcf.

Some programs set os.Args in their unit tests and this change would
break those tests.

Ref: https://github.com/spf13/cobra/pull/2173#issuecomment-2661544195
2025-02-16 18:42:04 -05:00
ccoVeille
a97f9fd47b
fix CompletionFunc implementation ()
The new type CompletionFunc could lead to a regression.
This commit make the new `CompletionFunc` type a type alias instead,
in case projects using Cobra have created their own similar type.

This commit also adds a test to ensure that the completion function
remains backwards-compatible.

Signed-off-by: ccoVeille <3875889+ccoVeille@users.noreply.github.com>
2025-02-16 13:08:14 -05:00
John McBride
5f9c40898e
chore: Upgrade dependencies for v1.9.0 ()
Signed-off-by: John McBirde <jpmmcbride@gmail.com>
2025-02-15 11:17:48 -07:00
Marc Khouzam
24ada7fe71
Remove the default "completion" cmd if it is alone ()
When a program has no sub-commands, its root command can accept
arguments.  If we add the default "completion" command to such programs
they will now have a sub-command and will no longer accept arguments.

What we do instead for this special case, is only add the "completion"
command if it is being called, or if it is being completed itself.

We want to have the "completion" command for such programs because it
will allow the completion of flags and of arguments (if provided
by the program).

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2025-02-15 11:07:02 -07:00
Steve Francia
680936a220
New logo 2025-02-11 20:00:54 -05:00
ccoVeille
8cb30f9ca5
feat: add CompletionWithDesc helper ()
The code has also been refactored to use a type alias for completion and a completion helper

Using a type alias is a non-breaking change and it makes the code more readable and easier to understand.

Signed-off-by: ccoVeille <3875889+ccoVeille@users.noreply.github.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2025-02-09 11:06:07 -05:00
Raúl Barroso
17b6dca2ff
doc: add Conduit ()
We recently added a CLI to a our Conduit project, and we use Cobra to power it.

Here's a blog post mentioning it https://meroxa.com/blog/introducing-the-new-conduit-cli:-a-powerful-tool-for-managing-your-pipelines/
2025-02-06 15:35:25 -05:00
Marc Khouzam
ab5cadcc1b
Allow to reset the templates to the default ()
Follow-up to .

This commit allows a program to reset any of the tree templates to their
default behaviour, as it was possible to do before the change of .

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2025-02-06 08:25:44 -07:00
Ville Skyttä
4ba5566f57
fix(bash): nounset unbound file filter variable on empty extension ()
Happens at least if a flag is marked as filename, with "" given as
extensions.
2025-02-01 19:35:34 -05:00
Marc Khouzam
41b26ec8bb
Print ActiveHelp for bash along other completions ()
In the bash shell we used to print ActiveHelp messages on every
tab-press. In the example below, notice the "Command help" line which is
ActiveHelp:

bash-5.1$ tanzu context u[tab]
Command help: Configure and manage contexts for the Tanzu CLI

bash-5.1$ tanzu context u[tab]
Command help: Configure and manage contexts for the Tanzu CLI

bash-5.1$ tanzu context u
unset  (Unset the active context so that it is not used by default.)
use    (Set the context to be used by default)
bash-5.1$ tanzu context u

Above, on the first [tab] press, only the ActiveHelp is printed.
On the second [tab] press, the ActiveHelp is printed again, followed
by a re-print of the command-line, followed by the completions choices.

The separation between ActiveHelp and completion choices makes the
ActiveHelp harder to see. Furthermore, I find the double printing of the
ActiveHelp string to look bad.

Note that for zsh, the UX is different and that ActiveHelp messages are
printed at the same time as the completion choices.

This commit aligns the UX for ActiveHelp in bash with the one for zsh:
if there are other completions to be shown, the ActiveHelp messages are
printed at the same time.

New behaviour:
1- ActiveHelp is no longer printed on the first [tab] press. This is
   better aligned with bash's standard approach.
2- ActiveHelp is printed on the second [tab] press, above the completion
   choices, with a `--` delimiter.
3- If there are no completion choices, the `--` delimiter is omitted.

This behaviour is the same as what is done for zsh (except that for zsh
the first [tab] press immediately shows completion choices).

Below is the above example, but using this commit.
Notice the more concise and easier to read completion output:

bash-5.1$ tanzu context u[tab][tab]
Command help: Configure and manage contexts for the Tanzu CLI
--
unset  (Unset the active context so that it is not used by default.)
use    (Set the context to be used by default)
bash-5.1$ tanzu context u

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
2025-01-29 19:28:46 -05:00
Alessandro Arzilli
611e16c322
Allow linker to perform deadcode elimination for program using Cobra ()
* Restructure code to let linker perform deadcode elimination step

Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.

Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.

This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:

1. changing Cobra's default behavior to emit output for usage and help using
   simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
   SetHelpTemplate and SetVersionTemplate so that the linker can statically
   determine if they are reachable

Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2025-01-27 09:43:43 -05:00
Toni Kangas
09d5664f34
Add similar whitespace escape logic to bash v2 completions than in other completions ()
Signed-off-by: Toni Kangas <toni.kangas@upcloud.com>
Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Jeffrey Faer <jeffrey.faer@gmail.com>
2025-01-22 21:28:30 -05:00
ccoVeille
6c3c1163c6
feat: add CompletionFunc type to help with completions ()
Also document that NoFilesCompletion and FixedCompletion can be used with RegisterFlagCompletionFunc.
2025-01-21 20:34:05 -05:00
ZhuHaiCheng
01ffff4eca
chore: fix function name in comment ()
Signed-off-by: zhuhaicity <zhuhai@52it.net>
2025-01-12 07:49:28 -05:00
Sebastiaan van Stijn
0745e55762
completion: improve detection for flags that accept multiple values ()
The completion code attempts to detect whether a flag can be specified
more than once, and therefore should provide completion even if already
set.

Currently, this code depends on conventions used in the pflag package,
which uses an "Array" or "Slice" suffix or for some types a "stringTo"
prefix.

Cobra allows custom value types to be used, which may not use the same
convention for naming, and therefore currently aren't detected to allow
multiple values.

The pflag module defines a [SliceValue] interface, which is implemented
by the Slice and Array value types it provides (unfortunately, it's not
currently implemented by the "stringTo" values).

This patch adds a reduced interface based on the [SliceValue] interface
mentioned above to allow detecting Value-types that accept multiple values.
Custom types can implement this interface to make completion work for
those values.

I deliberately used a reduced interface to keep the requirements for this
detection as low as possible, without enforcing the other methods defined
in the interface (Append, Replace) which may not apply to all custom types.

Future improvements can likely still be made, considering either implementing
the SliceValue interface for the "stringTo" values or defining a separate
"MapValue" interface for those types.

Possibly providing the reduced interface as part of the pflag module and
to export it.

[SliceValue]: d5e0c0615a/flag.go (L193-L203)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2024-12-28 17:41:43 -05:00
Sebastiaan van Stijn
d1e9d85fcf
Make detection for test-binary more universal ()
When running tests in verbose mode (or other options), tests involving
Cobra may fail if the test does not explicitly set Command.args to an
empty slice; in this case, Cobra defaults to using `os.Args`, which
will contain arguments passed to the test (such as `-v` (verbose)).

Commits e5762054c9 and 1ef0913976
implemented a workaround for this when running (unit) tests for Cobra
itself, but this check is specifig to Cobra (checking for `cobra.test`),
and don't work on Windows (which will have a `.exe` extension),

This patch implements a more universal check, so that users of Cobra
as a module also benefit from this workaround.

go1.21 and up provides a `testing.Testing()` utility ([1]); as the Cobra
module still supports Go1.16 and up, an alternative implementation was
added for older versions, based on golang.org/x/mod/lazyregexp [2].

Before this patch:

    go test -c -o foo.test

    ./foo.test -test.run TestNoArgs
    --- FAIL: TestNoArgs (0.00s)
        args_test.go:37: Unexpected output: Error: unknown command "TestNoArgs" for "c"
            Usage:
              c [flags]

            Flags:
              -h, --help   help for c

        args_test.go:40: Unexpected error: unknown command "TestNoArgs" for "c"
    FAIL

After this patch:

    go test -c -o foo.test

    ./foo.test -test.run TestNoArgs
    PASS

[1]: https://pkg.go.dev/testing#Testing
[2]: https://cs.opensource.google/go/x/mod/+/refs/tags/v0.19.0:internal/lazyregexp/lazyre.go;l=66-78

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2024-12-28 17:07:03 -05:00
Sebastiaan van Stijn
9f9056765c
build(deps): bump github.com/cpuguy83/go-md2man/v2 from 2.0.5 to 2.0.6 ()
fix compatibility with go versions before go1.17

diff: https://github.com/cpuguy83/go-md2man/compare/v2.0.5...v2.0.6

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 21:26:34 -05:00
Mikel Olasagasti Uranga
8519630750
Update to latest go-md2man ()
Since cpuguy83/go-md2man 2.0.5 no paraTag is written after "SEE ALSO".

With go-md2man 2.0.4:

.SH SEE ALSO
.PP
\fBroot-bbb(1)\fP, \fBroot-ccc(1)\fP

With go-md2man 2.0.5:

.SH SEE ALSO
\fBroot-bbb(1)\fP, \fBroot-ccc(1)\fP

See: https://github.com/cpuguy83/go-md2man/pull/122

Signed-off-by: Mikel Olasagasti Uranga <mikel@olasagasti.info>
2024-12-11 07:26:08 -05:00
Vui Lam
02326d52c0
Fix broken links in active_help.md ()
Small change to fix a couple of broken links in active_help.md

Signed-off-by: Vui Lam <vui.lam@broadcom.com>
2024-11-05 06:19:24 -05:00
Leonhard Stemplinger
5a138f143f
Make Powershell completion script work in constrained mode ()
Creating CompletionResult objects is not allowed in Powershell constrained mode, so return results as strings if constrained mode is enabled

Store results as PsCustomObjects instead of hashtables. This prevents Sort-Object from trying to convert the hashtable to a object, which is blocked in constrained mode.
PsCustomObjects are created using New-Object to work around https://github.com/PowerShell/PowerShell/issues/20767
2024-11-03 19:45:01 -05:00
Maxwel Mazur
3a5efaede9
doc: azion project added to the list of CLIs that use cobra () 2024-10-16 14:13:47 -04:00
Nir Soffer
5bef9d8d87
Fix --version help and output for plugins ()
* Fix --version help with CommandDisplayNameAnnotation

When setting Command.Version, a --version option is added. The help
message for the --version command did not consider the command display
name:

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

With this change the help test is consistent with other flags:

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

* Make command DisplayName() public

This allows using the display name in templates or other code that want
to use the same value.

* Use display name in version template

The version template used `{{.Name}}` but for plugins you want to use
`{{.DisplayName}}` to be consistent with other help output.

With this change will show:

    $ kubectl plugin --version
    kubectl plugin version 1.0.0
2024-10-12 12:08:27 -04:00
Nir Soffer
ff7c561cf7
Improve site formatting ()
* Improve site formatting

- Separate titles with blank lines
- Separate code blocks with blank lines
- Always use ``` blocks for examples
- Use console for console (bash syntax highlighting does work well with
  example command output)
- Start console examples with $ (highlight command and output
  differently and more friendly to other shells users)

* Unify indentation in example project structure

* Use single import line in the trivial examples

When we want to show a minimal example with single import it looks
cleaner and more minimal with a single line.
2024-10-12 11:35:01 -04:00
Ikko Eltociear Ashimine
11ab62158a
docs: update README.md ()
minor fix
2024-10-11 06:40:47 -04:00
Nir Soffer
78bfc837fe
Test also with go 1.23 () 2024-08-24 19:02:44 -04:00
Nir Soffer
511af59cb3
Replace deprecated ioutil usage ()
Fixing golangci-lint errors[1]:

    Error: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of
    Go 1.16, the same functionality is now provided by package [io] or
    package [os], and those implementations should be preferred in new
    code. See the specific function documentation for details.
    (staticcheck)

[1] https://github.com/spf13/cobra/actions/runs/10535452454/job/29194442289?pr=2180
2024-08-24 07:05:26 -04:00
Gabe Cook
756ba6dad6
fix(completions): Complete map flags multiple times () 2024-07-28 12:18:07 -04:00
Sebastiaan van Stijn
371ae25d2c
Fix deprecation comment for Command.SetOutput ()
Deprecation comments should be at the start of a paragraph [1], and because
of that have a whitespace above them [2];

> To signal that an identifier should not be used, add a paragraph to its
> doc comment that begins with Deprecated: followed by some information
> about the deprecation (...)

With the whitespace missing, some tools, including pkg.go.dev [3] don't
detect it to be deprecated.

[1]: https://go.dev/wiki/Deprecated
[2]: https://go.dev/doc/comment#paragraphs
[3]: https://pkg.go.dev/github.com/spf13/cobra@v1.8.1#Command.SetOutput

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-16 19:36:29 -04:00
Ville Skyttä
e94f6d0dd9
Address golangci-lint deprecation warnings, enable some more linters ()
* 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 ()
* 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 ()
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 .
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 () 2024-04-13 02:21:03 +00:00
Xinwei Xiong
0fc86c2ffd
docs: update user guide () 2024-04-08 06:47:35 -04:00
Ville Skyttä
6b5f577ebc
More linting ()
* 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 ()
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 
2024-03-12 06:42:46 -04:00
racerole
1f80fa2e23
chore: remove repetitive words ()
Signed-off-by: racerole <jiangyifeng@outlook.com>
2024-03-12 06:40:19 -04:00
damas
c69ae4c36b
ci: test golang 1.22 () 2024-03-12 06:40:01 -04:00
dependabot[bot]
a30cee5e5a
build(deps): bump actions/cache from 3 to 4 ()
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 ()
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 () 2024-03-07 19:36:58 -05:00
Radek Smid
bcfcff729e
Add Taikun CloudWorks to list of projects () 2024-01-15 08:38:50 -05:00
Dmytro Milinevskyi
4fb0a66a34
flags: clarify documentation that LocalFlags related function do not modify the state () 2024-01-06 16:49:13 -05:00
Denis
0dec88e793
Add tests for funcs in cobra.go () 2023-12-30 08:40:15 -05:00
Case Wylie
cbcf75eab9
[chore]: update projects using cobra ()
Signed-off-by: Case Wylie <cmwylie19@defenseunicorns.com>
2023-12-27 21:16:29 -05:00