Commit Graph

1058 Commits

Author SHA1 Message Date
Alessandro Arzilli 718befc9a8
Merge 84ffa30b08 into 02326d52c0 2024-11-11 10:22:27 -05:00
Vui Lam 02326d52c0
Fix broken links in active_help.md (#2202)
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 (#2196)
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 (#2198) 2024-10-16 14:13:47 -04:00
aarzilli 84ffa30b08 addressing review comments 2024-10-15 10:33:24 +02:00
aarzilli 4da4d97d60 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
2024-10-15 10:19:12 +02:00
Nir Soffer 5bef9d8d87
Fix --version help and output for plugins (#2180)
* 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 (#2183)
* 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 (#2197)
minor fix
2024-10-11 06:40:47 -04:00
Nir Soffer 78bfc837fe
Test also with go 1.23 (#2182) 2024-08-24 19:02:44 -04:00
Nir Soffer 511af59cb3
Replace deprecated ioutil usage (#2181)
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 (#2174) 2024-07-28 12:18:07 -04:00
Sebastiaan van Stijn 371ae25d2c
Fix deprecation comment for Command.SetOutput (#2172)
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 (#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