Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: spf13/cobra
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v1.7.0
Choose a base ref
...
head repository: spf13/cobra
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v1.8.1
Choose a head ref

Commits on Apr 8, 2023

  1. Copy the full SHA
    284f410 View commit details

Commits on Jun 12, 2023

  1. Copy the full SHA
    0e3a0bf View commit details

Commits on Jun 13, 2023

  1. 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>
    supertassu authored Jun 13, 2023
    Copy the full SHA
    2246fa8 View commit details

Commits on Jun 16, 2023

  1. 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`.
    branchvincent authored Jun 16, 2023
    Copy the full SHA
    988bd76 View commit details

Commits on Jun 19, 2023

  1. 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 6ba7ebb.
    
    Fixes #1853
    
    Signed-off-by: Paul Holzinger <pholzing@redhat.com>
    Luap99 authored Jun 19, 2023
    Copy the full SHA
    fdee73b View commit details

Commits on Jun 20, 2023

  1. Copy the full SHA
    cbe4865 View commit details
  2. Copy the full SHA
    dcb405a View commit details

Commits on Jul 16, 2023

  1. Copy the full SHA
    c81c46a View commit details

Commits on Jul 18, 2023

  1. Copy the full SHA
    66b215b View commit details

Commits on Jul 20, 2023

  1. Copy the full SHA
    60d056d View commit details

Commits on Jul 23, 2023

  1. Copy the full SHA
    fd865a4 View commit details

Commits on Aug 28, 2023

  1. Copy the full SHA
    4955da7 View commit details

Commits on Aug 29, 2023

  1. Copy the full SHA
    285460d View commit details

Commits on Sep 8, 2023

  1. Copy the full SHA
    c5dacb3 View commit details
  2. Copy the full SHA
    0c72800 View commit details

Commits on Sep 26, 2023

  1. Copy the full SHA
    bd4d165 View commit details

Commits on Oct 9, 2023

  1. Copy the full SHA
    95d8a1e View commit details

Commits on Oct 15, 2023

  1. Copy the full SHA
    efe8fa3 View commit details

Commits on Oct 16, 2023

  1. Copy the full SHA
    5c962a2 View commit details

Commits on Oct 22, 2023

  1. 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:
    - #216
    - #252
    
    Signed-off-by: Volodymyr Khoroz <volodymyr.khoroz@foundries.io>
    vkhoroz authored Oct 22, 2023
    Copy the full SHA
    4cafa37 View commit details

Commits on Oct 27, 2023

  1. 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>
    marckhouzam authored Oct 27, 2023
    Copy the full SHA
    8b1eba4 View commit details

Commits on Oct 28, 2023

  1. 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>
    marckhouzam authored Oct 28, 2023
    Copy the full SHA
    b711e87 View commit details
  2. 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:
    - #1320
    - #1438 (comment)
    
    Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
    marckhouzam authored Oct 28, 2023
    Copy the full SHA
    00b68a1 View commit details

Commits on Oct 29, 2023

  1. 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
    scop authored Oct 29, 2023
    Copy the full SHA
    22953d8 View commit details

Commits on Oct 30, 2023

  1. Copy the full SHA
    48cea5c View commit details

Commits on Nov 2, 2023

  1. 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>
    nirs authored Nov 2, 2023
    Copy the full SHA
    890302a View commit details
  2. 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>
    marckhouzam authored Nov 2, 2023
    Copy the full SHA
    a0a6ae0 View commit details

Commits on Nov 13, 2023

  1. Copy the full SHA
    283e32d View commit details

Commits on Nov 23, 2023

  1. 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
    scop authored Nov 23, 2023
    Copy the full SHA
    3d8ac43 View commit details

Commits on Dec 12, 2023

  1. Update projects_using_cobra.md (#2089)

    Add Encore to the list of projects using Cobra
    marcuskohlberg authored Dec 12, 2023
    Copy the full SHA
    236f3c0 View commit details

Commits on Dec 17, 2023

  1. 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.
    scop authored Dec 17, 2023
    Copy the full SHA
    e63925d View commit details

Commits on Dec 18, 2023

  1. 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.
    nirs authored and marckhouzam committed Dec 18, 2023
    Copy the full SHA
    df547f5 View commit details
  2. 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
    nirs authored and marckhouzam committed Dec 18, 2023
    Copy the full SHA
    a73b9c3 View commit details
  3. Document how to create a plugin

    Using the new CommandDisplayNameAnnotation annotation introduced in
    Cobra 1.8.0.
    nirs authored and marckhouzam committed Dec 18, 2023
    Copy the full SHA
    4122785 View commit details

Commits on Dec 23, 2023

  1. 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](actions/setup-go@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>
    dependabot[bot] authored and marckhouzam committed Dec 23, 2023
    Copy the full SHA
    c054701 View commit details
  2. Remove extra actions/checkout

    Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
    marckhouzam committed Dec 23, 2023
    Copy the full SHA
    531ce79 View commit details
  3. 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](actions/labeler@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>
    dependabot[bot] and marckhouzam authored Dec 23, 2023
    Copy the full SHA
    199b7ab View commit details

Commits on Dec 28, 2023

  1. [chore]: update projects using cobra (#2093)

    Signed-off-by: Case Wylie <cmwylie19@defenseunicorns.com>
    cmwylie19 authored Dec 28, 2023
    Copy the full SHA
    cbcf75e View commit details

Commits on Dec 30, 2023

  1. Copy the full SHA
    0dec88e View commit details

Commits on Jan 6, 2024

  1. Copy the full SHA
    4fb0a66 View commit details

Commits on Jan 15, 2024

  1. Copy the full SHA
    bcfcff7 View commit details

Commits on Mar 8, 2024

  1. Copy the full SHA
    bd2655e View commit details

Commits on Mar 12, 2024

  1. 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](golangci/golangci-lint-action@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>
    dependabot[bot] authored Mar 12, 2024
    Copy the full SHA
    f34069c View commit details
  2. 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](actions/cache@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>
    dependabot[bot] authored Mar 12, 2024
    Copy the full SHA
    a30cee5 View commit details
  3. Copy the full SHA
    c69ae4c View commit details
  4. chore: remove repetitive words (#2122)

    Signed-off-by: racerole <jiangyifeng@outlook.com>
    racerole authored Mar 12, 2024
    Copy the full SHA
    1f80fa2 View commit details
  5. 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
    pedromotita authored Mar 12, 2024
    Copy the full SHA
    bd914e5 View commit details

Commits on Apr 1, 2024

  1. More linting (#2099)

    * Address gocritic findings, enable it
    
    * Enable gosimple, no new findings to address
    scop authored Apr 1, 2024
    Copy the full SHA
    6b5f577 View commit details

Commits on Apr 8, 2024

  1. Copy the full SHA
    0fc86c2 View commit details

Commits on Apr 13, 2024

  1. Copy the full SHA
    5a1acea View commit details
Showing with 1,384 additions and 274 deletions.
  1. +13 −6 .github/labeler.yml
  2. +1 −1 .github/workflows/labeler.yml
  3. +11 −11 .github/workflows/test.yml
  4. +12 −17 .golangci.yml
  5. +4 −4 README.md
  6. +5 −8 active_help.go
  7. +2 −2 args.go
  8. +12 −15 bash_completions.go
  9. +1 −1 bash_completionsV2.go
  10. +9 −6 cobra.go
  11. +182 −0 cobra_test.go
  12. +90 −28 command.go
  13. +148 −66 command_test.go
  14. +76 −15 completions.go
  15. +533 −3 completions_test.go
  16. +1 −1 doc/man_docs.go
  17. +1 −1 doc/man_docs_test.go
  18. +6 −4 doc/md_docs.go
  19. +1 −1 doc/rest_docs.go
  20. +1 −1 doc/util.go
  21. +1 −1 fish_completions.go
  22. +0 −4 fish_completions.md
  23. +13 −22 fish_completions_test.go
  24. +76 −10 flag_groups.go
  25. +53 −10 flag_groups_test.go
  26. +1 −1 go.mod
  27. +2 −2 go.sum
  28. +5 −5 powershell_completions.go
  29. +0 −3 powershell_completions.md
  30. +1 −1 powershell_completions_test.go
  31. +2 −2 { → site/content}/active_help.md
  32. +9 −6 shell_completions.md → site/content/completions/_index.md
  33. +1 −1 bash_completions.md → site/content/completions/bash.md
  34. +4 −0 site/content/completions/fish.md
  35. +3 −0 site/content/completions/powershell.md
  36. +1 −1 zsh_completions.md → site/content/completions/zsh.md
  37. +4 −4 doc/README.md → site/content/docgen/_index.md
  38. 0 doc/man_docs.md → site/content/docgen/man.md
  39. 0 doc/md_docs.md → site/content/docgen/md.md
  40. 0 doc/rest_docs.md → site/content/docgen/rest.md
  41. 0 doc/yaml_docs.md → site/content/docgen/yaml.md
  42. +5 −0 { → site/content}/projects_using_cobra.md
  43. +94 −10 { → site/content}/user_guide.md
19 changes: 13 additions & 6 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
@@ -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*'
2 changes: 1 addition & 1 deletion .github/workflows/labeler.yml
Original file line number Diff line number Diff line change
@@ -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 }}"

22 changes: 11 additions & 11 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -18,7 +18,7 @@ jobs:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v3
- uses: actions/checkout@v4

- run: >-
docker run
@@ -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.20'
go-version: '^1.22'
check-latest: true
cache: true

- uses: actions/checkout@v3

- uses: golangci/golangci-lint-action@v3.4.0
- uses: golangci/golangci-lint-action@v4.0.0
with:
version: latest
args: --verbose
@@ -67,13 +65,15 @@ jobs:
- 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
@@ -107,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') }}
29 changes: 12 additions & 17 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -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
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ 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/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)
@@ -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)
13 changes: 5 additions & 8 deletions active_help.go
Original file line number Diff line number Diff line change
@@ -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)
}
4 changes: 2 additions & 2 deletions args.go
Original file line number Diff line number Diff line change
@@ -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) {
27 changes: 12 additions & 15 deletions bash_completions.go
Original file line number Diff line number Diff line change
@@ -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[*]}"
@@ -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 len(flag.Shorthand) > 0 {
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
}
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))
}
}
})
@@ -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 {
2 changes: 1 addition & 1 deletion bash_completionsV2.go
Original file line number Diff line number Diff line change
@@ -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[*]}"
15 changes: 9 additions & 6 deletions cobra.go
Original file line number Diff line number Diff line change
@@ -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 ("").
@@ -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] {
Loading