Compare commits

..

No commits in common. "main" and "v1.6.0" have entirely different histories.
main ... v1.6.0

63 changed files with 756 additions and 3235 deletions

19
.github/labeler.yml vendored
View file

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

View file

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

33
.github/workflows/size-labeler.yml vendored Normal file
View file

@ -0,0 +1,33 @@
# Reference: https://github.com/CodelyTV/pr-size-labeler
name: size-labeler
on: [pull_request_target]
permissions:
contents: read
jobs:
size-labeler:
permissions:
pull-requests: write # for codelytv/pr-size-labeler to add labels & comment on PRs
runs-on: ubuntu-latest
name: Label the PR size
steps:
- uses: codelytv/pr-size-labeler@v1.8.1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
xs_label: 'size/XS'
xs_max_size: '10'
s_label: 'size/S'
s_max_size: '24'
m_label: 'size/M'
m_max_size: '99'
l_label: 'size/L'
l_max_size: '200'
xl_label: 'size/XL'
fail_if_xl: 'false'
message_if_xl: >
'This PR exceeds the recommended size of 200 lines.
Please make sure you are NOT addressing multiple issues with one PR.
Note this PR might be rejected due to its size.

56
.github/workflows/stale.yml vendored Normal file
View file

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

View file

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

View file

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

View file

@ -1,13 +1,12 @@
![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
![cobra logo](https://github.com/user-attachments/assets/cbc3adf8-0dff-46e9-a88d-5e2d971c169e)
Cobra is a library for creating powerful modern CLI applications. Cobra is a library for creating powerful modern CLI applications.
Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), 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 [Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. name a few. [This list](./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) [![](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)
[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) [![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) [![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) [![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
@ -81,7 +80,7 @@ which maintains the same interface while adding POSIX compliance.
# Installing # Installing
Using Cobra is easy. First, use `go get` to install the latest version 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 go get -u github.com/spf13/cobra@latest
@ -106,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-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 Cobra User Guide](site/content/user_guide.md). For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).
# License # License
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)

View file

@ -1,105 +0,0 @@
# Security Policy
## Reporting a Vulnerability
The `cobra` maintainers take security issues seriously and
we appreciate your efforts to _**responsibly**_ disclose your findings.
We will make every effort to swiftly respond and address concerns.
To report a security vulnerability:
1. **DO NOT** create a public GitHub issue for the vulnerability!
2. **DO NOT** create a public GitHub Pull Request with a fix for the vulnerability!
3. Send an email to `cobra-security@googlegroups.com`.
4. Include the following details in your report:
- Description of the vulnerability
- Steps to reproduce
- Potential impact of the vulnerability (to your downstream project, to the Go ecosystem, etc.)
- Any potential mitigations you've already identified
5. Allow up to 7 days for an initial response.
You should receive an acknowledgment of your report and an estimated timeline for a fix.
6. (Optional) If you have a fix and would like to contribute your patch, please work
directly with the maintainers via `cobra-security@googlegroups.com` to
coordinate pushing the patch to GitHub, cutting a new release, and disclosing the change.
## Response Process
When a security vulnerability report is received, the `cobra` maintainers will:
1. Confirm receipt of the vulnerability report within 7 days.
2. Assess the report to determine if it constitutes a security vulnerability.
3. If confirmed, assign the vulnerability a severity level and create a timeline for addressing it.
4. Develop and test a fix.
5. Patch the vulnerability and make a new GitHub release: the maintainers will coordinate disclosure with the reporter.
6. Create a new GitHub Security Advisory to inform the broader Go ecosystem
## Disclosure Policy
The `cobra` maintainers follow a coordinated disclosure process:
1. Security vulnerabilities will be addressed as quickly as possible.
2. A CVE (Common Vulnerabilities and Exposures) identifier will be requested for significant vulnerabilities
that are within `cobra` itself.
3. Once a fix is ready, the maintainers will:
- Release a new version containing the fix.
- Update the security advisory with details about the vulnerability.
- Credit the reporter (unless they wish to remain anonymous).
- Credit the fixer (unless they wish to remain anonymous, this may be the same as the reporter).
- Announce the vulnerability through appropriate channels
(GitHub Security Advisory, mailing lists, GitHub Releases, etc.)
## Supported Versions
Security fixes will typically only be released for the most recent major release.
## Upstream Security Issues
`cobra` generally will not accept vulnerability reports that originate in upstream
dependencies. I.e., if there is a problem in Go code that `cobra` depends on,
it is best to engage that project's maintainers and owners.
This security policy primarily pertains only to `cobra` itself but if you believe you've
identified a problem that originates in an upstream dependency and is being widely
distributed by `cobra`, please follow the disclosure procedure above: the `cobra`
maintainers will work with you to determine the severity and ecosystem impact.
## Security Updates and CVEs
Information about known security vulnerabilities and CVEs affecting `cobra` will
be published as GitHub Security Advisories at
https://github.com/spf13/cobra/security/advisories.
All users are encouraged to watch the repository and upgrade promptly when
security releases are published.
## `cobra` Security Best Practices for Users
When using `cobra` in your CLIs, the `cobra` maintainers recommend the following:
1. Always use the latest version of `cobra`.
2. [Use Go modules](https://go.dev/blog/using-go-modules) for dependency management.
3. Always use the latest possible version of Go.
## Security Best Practices for Contributors
When contributing to `cobra`:
1. Be mindful of security implications when adding new features or modifying existing ones.
2. Be aware of `cobra`'s extremely large reach: it is used in nearly every Go CLI
(like Kubernetes, Docker, Prometheus, etc. etc.)
3. Write tests that explicitly cover edge cases and potential issues.
4. If you discover a security issue while working on `cobra`, please report it
following the process above rather than opening a public pull request or issue that
addresses the vulnerability.
5. Take personal sec-ops seriously and secure your GitHub account: use [two-factor authentication](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa),
[sign your commits with a GPG or SSH key](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification),
etc.
## Acknowledgments
The `cobra` maintainers would like to thank all security researchers and
community members who help keep cobra, its users, and the entire Go ecosystem secure through responsible disclosures!!
---
*This security policy is inspired by the [Open Web Application Security Project (OWASP)](https://owasp.org/) guidelines and security best practices.*

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -17,14 +17,15 @@ package cobra
import ( import (
"fmt" "fmt"
"os" "os"
"strings"
) )
const ( const (
activeHelpMarker = "_activeHelp_ " activeHelpMarker = "_activeHelp_ "
// The below values should not be changed: programs will be using them explicitly // The below values should not be changed: programs will be using them explicitly
// in their user documentation, and users will be using them explicitly. // in their user documentation, and users will be using them explicitly.
activeHelpEnvVarSuffix = "ACTIVE_HELP" activeHelpEnvVarSuffix = "_ACTIVE_HELP"
activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
activeHelpGlobalDisable = "0" activeHelpGlobalDisable = "0"
) )
@ -35,13 +36,13 @@ const (
// This function can be called multiple times before and/or after completions are added to // This function can be called multiple times before and/or after completions are added to
// the array. Each time this function is called with the same array, the new // the array. Each time this function is called with the same array, the new
// ActiveHelp line will be shown below the previous ones when completion is triggered. // ActiveHelp line will be shown below the previous ones when completion is triggered.
func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion { func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr)) return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
} }
// GetActiveHelpConfig returns the value of the ActiveHelp environment variable // GetActiveHelpConfig returns the value of the ActiveHelp environment variable
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper // <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
// case, with all non-ASCII-alphanumeric characters replaced by `_`. // case, with all - replaced by _.
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP // It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
// is set to "0". // is set to "0".
func GetActiveHelpConfig(cmd *Command) string { func GetActiveHelpConfig(cmd *Command) string {
@ -54,7 +55,9 @@ func GetActiveHelpConfig(cmd *Command) string {
// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment // 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 // variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. // root command in upper case, with all - replaced by _.
func activeHelpEnvVar(name string) string { func activeHelpEnvVar(name string) string {
return configEnvVar(name, activeHelpEnvVarSuffix) // 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, "-", "_")
} }

View file

@ -2,30 +2,28 @@
Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion. Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion.
For example, For example,
```
```console bash-5.1$ helm repo add [tab]
$ helm repo add [tab]
You must choose a name for the repo you are adding. You must choose a name for the repo you are adding.
$ bin/helm package [tab] bash-5.1$ bin/helm package [tab]
Please specify the path to the chart to package Please specify the path to the chart to package
$ bin/helm package [tab][tab] bash-5.1$ bin/helm package [tab][tab]
bin/ internal/ scripts/ pkg/ testdata/ bin/ internal/ scripts/ pkg/ testdata/
``` ```
**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program. **Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.
## Supported shells ## Supported shells
Active Help is currently only supported for the following shells: Active Help is currently only supported for the following shells:
- Bash (using [bash completion V2](completions/_index.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed. - Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.
- Zsh - Zsh
## Adding Active Help messages ## Adding Active Help messages
As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](completions/_index.md). As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md).
Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details. Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.
@ -41,8 +39,8 @@ cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return addRepo(args) return addRepo(args)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var comps []cobra.Completion var comps []string
if len(args) == 0 { if len(args) == 0 {
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
} else if len(args) == 1 { } else if len(args) == 1 {
@ -54,28 +52,24 @@ cmd := &cobra.Command{
}, },
} }
``` ```
The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior: The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior:
```
```console bash-5.1$ helm repo add [tab]
$ helm repo add [tab]
You must choose a name for the repo you are adding You must choose a name for the repo you are adding
$ helm repo add grafana [tab] bash-5.1$ helm repo add grafana [tab]
You must specify the URL for the repo you are adding You must specify the URL for the repo you are adding
$ helm repo add grafana https://grafana.github.io/helm-charts [tab] bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
This command does not take any more arguments This command does not take any more arguments
``` ```
**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions. **Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.
### Active Help for flags ### Active Help for flags
Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example: Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:
```go ```go
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { _ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 2 { if len(args) != 2 {
return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
} }
@ -83,12 +77,11 @@ _ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []st
}) })
``` ```
The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag. The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.
```
```console bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
$ bin/helm install myrelease --version 2.0.[tab]
You must first specify the chart to install before the --version flag can be completed You must first specify the chart to install before the --version flag can be completed
$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab] bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
2.0.1 2.0.2 2.0.3 2.0.1 2.0.2 2.0.3
``` ```
@ -99,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 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 variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your
program in uppercase with any non-ASCII-alphanumeric characters replaced by an `_`. The variable should be set by the user to whatever program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever
Active Help configuration values are supported by the program. 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 For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user
@ -110,12 +103,11 @@ Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function an
should or should not be added (instead of reading the environment variable directly). should or should not be added (instead of reading the environment variable directly).
For example: For example:
```go ```go
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
activeHelpLevel := cobra.GetActiveHelpConfig(cmd) activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
var comps []cobra.Completion var comps []string
if len(args) == 0 { if len(args) == 0 {
if activeHelpLevel != "off" { if activeHelpLevel != "off" {
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
@ -132,13 +124,11 @@ ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([
return comps, cobra.ShellCompDirectiveNoFileComp return comps, cobra.ShellCompDirectiveNoFileComp
}, },
``` ```
**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly. **Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.
**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to. **Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.
**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. **Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string.
## Active Help with Cobra's default completion command ## Active Help with Cobra's default completion command
Cobra provides a default `completion` command for programs that wish to use it. Cobra provides a default `completion` command for programs that wish to use it.
@ -148,11 +138,10 @@ details for your users.
## Debugging Active Help ## Debugging Active Help
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](completions/_index.md#debugging) for details. 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 non-ASCII-alphanumeric characters are 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 `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
```
```console
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER> $ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
bitnami/haproxy bitnami/haproxy
bitnami/harbor bitnami/harbor

View file

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

View file

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

View file

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

View file

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

View file

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

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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() __%[1]s_debug()
{ {
if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
echo "$*" >> "${BASH_COMP_DEBUG_FILE}" echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
fi fi
} }
@ -57,7 +57,7 @@ __%[1]s_get_completion_results() {
local requestComp lastParam lastChar args local requestComp lastParam lastChar args
# Prepare the command to request completions for the program. # Prepare the command to request completions for the program.
# Calling ${words[0]} instead of directly %[1]s allows handling aliases # Calling ${words[0]} instead of directly %[1]s allows to handle aliases
args=("${words[@]:1}") args=("${words[@]:1}")
requestComp="${words[0]} %[2]s ${args[*]}" requestComp="${words[0]} %[2]s ${args[*]}"
@ -65,7 +65,7 @@ __%[1]s_get_completion_results() {
lastChar=${lastParam:$((${#lastParam}-1)):1} lastChar=${lastParam:$((${#lastParam}-1)):1}
__%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" __%[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) # 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. # We add an extra empty parameter so we can indicate this to the go method.
__%[1]s_debug "Adding extra empty parameter" __%[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>) # When completing a flag with an = (e.g., %[1]s -n=<TAB>)
# bash focuses on the part after the =, so we need to remove # bash focuses on the part after the =, so we need to remove
# the flag part from $cur # the flag part from $cur
if [[ ${cur} == -*=* ]]; then if [[ "${cur}" == -*=* ]]; then
cur="${cur#*=}" cur="${cur#*=}"
fi fi
@ -87,7 +87,7 @@ __%[1]s_get_completion_results() {
directive=${out##*:} directive=${out##*:}
# Remove the directive # Remove the directive
out=${out%%:*} out=${out%%:*}
if [[ ${directive} == "${out}" ]]; then if [ "${directive}" = "${out}" ]; then
# There is not directive specified # There is not directive specified
directive=0 directive=0
fi fi
@ -101,36 +101,22 @@ __%[1]s_process_completion_results() {
local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveNoFileComp=%[5]d
local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterFileExt=%[6]d
local shellCompDirectiveFilterDirs=%[7]d local shellCompDirectiveFilterDirs=%[7]d
local shellCompDirectiveKeepOrder=%[8]d
if (((directive & shellCompDirectiveError) != 0)); then if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
# Error code. No completion. # Error code. No completion.
__%[1]s_debug "Received error from custom completion go code" __%[1]s_debug "Received error from custom completion go code"
return return
else else
if (((directive & shellCompDirectiveNoSpace) != 0)); then if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
if [[ $(type -t compopt) == builtin ]]; then if [[ $(type -t compopt) = "builtin" ]]; then
__%[1]s_debug "Activating no space" __%[1]s_debug "Activating no space"
compopt -o nospace compopt -o nospace
else else
__%[1]s_debug "No space directive not supported in this version of bash" __%[1]s_debug "No space directive not supported in this version of bash"
fi fi
fi fi
if (((directive & shellCompDirectiveKeepOrder) != 0)); then if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
if [[ $(type -t compopt) == builtin ]]; 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" __%[1]s_debug "Activating no file completion"
compopt +o default compopt +o default
else else
@ -144,9 +130,9 @@ __%[1]s_process_completion_results() {
local activeHelp=() local activeHelp=()
__%[1]s_extract_activeHelp __%[1]s_extract_activeHelp
if (((directive & shellCompDirectiveFilterFileExt) != 0)); then if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
# File extension filtering # File extension filtering
local fullFilter="" filter filteringCmd local fullFilter filter filteringCmd
# Do not use quotes around the $completions variable or else newline # Do not use quotes around the $completions variable or else newline
# characters will be kept. # characters will be kept.
@ -157,12 +143,13 @@ __%[1]s_process_completion_results() {
filteringCmd="_filedir $fullFilter" filteringCmd="_filedir $fullFilter"
__%[1]s_debug "File filtering command: $filteringCmd" __%[1]s_debug "File filtering command: $filteringCmd"
$filteringCmd $filteringCmd
elif (((directive & shellCompDirectiveFilterDirs) != 0)); then elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
# File completion for directories only # File completion for directories only
# Use printf to strip any trailing newline
local subdir local subdir
subdir=${completions[0]} subdir=$(printf "%%s" "${completions[0]}")
if [[ -n $subdir ]]; then if [ -n "$subdir" ]; then
__%[1]s_debug "Listing directories in $subdir" __%[1]s_debug "Listing directories in $subdir"
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
else else
@ -177,94 +164,41 @@ __%[1]s_process_completion_results() {
__%[1]s_handle_special_char "$cur" = __%[1]s_handle_special_char "$cur" =
# Print the activeHelp statements before we finish # Print the activeHelp statements before we finish
__%[1]s_handle_activeHelp if [ ${#activeHelp[*]} -ne 0 ]; then
} printf "\n";
printf "%%s\n" "${activeHelp[@]}"
printf "\n"
__%[1]s_handle_activeHelp() { # The prompt format is only available from bash 4.4.
# Print the activeHelp statements # We test if it is available before using it.
if ((${#activeHelp[*]} != 0)); then if (x=${PS1@P}) 2> /dev/null; then
if [ -z $COMP_TYPE ]; then printf "%%s" "${PS1@P}${COMP_LINE[@]}"
# Bash v3 does not set the COMP_TYPE variable. else
printf "\n"; # Can't print the prompt. Just print the
printf "%%s\n" "${activeHelp[@]}" # text the user had typed, it is workable enough.
printf "\n" printf "%%s" "${COMP_LINE[@]}"
__%[1]s_reprint_commandLine
return
fi fi
# Only print ActiveHelp on the second TAB press
if [ $COMP_TYPE -eq 63 ]; then
printf "\n"
printf "%%s\n" "${activeHelp[@]}"
if ((${#COMPREPLY[*]} == 0)); then
# When there are no completion choices from the program, file completion
# may kick in if the program has not disabled it; in such a case, we want
# to know if any files will match what the user typed, so that we know if
# there will be completions presented, so that we know how to handle ActiveHelp.
# To find out, we actually trigger the file completion ourselves;
# the call to _filedir will fill COMPREPLY if files match.
if (((directive & shellCompDirectiveNoFileComp) == 0)); then
__%[1]s_debug "Listing files"
_filedir
fi
fi
if ((${#COMPREPLY[*]} != 0)); then
# If there are completion choices to be shown, print a delimiter.
# Re-printing the command-line will automatically be done
# by the shell when it prints the completion choices.
printf -- "--"
else
# When there are no completion choices at all, we need
# to re-print the command-line since the shell will
# not be doing it itself.
__%[1]s_reprint_commandLine
fi
elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then
# For completion type: menu-complete/menu-complete-backward and insert-completions
# the completions are immediately inserted into the command-line, so we first
# print the activeHelp message and reprint the command-line since the shell won't.
printf "\n"
printf "%%s\n" "${activeHelp[@]}"
__%[1]s_reprint_commandLine
fi
fi
}
__%[1]s_reprint_commandLine() {
# The prompt format is only available from bash 4.4.
# We test if it is available before using it.
if (x=${PS1@P}) 2> /dev/null; then
printf "%%s" "${PS1@P}${COMP_LINE[@]}"
else
# Can't print the prompt. Just print the
# text the user had typed, it is workable enough.
printf "%%s" "${COMP_LINE[@]}"
fi fi
} }
# Separate activeHelp lines from real completions. # Separate activeHelp lines from real completions.
# Fills the $activeHelp and $completions arrays. # Fills the $activeHelp and $completions arrays.
__%[1]s_extract_activeHelp() { __%[1]s_extract_activeHelp() {
local activeHelpMarker="%[9]s" local activeHelpMarker="%[8]s"
local endIndex=${#activeHelpMarker} local endIndex=${#activeHelpMarker}
while IFS='' read -r comp; do while IFS='' read -r comp; do
[[ -z $comp ]] && continue if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then
if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
comp=${comp:endIndex} comp=${comp:endIndex}
__%[1]s_debug "ActiveHelp found: $comp" __%[1]s_debug "ActiveHelp found: $comp"
if [[ -n $comp ]]; then if [ -n "$comp" ]; then
activeHelp+=("$comp") activeHelp+=("$comp")
fi fi
else else
# Not an activeHelp line but a normal completion # Not an activeHelp line but a normal completion
completions+=("$comp") completions+=("$comp")
fi fi
done <<<"${out}" done < <(printf "%%s\n" "${out}")
} }
__%[1]s_handle_completion_types() { __%[1]s_handle_completion_types() {
@ -276,21 +210,16 @@ __%[1]s_handle_completion_types() {
# If the user requested inserting one completion at a time, or all # If the user requested inserting one completion at a time, or all
# completions at once on the command-line we must remove the descriptions. # completions at once on the command-line we must remove the descriptions.
# https://github.com/spf13/cobra/issues/1508 # https://github.com/spf13/cobra/issues/1508
local tab=$'\t' comp
# If there are no completions, we don't need to do anything while IFS='' read -r comp; do
(( ${#completions[@]} == 0 )) && return 0 [[ -z $comp ]] && continue
# Strip any description
local tab=$'\t' comp=${comp%%%%$tab*}
# Only consider the completions that match
# Strip any description and escape the completion to handled special characters if [[ $comp == "$cur"* ]]; then
IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}") COMPREPLY+=("$comp")
fi
# Only consider the completions that match done < <(printf "%%s\n" "${completions[@]}")
IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}")
# compgen looses the escaping so we need to escape all completions again since they will
# all be inserted on the command-line.
IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}")
;; ;;
*) *)
@ -301,25 +230,11 @@ __%[1]s_handle_completion_types() {
} }
__%[1]s_handle_standard_completion_case() { __%[1]s_handle_standard_completion_case() {
local tab=$'\t' local tab=$'\t' comp
# If there are no completions, we don't need to do anything
(( ${#completions[@]} == 0 )) && return 0
# Short circuit to optimize if we don't have descriptions # Short circuit to optimize if we don't have descriptions
if [[ "${completions[*]}" != *$tab* ]]; then if [[ "${completions[*]}" != *$tab* ]]; then
# First, escape the completions to handle special characters IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}")
# Only consider the completions that match what the user typed
IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}")
# compgen looses the escaping so, if there is only a single completion, we need to
# escape it again because it will be inserted on the command-line. If there are multiple
# completions, we don't want to escape them because they will be printed in a list
# and we don't want to show escape characters in that list.
if (( ${#COMPREPLY[@]} == 1 )); then
COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}")
fi
return 0 return 0
fi fi
@ -328,39 +243,23 @@ __%[1]s_handle_standard_completion_case() {
# Look for the longest completion so that we can format things nicely # Look for the longest completion so that we can format things nicely
while IFS='' read -r compline; do while IFS='' read -r compline; do
[[ -z $compline ]] && continue [[ -z $compline ]] && continue
# Strip any description before checking the length
# Before checking if the completion matches what the user typed, comp=${compline%%%%$tab*}
# we need to strip any description and escape the completion to handle special
# characters because those escape characters are part of what the user typed.
# Don't call "printf" in a sub-shell because it will be much slower
# since we are in a loop.
printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}")
# Only consider the completions that match # Only consider the completions that match
[[ $comp == "$cur"* ]] || continue [[ $comp == "$cur"* ]] || continue
# The completions matches. Add it to the list of full completions including
# its description. We don't escape the completion because it may get printed
# in a list if there are more than one and we don't want show escape characters
# in that list.
COMPREPLY+=("$compline") COMPREPLY+=("$compline")
# Strip any description before checking the length, and again, don't escape
# the completion because this length is only used when printing the completions
# in a list and we don't want show escape characters in that list.
comp=${compline%%%%$tab*}
if ((${#comp}>longest)); then if ((${#comp}>longest)); then
longest=${#comp} longest=${#comp}
fi fi
done < <(printf "%%s\n" "${completions[@]}") done < <(printf "%%s\n" "${completions[@]}")
# If there is a single completion left, remove the description text and escape any special characters # If there is a single completion left, remove the description text
if ((${#COMPREPLY[*]} == 1)); then if [ ${#COMPREPLY[*]} -eq 1 ]; then
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}") comp="${COMPREPLY[0]%%%%$tab*}"
__%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}" __%[1]s_debug "Removed description from single completion, which is now: ${comp}"
else COMPREPLY[0]=$comp
# Format the descriptions else # Format the descriptions
__%[1]s_format_comp_descriptions $longest __%[1]s_format_comp_descriptions $longest
fi fi
} }
@ -372,8 +271,8 @@ __%[1]s_handle_special_char()
if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
local word=${comp%%"${comp##*${char}}"} local word=${comp%%"${comp##*${char}}"}
local idx=${#COMPREPLY[*]} local idx=${#COMPREPLY[*]}
while ((--idx >= 0)); do while [[ $((--idx)) -ge 0 ]]; do
COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"}
done done
fi fi
} }
@ -399,7 +298,7 @@ __%[1]s_format_comp_descriptions()
# Make sure we can fit a description of at least 8 characters # Make sure we can fit a description of at least 8 characters
# if we are to align the descriptions. # if we are to align the descriptions.
if ((maxdesclength > 8)); then if [[ $maxdesclength -gt 8 ]]; then
# Add the proper number of spaces to align the descriptions # Add the proper number of spaces to align the descriptions
for ((i = ${#comp} ; i < longest ; i++)); do for ((i = ${#comp} ; i < longest ; i++)); do
comp+=" " comp+=" "
@ -411,8 +310,8 @@ __%[1]s_format_comp_descriptions()
# If there is enough space for any description text, # If there is enough space for any description text,
# truncate the descriptions that are too long for the shell width # truncate the descriptions that are too long for the shell width
if ((maxdesclength > 0)); then if [ $maxdesclength -gt 0 ]; then
if ((${#desc} > maxdesclength)); then if [ ${#desc} -gt $maxdesclength ]; then
desc=${desc:0:$(( maxdesclength - 1 ))} desc=${desc:0:$(( maxdesclength - 1 ))}
desc+="…" desc+="…"
fi fi
@ -433,9 +332,9 @@ __start_%[1]s()
# Call _init_completion from the bash-completion package # Call _init_completion from the bash-completion package
# to prepare the arguments properly # to prepare the arguments properly
if declare -F _init_completion >/dev/null 2>&1; then if declare -F _init_completion >/dev/null 2>&1; then
_init_completion -n =: || return _init_completion -n "=:" || return
else else
__%[1]s_init_completion -n =: || return __%[1]s_init_completion -n "=:" || return
fi fi
__%[1]s_debug __%[1]s_debug
@ -462,7 +361,7 @@ fi
# ex: ts=4 sw=4 et filetype=sh # ex: ts=4 sw=4 et filetype=sh
`, name, compCmd, `, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
activeHelpMarker)) activeHelpMarker))
} }

View file

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

View file

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

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -43,13 +43,12 @@ var initializers []func()
var finalizers []func() var finalizers []func()
const ( const (
defaultPrefixMatching = false defaultPrefixMatching = false
defaultCommandSorting = true defaultCommandSorting = true
defaultCaseInsensitive = false defaultCaseInsensitive = false
defaultTraverseRunHooks = false
) )
// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing // EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
// to automatically enable in CLI tools. // to automatically enable in CLI tools.
// Set this to true to enable it. // Set this to true to enable it.
var EnablePrefixMatching = defaultPrefixMatching var EnablePrefixMatching = defaultPrefixMatching
@ -61,10 +60,6 @@ var EnableCommandSorting = defaultCommandSorting
// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) // EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
var EnableCaseInsensitive = defaultCaseInsensitive 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 // MousetrapHelpText enables an information splash screen on Windows
// if the CLI is started from explorer.exe. // if the CLI is started from explorer.exe.
// To disable the mousetrap, just set this variable to blank string (""). // To disable the mousetrap, just set this variable to blank string ("").
@ -172,20 +167,16 @@ func appendIfNotPresent(s, stringToAppend string) string {
// rpad adds padding to the right of a string. // rpad adds padding to the right of a string.
func rpad(s string, padding int) string { func rpad(s string, padding int) string {
formattedString := fmt.Sprintf("%%-%ds", padding) template := fmt.Sprintf("%%-%ds", padding)
return fmt.Sprintf(formattedString, s) return fmt.Sprintf(template, s)
} }
func tmpl(text string) *tmplFunc { // tmpl executes the given template text on data, writing the result to w.
return &tmplFunc{ func tmpl(w io.Writer, text string, data interface{}) error {
tmpl: text, t := template.New("top")
fn: func(w io.Writer, data interface{}) error { t.Funcs(templateFuncs)
t := template.New("top") template.Must(t.Parse(text))
t.Funcs(templateFuncs) return t.Execute(w, data)
template.Must(t.Parse(text))
return t.Execute(w, data)
},
}
} }
// ld compares two strings and returns the levenshtein distance between them. // ld compares two strings and returns the levenshtein distance between them.
@ -197,6 +188,8 @@ func ld(s, t string, ignoreCase bool) int {
d := make([][]int, len(s)+1) d := make([][]int, len(s)+1)
for i := range d { for i := range d {
d[i] = make([]int, len(t)+1) d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i d[i][0] = i
} }
for j := range d[0] { for j := range d[0] {

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -15,11 +15,6 @@
package cobra package cobra
import ( import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing" "testing"
"text/template" "text/template"
) )
@ -45,257 +40,3 @@ func TestAddTemplateFunctions(t *testing.T) {
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got) 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)
}
})
}
}
// TestDeadcodeElimination checks that a simple program using cobra in its
// default configuration is linked taking full advantage of the linker's
// deadcode elimination step.
//
// If reflect.Value.MethodByName/reflect.Value.Method are reachable the
// linker will not always be able to prove that exported methods are
// unreachable, making deadcode elimination less effective. Using
// text/template and html/template makes reflect.Value.MethodByName
// reachable.
// Since cobra can use text/template templates this test checks that in its
// default configuration that code path can be proven to be unreachable by
// the linker.
//
// See also: https://github.com/spf13/cobra/pull/1956
func TestDeadcodeElimination(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("go tool nm fails on windows")
}
// check that a simple program using cobra in its default configuration is
// linked with deadcode elimination enabled.
const (
dirname = "test_deadcode"
progname = "test_deadcode_elimination"
)
_ = os.Mkdir(dirname, 0770)
defer os.RemoveAll(dirname)
filename := filepath.Join(dirname, progname+".go")
err := os.WriteFile(filename, []byte(`package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Version: "1.0",
Use: "example_program",
Short: "example_program - test fixture to check that deadcode elimination is allowed",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("hello world")
},
Aliases: []string{"alias1", "alias2"},
Example: "stringer --help",
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err)
os.Exit(1)
}
}
`), 0600)
if err != nil {
t.Fatalf("could not write test program: %v", err)
}
buf, err := exec.Command("go", "build", filename).CombinedOutput()
if err != nil {
t.Fatalf("could not compile test program: %s", string(buf))
}
defer os.Remove(progname)
buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput()
if err != nil {
t.Fatalf("could not run go tool nm: %v", err)
}
if strings.Contains(string(buf), "MethodByName") {
t.Error("compiled programs contains MethodByName symbol")
}
}

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -30,18 +30,12 @@ import (
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
) )
const ( const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
helpFlagName = "help"
helpCommandName = "help"
)
// FParseErrWhitelist configures Flag parse errors to be ignored // FParseErrWhitelist configures Flag parse errors to be ignored
type FParseErrWhitelist flag.ParseErrorsWhitelist type FParseErrWhitelist flag.ParseErrorsWhitelist
// Group Structure to manage groups for commands // Structure to manage groups for commands
type Group struct { type Group struct {
ID string ID string
Title string Title string
@ -53,7 +47,7 @@ type Group struct {
// definition to ensure usability. // definition to ensure usability.
type Command struct { type Command struct {
// Use is the one-line usage message. // Use is the one-line usage message.
// Recommended syntax is as follows: // Recommended syntax is as follow:
// [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. // [ ] 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 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 // | indicates mutually exclusive information. You can use the argument to the left of the separator or the
@ -83,11 +77,11 @@ type Command struct {
Example string Example string
// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
ValidArgs []Completion ValidArgs []string
// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.
// It is a dynamic version of using ValidArgs. // It is a dynamic version of using ValidArgs.
// Only one of ValidArgs and ValidArgsFunction can be used for a command. // Only one of ValidArgs and ValidArgsFunction can be used for a command.
ValidArgsFunction CompletionFunc ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
// Expected arguments // Expected arguments
Args PositionalArgs Args PositionalArgs
@ -105,7 +99,7 @@ type Command struct {
Deprecated string Deprecated string
// Annotations are key/value pairs that can be used by applications to identify or // Annotations are key/value pairs that can be used by applications to identify or
// group commands or set special options. // group commands.
Annotations map[string]string Annotations map[string]string
// Version defines the version for this command. If this value is non-empty and the command does not // Version defines the version for this command. If this value is non-empty and the command does not
@ -121,8 +115,6 @@ type Command struct {
// * PostRun() // * PostRun()
// * PersistentPostRun() // * PersistentPostRun()
// All functions get the same args, the arguments after the command name. // 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: children of this command will inherit and execute.
PersistentPreRun func(cmd *Command, args []string) PersistentPreRun func(cmd *Command, args []string)
@ -157,10 +149,8 @@ type Command struct {
// pflags contains persistent flags. // pflags contains persistent flags.
pflags *flag.FlagSet pflags *flag.FlagSet
// lflags contains local flags. // 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 lflags *flag.FlagSet
// iflags contains inherited flags. // 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 iflags *flag.FlagSet
// parentsPflags is all persistent flags of cmd's parents. // parentsPflags is all persistent flags of cmd's parents.
parentsPflags *flag.FlagSet parentsPflags *flag.FlagSet
@ -171,12 +161,12 @@ type Command struct {
// usageFunc is usage func defined by user. // usageFunc is usage func defined by user.
usageFunc func(*Command) error usageFunc func(*Command) error
// usageTemplate is usage template defined by user. // usageTemplate is usage template defined by user.
usageTemplate *tmplFunc usageTemplate string
// flagErrorFunc is func defined by user and it's called when the parsing of // flagErrorFunc is func defined by user and it's called when the parsing of
// flags returns an error. // flags returns an error.
flagErrorFunc func(*Command, error) error flagErrorFunc func(*Command, error) error
// helpTemplate is help template defined by user. // helpTemplate is help template defined by user.
helpTemplate *tmplFunc helpTemplate string
// helpFunc is help func defined by user. // helpFunc is help func defined by user.
helpFunc func(*Command, []string) helpFunc func(*Command, []string)
// helpCommand is command with usage 'help'. If it's not defined by user, // helpCommand is command with usage 'help'. If it's not defined by user,
@ -189,10 +179,7 @@ type Command struct {
completionCommandGroupID string completionCommandGroupID string
// versionTemplate is the version template defined by user. // versionTemplate is the version template defined by user.
versionTemplate *tmplFunc 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 is a reader defined by the user that replaces stdin
inReader io.Reader inReader io.Reader
@ -284,7 +271,6 @@ func (c *Command) SetArgs(a []string) {
// SetOutput sets the destination for usage and error messages. // SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used. // If output is nil, os.Stderr is used.
//
// Deprecated: Use SetOut and/or SetErr instead // Deprecated: Use SetOut and/or SetErr instead
func (c *Command) SetOutput(output io.Writer) { func (c *Command) SetOutput(output io.Writer) {
c.outWriter = output c.outWriter = output
@ -316,11 +302,7 @@ func (c *Command) SetUsageFunc(f func(*Command) error) {
// SetUsageTemplate sets usage template. Can be defined by Application. // SetUsageTemplate sets usage template. Can be defined by Application.
func (c *Command) SetUsageTemplate(s string) { func (c *Command) SetUsageTemplate(s string) {
if s == "" { c.usageTemplate = s
c.usageTemplate = nil
return
}
c.usageTemplate = tmpl(s)
} }
// SetFlagErrorFunc sets a function to generate an error when flag parsing // SetFlagErrorFunc sets a function to generate an error when flag parsing
@ -339,7 +321,7 @@ func (c *Command) SetHelpCommand(cmd *Command) {
c.helpCommand = cmd c.helpCommand = cmd
} }
// SetHelpCommandGroupID sets the group id of the help command. // SetHelpCommandGroup sets the group id of the help command.
func (c *Command) SetHelpCommandGroupID(groupID string) { func (c *Command) SetHelpCommandGroupID(groupID string) {
if c.helpCommand != nil { if c.helpCommand != nil {
c.helpCommand.GroupID = groupID c.helpCommand.GroupID = groupID
@ -348,7 +330,7 @@ func (c *Command) SetHelpCommandGroupID(groupID string) {
c.helpCommandGroupID = groupID c.helpCommandGroupID = groupID
} }
// SetCompletionCommandGroupID sets the group id of the completion command. // SetCompletionCommandGroup sets the group id of the completion command.
func (c *Command) SetCompletionCommandGroupID(groupID string) { func (c *Command) SetCompletionCommandGroupID(groupID string) {
// completionCommandGroupID is used if no completion command is defined by the user // completionCommandGroupID is used if no completion command is defined by the user
c.Root().completionCommandGroupID = groupID c.Root().completionCommandGroupID = groupID
@ -356,25 +338,12 @@ func (c *Command) SetCompletionCommandGroupID(groupID string) {
// SetHelpTemplate sets help template to be used. Application can use it to set custom template. // SetHelpTemplate sets help template to be used. Application can use it to set custom template.
func (c *Command) SetHelpTemplate(s string) { func (c *Command) SetHelpTemplate(s string) {
if s == "" { c.helpTemplate = s
c.helpTemplate = nil
return
}
c.helpTemplate = tmpl(s)
} }
// SetVersionTemplate sets version template to be used. Application can use it to set custom template. // SetVersionTemplate sets version template to be used. Application can use it to set custom template.
func (c *Command) SetVersionTemplate(s string) { func (c *Command) SetVersionTemplate(s string) {
if s == "" { c.versionTemplate = s
c.versionTemplate = nil
return
}
c.versionTemplate = tmpl(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. // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
@ -450,8 +419,7 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
} }
return func(c *Command) error { return func(c *Command) error {
c.mergePersistentFlags() c.mergePersistentFlags()
fn := c.getUsageTemplateFunc() err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
err := fn(c.OutOrStderr(), c)
if err != nil { if err != nil {
c.PrintErrln(err) c.PrintErrln(err)
} }
@ -459,19 +427,6 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
} }
} }
// getUsageTemplateFunc returns the usage template function for the command
// going up the command tree if necessary.
func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {
if c.usageTemplate != nil {
return c.usageTemplate.fn
}
if c.HasParent() {
return c.parent.getUsageTemplateFunc()
}
return defaultUsageFunc
}
// Usage puts out the usage for the command. // Usage puts out the usage for the command.
// Used when a user provides invalid input. // Used when a user provides invalid input.
// Can be defined by user by overriding UsageFunc. // Can be defined by user by overriding UsageFunc.
@ -490,30 +445,15 @@ func (c *Command) HelpFunc() func(*Command, []string) {
} }
return func(c *Command, a []string) { return func(c *Command, a []string) {
c.mergePersistentFlags() c.mergePersistentFlags()
fn := c.getHelpTemplateFunc()
// The help should be sent to stdout // The help should be sent to stdout
// See https://github.com/spf13/cobra/issues/1002 // See https://github.com/spf13/cobra/issues/1002
err := fn(c.OutOrStdout(), c) err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
if err != nil { if err != nil {
c.PrintErrln(err) c.PrintErrln(err)
} }
} }
} }
// getHelpTemplateFunc returns the help template function for the command
// going up the command tree if necessary.
func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {
if c.helpTemplate != nil {
return c.helpTemplate.fn
}
if c.HasParent() {
return c.parent.getHelpTemplateFunc()
}
return defaultHelpFunc
}
// Help puts out the help for the command. // Help puts out the help for the command.
// Used when a user calls help [command]. // Used when a user calls help [command].
// Can be defined by user by overriding HelpFunc. // Can be defined by user by overriding HelpFunc.
@ -588,67 +528,71 @@ func (c *Command) NamePadding() int {
} }
// UsageTemplate returns usage template for the command. // UsageTemplate returns usage template for the command.
// This function is kept for backwards-compatibility reasons.
func (c *Command) UsageTemplate() string { func (c *Command) UsageTemplate() string {
if c.usageTemplate != nil { if c.usageTemplate != "" {
return c.usageTemplate.tmpl return c.usageTemplate
} }
if c.HasParent() { if c.HasParent() {
return c.parent.UsageTemplate() return c.parent.UsageTemplate()
} }
return defaultUsageTemplate return `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
} }
// HelpTemplate return help template for the command. // HelpTemplate return help template for the command.
// This function is kept for backwards-compatibility reasons.
func (c *Command) HelpTemplate() string { func (c *Command) HelpTemplate() string {
if c.helpTemplate != nil { if c.helpTemplate != "" {
return c.helpTemplate.tmpl return c.helpTemplate
} }
if c.HasParent() { if c.HasParent() {
return c.parent.HelpTemplate() return c.parent.HelpTemplate()
} }
return defaultHelpTemplate return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
} }
// VersionTemplate return version template for the command. // VersionTemplate return version template for the command.
// This function is kept for backwards-compatibility reasons.
func (c *Command) VersionTemplate() string { func (c *Command) VersionTemplate() string {
if c.versionTemplate != nil { if c.versionTemplate != "" {
return c.versionTemplate.tmpl return c.versionTemplate
} }
if c.HasParent() { if c.HasParent() {
return c.parent.VersionTemplate() return c.parent.VersionTemplate()
} }
return defaultVersionTemplate return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
} `
// getVersionTemplateFunc returns the version template function for the command
// going up the command tree if necessary.
func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {
if c.versionTemplate != nil {
return c.versionTemplate.fn
}
if c.HasParent() {
return c.parent.getVersionTemplateFunc()
}
return defaultVersionFunc
}
// 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 { func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
@ -711,44 +655,20 @@ Loop:
// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like // 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]). // openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
// Special care needs to be taken not to remove a flag value. func argsMinusFirstX(args []string, x string) []string {
func (c *Command) argsMinusFirstX(args []string, x string) []string { for i, y := range args {
if len(args) == 0 { if x == y {
return args ret := []string{}
} ret = append(ret, args[:i]...)
c.mergePersistentFlags() ret = append(ret, args[i+1:]...)
flags := c.Flags() return ret
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 return args
} }
func isFlagArg(arg string) bool { func isFlagArg(arg string) bool {
return ((len(arg) >= 3 && arg[0:2] == "--") || return ((len(arg) >= 3 && arg[1] == '-') ||
(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
} }
@ -766,7 +686,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) {
cmd := c.findNext(nextSubCmd) cmd := c.findNext(nextSubCmd)
if cmd != nil { if cmd != nil {
return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd)) return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
} }
return c, innerArgs return c, innerArgs
} }
@ -785,14 +705,14 @@ func (c *Command) findSuggestions(arg string) string {
if c.SuggestionsMinimumDistance <= 0 { if c.SuggestionsMinimumDistance <= 0 {
c.SuggestionsMinimumDistance = 2 c.SuggestionsMinimumDistance = 2
} }
var sb strings.Builder suggestionsString := ""
if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
sb.WriteString("\n\nDid you mean this?\n") suggestionsString += "\n\nDid you mean this?\n"
for _, s := range suggestions { for _, s := range suggestions {
_, _ = fmt.Fprintf(&sb, "\t%v\n", s) suggestionsString += fmt.Sprintf("\t%v\n", s)
} }
} }
return sb.String() return suggestionsString
} }
func (c *Command) findNext(next string) *Command { func (c *Command) findNext(next string) *Command {
@ -808,9 +728,7 @@ func (c *Command) findNext(next string) *Command {
} }
if len(matches) == 1 { if len(matches) == 1 {
// Temporarily disable gosec G602, which produces a false positive. return matches[0]
// See https://github.com/securego/gosec/issues/1005.
return matches[0] // #nosec G602
} }
return nil return nil
@ -904,7 +822,7 @@ func (c *Command) ArgsLenAtDash() int {
func (c *Command) execute(a []string) (err error) { func (c *Command) execute(a []string) (err error) {
if c == nil { 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 { if len(c.Deprecated) > 0 {
@ -923,7 +841,7 @@ func (c *Command) execute(a []string) (err error) {
// If help is called, regardless of other flags, return we want help. // If help is called, regardless of other flags, return we want help.
// Also say we need help if the command isn't runnable. // Also say we need help if the command isn't runnable.
helpVal, err := c.Flags().GetBool(helpFlagName) helpVal, err := c.Flags().GetBool("help")
if err != nil { if err != nil {
// should be impossible to get here as we always declare a help // should be impossible to get here as we always declare a help
// flag in InitDefaultHelpFlag() // flag in InitDefaultHelpFlag()
@ -943,8 +861,7 @@ func (c *Command) execute(a []string) (err error) {
return err return err
} }
if versionVal { if versionVal {
fn := c.getVersionTemplateFunc() err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)
err := fn(c.OutOrStdout(), c)
if err != nil { if err != nil {
c.Println(err) c.Println(err)
} }
@ -969,31 +886,15 @@ func (c *Command) execute(a []string) (err error) {
return err return err
} }
parents := make([]*Command, 0, 5)
for p := c; p != nil; p = p.Parent() { 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 p.PersistentPreRunE != nil {
if err := p.PersistentPreRunE(c, argWoFlags); err != nil { if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
return err return err
} }
if !EnableTraverseRunHooks { break
break
}
} else if p.PersistentPreRun != nil { } else if p.PersistentPreRun != nil {
p.PersistentPreRun(c, argWoFlags) p.PersistentPreRun(c, argWoFlags)
if !EnableTraverseRunHooks { break
break
}
} }
} }
if c.PreRunE != nil { if c.PreRunE != nil {
@ -1030,14 +931,10 @@ func (c *Command) execute(a []string) (err error) {
if err := p.PersistentPostRunE(c, argWoFlags); err != nil { if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
return err return err
} }
if !EnableTraverseRunHooks { break
break
}
} else if p.PersistentPostRun != nil { } else if p.PersistentPostRun != nil {
p.PersistentPostRun(c, argWoFlags) p.PersistentPostRun(c, argWoFlags)
if !EnableTraverseRunHooks { break
break
}
} }
} }
@ -1098,6 +995,8 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// initialize help at the last point to allow for user overriding // initialize help at the last point to allow for user overriding
c.InitDefaultHelpCmd() c.InitDefaultHelpCmd()
// initialize completion at the last point to allow for user overriding
c.InitDefaultCompletionCmd()
args := c.args args := c.args
@ -1106,16 +1005,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
args = os.Args[1:] args = os.Args[1:]
} }
// initialize the __complete command to be used for shell completion // initialize the hidden command to be used for shell completion
c.initCompleteCmd(args) c.initCompleteCmd(args)
// initialize the default completion command
c.InitDefaultCompletionCmd(args...)
// Now that all commands have been created, let's make sure all groups
// are properly created also
c.checkCommandGroups()
var flags []string var flags []string
if c.TraverseChildren { if c.TraverseChildren {
cmd, flags, err = c.Traverse(args) cmd, flags, err = c.Traverse(args)
@ -1128,7 +1020,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
c = cmd c = cmd
} }
if !c.SilenceErrors { if !c.SilenceErrors {
c.PrintErrln(c.ErrPrefix(), err.Error()) c.PrintErrln("Error:", err.Error())
c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
} }
return c, err return c, err
@ -1157,7 +1049,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// If root command has SilenceErrors flagged, // If root command has SilenceErrors flagged,
// all subcommands should respect it // all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors { if !cmd.SilenceErrors && !c.SilenceErrors {
c.PrintErrln(cmd.ErrPrefix(), err.Error()) c.PrintErrln("Error:", err.Error())
} }
// If root command has SilenceUsage flagged, // If root command has SilenceUsage flagged,
@ -1200,34 +1092,20 @@ func (c *Command) ValidateRequiredFlags() error {
return nil 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. // InitDefaultHelpFlag adds default help flag to c.
// It is called automatically by executing the c or by calling help and usage. // It is called automatically by executing the c or by calling help and usage.
// If c already has help flag, it will do nothing. // If c already has help flag, it will do nothing.
func (c *Command) InitDefaultHelpFlag() { func (c *Command) InitDefaultHelpFlag() {
c.mergePersistentFlags() c.mergePersistentFlags()
if c.Flags().Lookup(helpFlagName) == nil { if c.Flags().Lookup("help") == nil {
usage := "help for " usage := "help for "
name := c.DisplayName() if c.Name() == "" {
if name == "" {
usage += "this command" usage += "this command"
} else { } else {
usage += name usage += c.Name()
} }
c.Flags().BoolP(helpFlagName, "h", false, usage) c.Flags().BoolP("help", "h", false, usage)
_ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"}) _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
} }
} }
@ -1246,7 +1124,7 @@ func (c *Command) InitDefaultVersionFlag() {
if c.Name() == "" { if c.Name() == "" {
usage += "this command" usage += "this command"
} else { } else {
usage += c.DisplayName() usage += c.Name()
} }
if c.Flags().ShorthandLookup("v") == nil { if c.Flags().ShorthandLookup("v") == nil {
c.Flags().BoolP("version", "v", false, usage) c.Flags().BoolP("version", "v", false, usage)
@ -1270,9 +1148,9 @@ func (c *Command) InitDefaultHelpCmd() {
Use: "help [command]", Use: "help [command]",
Short: "Help about any command", Short: "Help about any command",
Long: `Help provides help for any command in the application. Long: `Help provides help for any command in the application.
Simply type ` + c.DisplayName() + ` help [path to command] for full details.`, Simply type ` + c.Name() + ` help [path to command] for full details.`,
ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
var completions []Completion var completions []string
cmd, _, e := c.Root().Find(args) cmd, _, e := c.Root().Find(args)
if e != nil { if e != nil {
return nil, ShellCompDirectiveNoFileComp return nil, ShellCompDirectiveNoFileComp
@ -1284,7 +1162,7 @@ Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
for _, subCmd := range cmd.Commands() { for _, subCmd := range cmd.Commands() {
if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {
if strings.HasPrefix(subCmd.Name(), toComplete) { if strings.HasPrefix(subCmd.Name(), toComplete) {
completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
} }
} }
} }
@ -1296,11 +1174,6 @@ Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
c.Printf("Unknown help topic %#q\n", args) c.Printf("Unknown help topic %#q\n", args)
CheckErr(c.Root().Usage()) CheckErr(c.Root().Usage())
} else { } else {
// FLow the context down to be used in help text
if cmd.ctx == nil {
cmd.ctx = c.ctx
}
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
CheckErr(cmd.Help()) CheckErr(cmd.Help())
@ -1345,6 +1218,10 @@ func (c *Command) AddCommand(cmds ...*Command) {
panic("Command can't be a child of itself") panic("Command can't be a child of itself")
} }
cmds[i].parent = c 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 // update max lengths
usageLen := len(x.Use) usageLen := len(x.Use)
if usageLen > c.commandsMaxUseLen { if usageLen > c.commandsMaxUseLen {
@ -1382,7 +1259,7 @@ func (c *Command) AllChildCommandsHaveGroup() bool {
return true return true
} }
// ContainsGroup return if groupID exists in the list of command groups. // ContainGroups return if groupID exists in the list of command groups.
func (c *Command) ContainsGroup(groupID string) bool { func (c *Command) ContainsGroup(groupID string) bool {
for _, x := range c.commandgroups { for _, x := range c.commandgroups {
if x.ID == groupID { if x.ID == groupID {
@ -1466,26 +1343,16 @@ func (c *Command) CommandPath() string {
if c.HasParent() { if c.HasParent() {
return c.Parent().CommandPath() + " " + c.Name() return c.Parent().CommandPath() + " " + c.Name()
} }
return c.DisplayName()
}
// DisplayName returns the name to display in help text. Returns command Name()
// If CommandDisplayNameAnnoation is not set
func (c *Command) DisplayName() string {
if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
return displayName
}
return c.Name() return c.Name()
} }
// UseLine puts out the full usage for a given command (including parents). // UseLine puts out the full usage for a given command (including parents).
func (c *Command) UseLine() string { func (c *Command) UseLine() string {
var useline string var useline string
use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)
if c.HasParent() { if c.HasParent() {
useline = c.parent.CommandPath() + " " + use useline = c.parent.CommandPath() + " " + c.Use
} else { } else {
useline = use useline = c.Use
} }
if c.DisableFlagsInUseLine { if c.DisableFlagsInUseLine {
return useline return useline
@ -1687,7 +1554,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f
// to this command (local and persistent declared here and by all parents). // to this command (local and persistent declared here and by all parents).
func (c *Command) Flags() *flag.FlagSet { func (c *Command) Flags() *flag.FlagSet {
if c.flags == nil { if c.flags == nil {
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
if c.flagErrorBuf == nil { if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf = new(bytes.Buffer)
} }
@ -1698,11 +1565,10 @@ func (c *Command) Flags() *flag.FlagSet {
} }
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. // 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 { func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
persistentFlags := c.PersistentFlags() persistentFlags := c.PersistentFlags()
out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.LocalFlags().VisitAll(func(f *flag.Flag) { c.LocalFlags().VisitAll(func(f *flag.Flag) {
if persistentFlags.Lookup(f.Name) == nil { if persistentFlags.Lookup(f.Name) == nil {
out.AddFlag(f) out.AddFlag(f)
@ -1712,12 +1578,11 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
} }
// LocalFlags returns the local FlagSet specifically set in the current command. // 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 { func (c *Command) LocalFlags() *flag.FlagSet {
c.mergePersistentFlags() c.mergePersistentFlags()
if c.lflags == nil { if c.lflags == nil {
c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
if c.flagErrorBuf == nil { if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf = new(bytes.Buffer)
} }
@ -1740,12 +1605,11 @@ func (c *Command) LocalFlags() *flag.FlagSet {
} }
// InheritedFlags returns all flags which were inherited from parent commands. // 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 { func (c *Command) InheritedFlags() *flag.FlagSet {
c.mergePersistentFlags() c.mergePersistentFlags()
if c.iflags == nil { if c.iflags == nil {
c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
if c.flagErrorBuf == nil { if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf = new(bytes.Buffer)
} }
@ -1766,7 +1630,6 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
} }
// NonInheritedFlags returns all flags which were not inherited from parent commands. // 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 { func (c *Command) NonInheritedFlags() *flag.FlagSet {
return c.LocalFlags() return c.LocalFlags()
} }
@ -1774,7 +1637,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet {
// PersistentFlags returns the persistent FlagSet specifically set in the current command. // PersistentFlags returns the persistent FlagSet specifically set in the current command.
func (c *Command) PersistentFlags() *flag.FlagSet { func (c *Command) PersistentFlags() *flag.FlagSet {
if c.pflags == nil { if c.pflags == nil {
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
if c.flagErrorBuf == nil { if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf = new(bytes.Buffer)
} }
@ -1787,9 +1650,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
func (c *Command) ResetFlags() { func (c *Command) ResetFlags() {
c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf = new(bytes.Buffer)
c.flagErrorBuf.Reset() c.flagErrorBuf.Reset()
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.flags.SetOutput(c.flagErrorBuf) c.flags.SetOutput(c.flagErrorBuf)
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.pflags.SetOutput(c.flagErrorBuf) c.pflags.SetOutput(c.flagErrorBuf)
c.lflags = nil c.lflags = nil
@ -1906,7 +1769,7 @@ func (c *Command) mergePersistentFlags() {
// If c.parentsPflags == nil, it makes new. // If c.parentsPflags == nil, it makes new.
func (c *Command) updateParentsPflags() { func (c *Command) updateParentsPflags() {
if c.parentsPflags == nil { if c.parentsPflags == nil {
c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
c.parentsPflags.SetOutput(c.flagErrorBuf) c.parentsPflags.SetOutput(c.flagErrorBuf)
c.parentsPflags.SortFlags = false c.parentsPflags.SortFlags = false
} }
@ -1932,141 +1795,3 @@ func commandNameMatches(s string, t string) bool {
return s == t return s == t
} }
// tmplFunc holds a template and a function that will execute said template.
type tmplFunc struct {
tmpl string
fn func(io.Writer, interface{}) error
}
var defaultUsageTemplate = `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.
func defaultUsageFunc(w io.Writer, in interface{}) error {
c := in.(*Command)
fmt.Fprint(w, "Usage:")
if c.Runnable() {
fmt.Fprintf(w, "\n %s", c.UseLine())
}
if c.HasAvailableSubCommands() {
fmt.Fprintf(w, "\n %s [command]", c.CommandPath())
}
if len(c.Aliases) > 0 {
fmt.Fprintf(w, "\n\nAliases:\n")
fmt.Fprintf(w, " %s", c.NameAndAliases())
}
if c.HasExample() {
fmt.Fprintf(w, "\n\nExamples:\n")
fmt.Fprintf(w, "%s", c.Example)
}
if c.HasAvailableSubCommands() {
cmds := c.Commands()
if len(c.Groups()) == 0 {
fmt.Fprintf(w, "\n\nAvailable Commands:")
for _, subcmd := range cmds {
if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
}
}
} else {
for _, group := range c.Groups() {
fmt.Fprintf(w, "\n\n%s", group.Title)
for _, subcmd := range cmds {
if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
}
}
}
if !c.AllChildCommandsHaveGroup() {
fmt.Fprintf(w, "\n\nAdditional Commands:")
for _, subcmd := range cmds {
if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
}
}
}
}
}
if c.HasAvailableLocalFlags() {
fmt.Fprintf(w, "\n\nFlags:\n")
fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))
}
if c.HasAvailableInheritedFlags() {
fmt.Fprintf(w, "\n\nGlobal Flags:\n")
fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))
}
if c.HasHelpSubCommands() {
fmt.Fprintf(w, "\n\nAdditional help topics:")
for _, subcmd := range c.Commands() {
if subcmd.IsAdditionalHelpTopicCommand() {
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)
}
}
}
if c.HasAvailableSubCommands() {
fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath())
}
fmt.Fprintln(w)
return nil
}
var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.
func defaultHelpFunc(w io.Writer, in interface{}) error {
c := in.(*Command)
usage := c.Long
if usage == "" {
usage = c.Short
}
usage = trimRightSpace(usage)
if usage != "" {
fmt.Fprintln(w, usage)
fmt.Fprintln(w)
}
if c.Runnable() || c.HasSubCommands() {
fmt.Fprint(w, c.UsageString())
}
return nil
}
var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
`
// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.
func defaultVersionFunc(w io.Writer, in interface{}) error {
c := in.(*Command)
_, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version)
return err
}

View file

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

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -18,7 +18,7 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io" "io/ioutil"
"os" "os"
"reflect" "reflect"
"strings" "strings"
@ -366,71 +366,6 @@ func TestAliasPrefixMatching(t *testing.T) {
EnablePrefixMatching = defaultPrefixMatching 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",
Version: "1.0.0",
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")
checkStringContains(t, cmdHelp, "version for kubectl plugin")
}
// TestPluginWithSubCommands checks usage as plugin with sub commands.
func TestPluginWithSubCommands(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Version: "1.0.0",
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, "version 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, // TestChildSameName checks the correct behaviour of cobra in cases,
// when an application with name "foo" and with subcommand "foo" // when an application with name "foo" and with subcommand "foo"
// is executed with args "foo foo". // is executed with args "foo foo".
@ -503,7 +438,7 @@ func TestFlagLong(t *testing.T) {
output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two") output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")
if output != "" { if output != "" {
t.Errorf("Unexpected output: %v", output) t.Errorf("Unexpected output: %v", err)
} }
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
@ -540,7 +475,7 @@ func TestFlagShort(t *testing.T) {
output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two") output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")
if output != "" { if output != "" {
t.Errorf("Unexpected output: %v", output) t.Errorf("Unexpected output: %v", err)
} }
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
@ -569,7 +504,7 @@ func TestChildFlag(t *testing.T) {
output, err := executeCommand(rootCmd, "child", "-i7") output, err := executeCommand(rootCmd, "child", "-i7")
if output != "" { if output != "" {
t.Errorf("Unexpected output: %v", output) t.Errorf("Unexpected output: %v", err)
} }
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
@ -1018,49 +953,6 @@ func TestSetHelpCommand(t *testing.T) {
} }
} }
func TestSetHelpTemplate(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
rootCmd.SetHelpTemplate("WORKS {{.UseLine}}")
// Call the help on the root command and check the new template is used
got, err := executeCommand(rootCmd, "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := "WORKS " + rootCmd.UseLine()
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// Call the help on the child command and check
// the new template is inherited from the parent
got, err = executeCommand(rootCmd, "child", "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected = "WORKS " + childCmd.UseLine()
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// Reset the root command help template and make sure
// it falls back to the default
rootCmd.SetHelpTemplate("")
got, err = executeCommand(rootCmd, "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !strings.Contains(got, "Usage:") {
t.Errorf("Expected to contain %q, got %q", "Usage:", got)
}
}
func TestHelpFlagExecuted(t *testing.T) { func TestHelpFlagExecuted(t *testing.T) {
rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
@ -1126,45 +1018,6 @@ func TestHelpExecutedOnNonRunnableChild(t *testing.T) {
checkStringContains(t, output, childCmd.Long) checkStringContains(t, output, childCmd.Long)
} }
func TestSetUsageTemplate(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
rootCmd.SetUsageTemplate("WORKS {{.UseLine}}")
// Trigger the usage on the root command and check the new template is used
got, err := executeCommand(rootCmd, "--invalid")
if err == nil {
t.Errorf("Expected error but did not get one")
}
expected := "WORKS " + rootCmd.UseLine()
checkStringContains(t, got, expected)
// Trigger the usage on the child command and check
// the new template is inherited from the parent
got, err = executeCommand(rootCmd, "child", "--invalid")
if err == nil {
t.Errorf("Expected error but did not get one")
}
expected = "WORKS " + childCmd.UseLine()
checkStringContains(t, got, expected)
// Reset the root command usage template and make sure
// it falls back to the default
rootCmd.SetUsageTemplate("")
got, err = executeCommand(rootCmd, "--invalid")
if err == nil {
t.Errorf("Expected error but did not get one")
}
if !strings.Contains(got, "Usage:") {
t.Errorf("Expected to contain %q, got %q", "Usage:", got)
}
}
func TestVersionFlagExecuted(t *testing.T) { func TestVersionFlagExecuted(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}
@ -1176,24 +1029,6 @@ func TestVersionFlagExecuted(t *testing.T) {
checkStringContains(t, output, "root version 1.0.0") checkStringContains(t, output, "root version 1.0.0")
} }
func TestVersionFlagExecutedDiplayName(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Version: "1.0.0",
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Run: emptyRun,
}
output, err := executeCommand(rootCmd, "--version", "arg1")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, "kubectl plugin version 1.0.0")
}
func TestVersionFlagExecutedWithNoName(t *testing.T) { func TestVersionFlagExecutedWithNoName(t *testing.T) {
rootCmd := &Command{Version: "1.0.0", Run: emptyRun} rootCmd := &Command{Version: "1.0.0", Run: emptyRun}
@ -1264,39 +1099,6 @@ func TestShorthandVersionTemplate(t *testing.T) {
checkStringContains(t, output, "customized version: 1.0.0") 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) { func TestVersionFlagExecutedOnSubcommand(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0"} rootCmd := &Command{Use: "root", Version: "1.0.0"}
rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})
@ -1695,73 +1497,57 @@ func TestHooks(t *testing.T) {
} }
func TestPersistentHooks(t *testing.T) { func TestPersistentHooks(t *testing.T) {
EnableTraverseRunHooks = true var (
testPersistentHooks(t, []string{ parentPersPreArgs string
"parent PersistentPreRun", parentPreArgs string
"child PersistentPreRun", parentRunArgs string
"child PreRun", parentPostArgs string
"child Run", parentPersPostArgs string
"child PostRun", )
"child PersistentPostRun",
"parent PersistentPostRun",
})
EnableTraverseRunHooks = false var (
testPersistentHooks(t, []string{ childPersPreArgs string
"child PersistentPreRun", childPreArgs string
"child PreRun", childRunArgs string
"child Run", childPostArgs string
"child PostRun", childPersPostArgs string
"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{ parentCmd := &Command{
Use: "parent", Use: "parent",
PersistentPreRun: func(_ *Command, args []string) { PersistentPreRun: func(_ *Command, args []string) {
validateHook(args, "parent PersistentPreRun") parentPersPreArgs = strings.Join(args, " ")
}, },
PreRun: func(_ *Command, args []string) { PreRun: func(_ *Command, args []string) {
validateHook(args, "parent PreRun") parentPreArgs = strings.Join(args, " ")
}, },
Run: func(_ *Command, args []string) { Run: func(_ *Command, args []string) {
validateHook(args, "parent Run") parentRunArgs = strings.Join(args, " ")
}, },
PostRun: func(_ *Command, args []string) { PostRun: func(_ *Command, args []string) {
validateHook(args, "parent PostRun") parentPostArgs = strings.Join(args, " ")
}, },
PersistentPostRun: func(_ *Command, args []string) { PersistentPostRun: func(_ *Command, args []string) {
validateHook(args, "parent PersistentPostRun") parentPersPostArgs = strings.Join(args, " ")
}, },
} }
childCmd := &Command{ childCmd := &Command{
Use: "child", Use: "child",
PersistentPreRun: func(_ *Command, args []string) { PersistentPreRun: func(_ *Command, args []string) {
validateHook(args, "child PersistentPreRun") childPersPreArgs = strings.Join(args, " ")
}, },
PreRun: func(_ *Command, args []string) { PreRun: func(_ *Command, args []string) {
validateHook(args, "child PreRun") childPreArgs = strings.Join(args, " ")
}, },
Run: func(_ *Command, args []string) { Run: func(_ *Command, args []string) {
validateHook(args, "child Run") childRunArgs = strings.Join(args, " ")
}, },
PostRun: func(_ *Command, args []string) { PostRun: func(_ *Command, args []string) {
validateHook(args, "child PostRun") childPostArgs = strings.Join(args, " ")
}, },
PersistentPostRun: func(_ *Command, args []string) { PersistentPostRun: func(_ *Command, args []string) {
validateHook(args, "child PersistentPostRun") childPersPostArgs = strings.Join(args, " ")
}, },
} }
parentCmd.AddCommand(childCmd) parentCmd.AddCommand(childCmd)
@ -1774,13 +1560,41 @@ func testPersistentHooks(t *testing.T, expectedHookRunOrder []string) {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
for idx, exp := range expectedHookRunOrder { for _, v := range []struct {
if len(hookRunOrder) > idx { name string
if act := hookRunOrder[idx]; act != exp { got string
t.Errorf("Expected %q at %d, got %q", exp, idx, act) }{
} // TODO: currently PersistentPreRun* defined in parent does not
} else { // run if the matching child subcommand has PersistentPreRun.
t.Errorf("Expected %q at %d, got nothing", exp, idx) // 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)
} }
} }
} }
@ -2048,84 +1862,6 @@ func TestAddGroup(t *testing.T) {
checkStringContains(t, output, "\nTest group\n cmd") 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) { func TestSetOutput(t *testing.T) {
c := &Command{} c := &Command{}
c.SetOutput(nil) c.SetOutput(nil)
@ -2196,12 +1932,12 @@ func TestCommandPrintRedirection(t *testing.T) {
t.Error(err) t.Error(err)
} }
gotErrBytes, err := io.ReadAll(errBuff) gotErrBytes, err := ioutil.ReadAll(errBuff)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
gotOutBytes, err := io.ReadAll(outBuff) gotOutBytes, err := ioutil.ReadAll(outBuff)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -2789,166 +2525,3 @@ func TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) {
checkStringContains(t, output, HelpFlag) checkStringContains(t, output, HelpFlag)
checkStringOmits(t, output, VersionFlag) 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")
})
}
}
func TestHelpFuncExecuted(t *testing.T) {
helpText := "Long description"
// Create a context that will be unique, not just the background context
//nolint:golint,staticcheck // We can safely use a basic type as key in tests.
executionCtx := context.WithValue(context.Background(), "testKey", "123")
child := &Command{Use: "child", Run: emptyRun}
child.SetHelpFunc(func(cmd *Command, args []string) {
_, err := cmd.OutOrStdout().Write([]byte(helpText))
if err != nil {
t.Error(err)
}
// Test for https://github.com/spf13/cobra/issues/2240
if cmd.Context() != executionCtx {
t.Error("Context doesn't equal the execution context")
}
})
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.AddCommand(child)
output, err := executeCommandWithContext(executionCtx, rootCmd, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, helpText)
}

View file

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

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -17,8 +17,6 @@ package cobra
import ( import (
"fmt" "fmt"
"os" "os"
"regexp"
"strconv"
"strings" "strings"
"sync" "sync"
@ -35,7 +33,7 @@ const (
) )
// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. // Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.
var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{} var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
// lock for reading and writing from flagCompletionFunctions // lock for reading and writing from flagCompletionFunctions
var flagCompletionMutex = &sync.RWMutex{} var flagCompletionMutex = &sync.RWMutex{}
@ -79,10 +77,6 @@ const (
// obtain the same behavior but only for flags. // obtain the same behavior but only for flags.
ShellCompDirectiveFilterDirs 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. // All directives using iota should be above this one.
@ -117,50 +111,22 @@ type CompletionOptions struct {
HiddenDefaultCmd bool HiddenDefaultCmd bool
} }
// Completion is a string that can be used for completions
//
// two formats are supported:
// - the completion choice
// - the completion choice with a textual description (separated by a TAB).
//
// [CompletionWithDesc] can be used to create a completion string with a textual description.
//
// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used.
type Completion = string
// CompletionFunc is a function that provides completion results.
type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)
// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.
func CompletionWithDesc(choice string, description string) Completion {
return choice + "\t" + description
}
// NoFileCompletions can be used to disable file completion for commands that should // NoFileCompletions can be used to disable file completion for commands that should
// not trigger file completions. // not trigger file completions.
// func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
// This method satisfies [CompletionFunc].
// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].
func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {
return nil, ShellCompDirectiveNoFileComp return nil, ShellCompDirectiveNoFileComp
} }
// FixedCompletions can be used to create a completion function which always // FixedCompletions can be used to create a completion function which always
// returns the same results. // returns the same results.
// func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
// This method returns a function that satisfies [CompletionFunc] return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].
func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc {
return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {
return choices, directive return choices, directive
} }
} }
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. // RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
// func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions],
// or you can define your own.
func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error {
flag := c.Flag(flagName) flag := c.Flag(flagName)
if flag == nil { if flag == nil {
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
@ -175,20 +141,6 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc)
return nil return nil
} }
// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.
func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, 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 // Returns a string listing the different directive enabled in the specified parameter
func (d ShellCompDirective) string() string { func (d ShellCompDirective) string() string {
var directives []string var directives []string
@ -207,9 +159,6 @@ func (d ShellCompDirective) string() string {
if d&ShellCompDirectiveFilterDirs != 0 { if d&ShellCompDirectiveFilterDirs != 0 {
directives = append(directives, "ShellCompDirectiveFilterDirs") directives = append(directives, "ShellCompDirectiveFilterDirs")
} }
if d&ShellCompDirectiveKeepOrder != 0 {
directives = append(directives, "ShellCompDirectiveKeepOrder")
}
if len(directives) == 0 { if len(directives) == 0 {
directives = append(directives, "ShellCompDirectiveDefault") directives = append(directives, "ShellCompDirectiveDefault")
} }
@ -220,7 +169,7 @@ func (d ShellCompDirective) string() string {
return strings.Join(directives, ", ") return strings.Join(directives, ", ")
} }
// initCompleteCmd adds a special hidden command that can be used to request custom completions. // Adds a special hidden command that can be used to request custom completions.
func (c *Command) initCompleteCmd(args []string) { func (c *Command) initCompleteCmd(args []string) {
completeCmd := &Command{ completeCmd := &Command{
Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
@ -241,29 +190,24 @@ func (c *Command) initCompleteCmd(args []string) {
// 2- Even without completions, we need to print the directive // 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 { for _, comp := range completions {
if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) { if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
// Remove all activeHelp entries if it's disabled. // Remove all activeHelp entries in this case
continue if strings.HasPrefix(comp, activeHelpMarker) {
continue
}
} }
if noDescriptions { if noDescriptions {
// Remove any description that may be included following a tab character. // Remove any description that may be included following a tab character.
comp = strings.SplitN(comp, "\t", 2)[0] comp = strings.Split(comp, "\t")[0]
} }
// Make sure we only write the first line to the output. // Make sure we only write the first line to the output.
// This is needed if a description contains a linebreak. // This is needed if a description contains a linebreak.
// Otherwise the shell scripts will interpret the other lines as new flags // Otherwise the shell scripts will interpret the other lines as new flags
// and could therefore provide a wrong completion. // and could therefore provide a wrong completion.
comp = strings.SplitN(comp, "\n", 2)[0] comp = strings.Split(comp, "\n")[0]
// Finally trim the completion. This is especially important to get rid // Finally trim the completion. This is especially important to get rid
// of a trailing tab when there are no description following it. // of a trailing tab when there are no description following it.
@ -272,14 +216,14 @@ func (c *Command) initCompleteCmd(args []string) {
// although there is no description). // although there is no description).
comp = strings.TrimSpace(comp) comp = strings.TrimSpace(comp)
// Print each possible completion to the output for the completion script to consume. // Print each possible completion to stdout for the completion script to consume.
fmt.Fprintln(out, comp) fmt.Fprintln(finalCmd.OutOrStdout(), comp)
} }
// As the last printout, print the completion directive for the completion script to parse. // 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 directive integer must be that last character following a single colon (:).
// The completion script expects :<directive> // The completion script expects :<directive>
fmt.Fprintf(out, ":%d\n", directive) fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
// Print some helpful info to stderr for the user to understand. // Print some helpful info to stderr for the user to understand.
// Output from stderr must be ignored by the completion script. // Output from stderr must be ignored by the completion script.
@ -298,15 +242,7 @@ func (c *Command) initCompleteCmd(args []string) {
} }
} }
// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
// flags that accept multiple values and therefore can provide completion
// multiple times.
type SliceValue interface {
// GetSlice returns the flag value list as an array of strings.
GetSlice() []string
}
func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) {
// The last argument, which is not completely typed by the user, // The last argument, which is not completely typed by the user,
// should not be part of the list of arguments // should not be part of the list of arguments
toComplete := args[len(args)-1] toComplete := args[len(args)-1]
@ -334,19 +270,15 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
} }
if err != nil { if err != nil {
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB> // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
return c, []Completion{}, 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 finalCmd.ctx = c.ctx
// These flags are normally added when `execute()` is called on `finalCmd`, // These flags are normally added when `execute()` is called on `finalCmd`,
// however, when doing completion, we don't call `finalCmd.execute()`. // however, when doing completion, we don't call `finalCmd.execute()`.
// Let's add the --help and --version flag ourselves but only if the finalCmd // Let's add the --help and --version flag ourselves.
// has not disabled flag parsing; if flag parsing is disabled, it is up to the finalCmd.InitDefaultHelpFlag()
// finalCmd itself to handle the completion of *all* flags. finalCmd.InitDefaultVersionFlag()
if !finalCmd.DisableFlagParsing {
finalCmd.InitDefaultHelpFlag()
finalCmd.InitDefaultVersionFlag()
}
// Check if we are doing flag value completion before parsing the flags. // 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 // This is important because if we are completing a flag value, we need to also
@ -364,7 +296,7 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
// Parse the flags early so we can check if required flags are set // Parse the flags early so we can check if required flags are set
if err = finalCmd.ParseFlags(finalArgs); err != nil { if err = finalCmd.ParseFlags(finalArgs); err != nil {
return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
} }
realArgCount := finalCmd.Flags().NArg() realArgCount := finalCmd.Flags().NArg()
@ -376,14 +308,14 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
if flagErr != nil { if flagErr != nil {
// If error type is flagCompError and we don't want flagCompletion we should ignore the error // If error type is flagCompError and we don't want flagCompletion we should ignore the error
if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
} }
} }
// Look for the --help or --version flags. If they are present, // Look for the --help or --version flags. If they are present,
// there should be no further completions. // there should be no further completions.
if helpOrVersionFlagPresent(finalCmd) { if helpOrVersionFlagPresent(finalCmd) {
return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil
} }
// We only remove the flags from the arguments if DisableFlagParsing is not set. // We only remove the flags from the arguments if DisableFlagParsing is not set.
@ -412,11 +344,11 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil
} }
// Directory completion // Directory completion
return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil
} }
} }
var completions []Completion var completions []string
var directive ShellCompDirective var directive ShellCompDirective
// Enforce flag groups before doing flag completions // Enforce flag groups before doing flag completions
@ -435,14 +367,10 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
// If we have not found any required flags, only then can we show regular flags // If we have not found any required flags, only then can we show regular flags
if len(completions) == 0 { if len(completions) == 0 {
doCompleteFlags := func(flag *pflag.Flag) { doCompleteFlags := func(flag *pflag.Flag) {
_, acceptsMultiple := flag.Value.(SliceValue) if !flag.Changed ||
acceptsMultiple = acceptsMultiple ||
strings.Contains(flag.Value.Type(), "Slice") || strings.Contains(flag.Value.Type(), "Slice") ||
strings.Contains(flag.Value.Type(), "Array") || strings.Contains(flag.Value.Type(), "Array") {
strings.HasPrefix(flag.Value.Type(), "stringTo") // If the flag is not already present, or if it can be specified multiple times (Array or Slice)
if !flag.Changed || acceptsMultiple {
// If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo)
// we suggest it as a completion // we suggest it as a completion
completions = append(completions, getFlagNameCompletions(flag, toComplete)...) completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
} }
@ -454,11 +382,6 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
doCompleteFlags(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) { finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
doCompleteFlags(flag) doCompleteFlags(flag)
}) })
@ -502,7 +425,7 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
for _, subCmd := range finalCmd.Commands() { for _, subCmd := range finalCmd.Commands() {
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
if strings.HasPrefix(subCmd.Name(), toComplete) { if strings.HasPrefix(subCmd.Name(), toComplete) {
completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
} }
directive = ShellCompDirectiveNoFileComp directive = ShellCompDirectiveNoFileComp
} }
@ -547,7 +470,7 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
} }
// Find the completion function for the flag or command // Find the completion function for the flag or command
var completionFn CompletionFunc var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
if flag != nil && flagCompletion { if flag != nil && flagCompletion {
flagCompletionMutex.RLock() flagCompletionMutex.RLock()
completionFn = flagCompletionFunctions[flag] completionFn = flagCompletionFunctions[flag]
@ -558,7 +481,7 @@ func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCo
if completionFn != nil { if completionFn != nil {
// Go custom completion defined for this flag or command. // Go custom completion defined for this flag or command.
// Call the registered completion function to get the completions. // Call the registered completion function to get the completions.
var comps []Completion var comps []string
comps, directive = completionFn(finalCmd, finalArgs, toComplete) comps, directive = completionFn(finalCmd, finalArgs, toComplete)
completions = append(completions, comps...) completions = append(completions, comps...)
} }
@ -571,23 +494,23 @@ func helpOrVersionFlagPresent(cmd *Command) bool {
len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed { len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
return true return true
} }
if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil && if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&
len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
return true return true
} }
return false return false
} }
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion { func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
if nonCompletableFlag(flag) { if nonCompletableFlag(flag) {
return []Completion{} return []string{}
} }
var completions []Completion var completions []string
flagName := "--" + flag.Name flagName := "--" + flag.Name
if strings.HasPrefix(flagName, toComplete) { if strings.HasPrefix(flagName, toComplete) {
// Flag without the = // Flag without the =
completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
// Why suggest both long forms: --flag and --flag= ? // Why suggest both long forms: --flag and --flag= ?
// This forces the user to *always* have to type either an = or a space after the flag name. // This forces the user to *always* have to type either an = or a space after the flag name.
@ -599,20 +522,20 @@ func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {
// if len(flag.NoOptDefVal) == 0 { // if len(flag.NoOptDefVal) == 0 {
// // Flag requires a value, so it can be suffixed with = // // Flag requires a value, so it can be suffixed with =
// flagName += "=" // flagName += "="
// completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
// } // }
} }
flagName = "-" + flag.Shorthand flagName = "-" + flag.Shorthand
if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
} }
return completions return completions
} }
func completeRequireFlags(finalCmd *Command, toComplete string) []Completion { func completeRequireFlags(finalCmd *Command, toComplete string) []string {
var completions []Completion var completions []string
doCompleteRequiredFlags := func(flag *pflag.Flag) { doCompleteRequiredFlags := func(flag *pflag.Flag) {
if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {
@ -727,8 +650,8 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
// 1- the feature has been explicitly disabled by the program, // 1- the feature has been explicitly disabled by the program,
// 2- c has no subcommands (to avoid creating one), // 2- c has no subcommands (to avoid creating one),
// 3- c already has a 'completion' command provided by the program. // 3- c already has a 'completion' command provided by the program.
func (c *Command) InitDefaultCompletionCmd(args ...string) { func (c *Command) InitDefaultCompletionCmd() {
if c.CompletionOptions.DisableDefaultCmd { if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
return return
} }
@ -741,16 +664,6 @@ func (c *Command) InitDefaultCompletionCmd(args ...string) {
haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions
// Special case to know if there are sub-commands or not.
hasSubCommands := false
for _, cmd := range c.commands {
if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName {
// We found a real sub-command (not 'help' or '__complete')
hasSubCommands = true
break
}
}
completionCmd := &Command{ completionCmd := &Command{
Use: compCmdName, Use: compCmdName,
Short: "Generate the autocompletion script for the specified shell", Short: "Generate the autocompletion script for the specified shell",
@ -764,22 +677,6 @@ See each sub-command's help for details on how to use the generated script.
} }
c.AddCommand(completionCmd) c.AddCommand(completionCmd)
if !hasSubCommands {
// If the 'completion' command will be the only sub-command,
// we only create it if it is actually being called.
// This avoids breaking programs that would suddenly find themselves with
// a subcommand, which would prevent them from accepting arguments.
// We also create the 'completion' command if the user is triggering
// shell completion for it (prog __complete completion '')
subCmd, cmdArgs, err := c.Find(args)
if err != nil || subCmd.Name() != compCmdName &&
!(subCmd.Name() == ShellCompRequestCmd && len(cmdArgs) > 1 && cmdArgs[0] == compCmdName) {
// The completion command is not being called or being completed so we remove it.
c.RemoveCommand(completionCmd)
return
}
}
out := c.OutOrStdout() out := c.OutOrStdout()
noDesc := c.CompletionOptions.DisableDescriptions noDesc := c.CompletionOptions.DisableDescriptions
shortDesc := "Generate the autocompletion script for %s" shortDesc := "Generate the autocompletion script for %s"
@ -830,7 +727,7 @@ to enable it. You can execute the following once:
To load completions in your current shell session: To load completions in your current shell session:
source <(%[1]s completion zsh) source <(%[1]s completion zsh); compdef _%[1]s %[1]s
To load completions for every new session, execute once: To load completions for every new session, execute once:
@ -972,34 +869,3 @@ func CompError(msg string) {
func CompErrorln(msg string) { func CompErrorln(msg string) {
CompError(fmt.Sprintf("%s\n", msg)) 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
}

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -18,6 +18,7 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -141,12 +142,15 @@ func TestGenManSeeAlso(t *testing.T) {
if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil { if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil {
t.Fatalf("Couldn't find SEE ALSO section header: %v", err) t.Fatalf("Couldn't find SEE ALSO section header: %v", err)
} }
if err := assertNextLineEquals(scanner, ".PP"); err != nil {
t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err)
}
if err := assertNextLineEquals(scanner, `\fBroot-bbb(1)\fP, \fBroot-ccc(1)\fP`); err != nil { if err := assertNextLineEquals(scanner, `\fBroot-bbb(1)\fP, \fBroot-ccc(1)\fP`); err != nil {
t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err) t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
} }
} }
func TestManPrintFlagsHidesShortDeprecated(t *testing.T) { func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
c := &cobra.Command{} c := &cobra.Command{}
c.Flags().StringP("foo", "f", "default", "Foo flag") c.Flags().StringP("foo", "f", "default", "Foo flag")
assertNoErr(t, c.Flags().MarkShorthandDeprecated("foo", "don't use it no more")) assertNoErr(t, c.Flags().MarkShorthandDeprecated("foo", "don't use it no more"))
@ -164,7 +168,7 @@ func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
func TestGenManTree(t *testing.T) { func TestGenManTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
header := &GenManHeader{Section: "2"} header := &GenManHeader{Section: "2"}
tmpdir, err := os.MkdirTemp("", "test-gen-man-tree") tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
if err != nil { if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error()) t.Fatalf("Failed to create tmpdir: %s", err.Error())
} }
@ -215,7 +219,7 @@ func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
} }
func BenchmarkGenManToFile(b *testing.B) { func BenchmarkGenManToFile(b *testing.B) {
file, err := os.CreateTemp("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }

View file

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

View file

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

View file

@ -35,7 +35,7 @@ package main
import ( import (
"log" "log"
"io" "io/ioutil"
"os" "os"
"k8s.io/kubernetes/pkg/kubectl/cmd" "k8s.io/kubernetes/pkg/kubectl/cmd"
@ -45,7 +45,7 @@ import (
) )
func main() { func main() {
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard) kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
err := doc.GenMarkdownTree(kubectl, "./") err := doc.GenMarkdownTree(kubectl, "./")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@ package doc
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -93,7 +94,7 @@ func TestGenMdNoTag(t *testing.T) {
func TestGenMdTree(t *testing.T) { func TestGenMdTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
tmpdir, err := os.MkdirTemp("", "test-gen-md-tree") tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
if err != nil { if err != nil {
t.Fatalf("Failed to create tmpdir: %v", err) t.Fatalf("Failed to create tmpdir: %v", err)
} }
@ -109,7 +110,7 @@ func TestGenMdTree(t *testing.T) {
} }
func BenchmarkGenMarkdownToFile(b *testing.B) { func BenchmarkGenMarkdownToFile(b *testing.B) {
file, err := os.CreateTemp("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }

View file

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

View file

@ -35,7 +35,7 @@ package main
import ( import (
"log" "log"
"io" "io/ioutil"
"os" "os"
"k8s.io/kubernetes/pkg/kubectl/cmd" "k8s.io/kubernetes/pkg/kubectl/cmd"
@ -45,7 +45,7 @@ import (
) )
func main() { func main() {
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard) kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
err := doc.GenReSTTree(kubectl, "./") err := doc.GenReSTTree(kubectl, "./")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@ package doc
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -80,7 +81,7 @@ func TestGenRSTNoTag(t *testing.T) {
func TestGenRSTTree(t *testing.T) { func TestGenRSTTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
tmpdir, err := os.MkdirTemp("", "test-gen-rst-tree") tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
if err != nil { if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error()) t.Fatalf("Failed to create tmpdir: %s", err.Error())
} }
@ -96,7 +97,7 @@ func TestGenRSTTree(t *testing.T) {
} }
func BenchmarkGenReSTToFile(b *testing.B) { func BenchmarkGenReSTToFile(b *testing.B) {
file, err := os.CreateTemp("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }

View file

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

View file

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

View file

@ -34,7 +34,7 @@ This program can actually generate docs for the kubectl command in the kubernete
package main package main
import ( import (
"io" "io/ioutil"
"log" "log"
"os" "os"
@ -45,7 +45,7 @@ import (
) )
func main() { func main() {
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard) kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
err := doc.GenYamlTree(kubectl, "./") err := doc.GenYamlTree(kubectl, "./")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@ package doc
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -57,7 +58,7 @@ func TestGenYamlNoTag(t *testing.T) {
func TestGenYamlTree(t *testing.T) { func TestGenYamlTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
tmpdir, err := os.MkdirTemp("", "test-gen-yaml-tree") tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
if err != nil { if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error()) t.Fatalf("Failed to create tmpdir: %s", err.Error())
} }
@ -84,7 +85,7 @@ func TestGenYamlDocRunnable(t *testing.T) {
} }
func BenchmarkGenYamlToFile(b *testing.B) { func BenchmarkGenYamlToFile(b *testing.B) {
file, err := os.CreateTemp("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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" __%[1]s_debug "last arg: $lastArg"
# Disable ActiveHelp which is not supported for fish shell # Disable ActiveHelp which is not supported for fish shell
set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg" set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
__%[1]s_debug "Calling $requestComp" __%[1]s_debug "Calling $requestComp"
set -l results (eval $requestComp 2> /dev/null) set -l results (eval $requestComp 2> /dev/null)
@ -89,60 +89,6 @@ function __%[1]s_perform_completion
printf "%%s\n" "$directiveLine" printf "%%s\n" "$directiveLine"
end 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: # This function does two things:
# - Obtain the completions and store them in the global __%[1]s_comp_results # - Obtain the completions and store them in the global __%[1]s_comp_results
# - Return false if file completion should be performed # - Return false if file completion should be performed
@ -153,17 +99,17 @@ function __%[1]s_prepare_completions
# Start fresh # Start fresh
set --erase __%[1]s_comp_results set --erase __%[1]s_comp_results
__%[1]s_perform_completion_once set -l results (__%[1]s_perform_completion)
__%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result" __%[1]s_debug "Completion results: $results"
if test -z "$__%[1]s_perform_completion_once_result" if test -z "$results"
__%[1]s_debug "No completion, probably due to a failure" __%[1]s_debug "No completion, probably due to a failure"
# Might as well do file completion, in case it helps # Might as well do file completion, in case it helps
return 1 return 1
end end
set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) set -l directive (string sub --start 2 $results[-1])
set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2] set --global __%[1]s_comp_results $results[1..-2]
__%[1]s_debug "Completions are: $__%[1]s_comp_results" __%[1]s_debug "Completions are: $__%[1]s_comp_results"
__%[1]s_debug "Directive is: $directive" __%[1]s_debug "Directive is: $directive"
@ -259,17 +205,13 @@ end
# Remove any pre-existing completions for the program since we will be handling all of them. # Remove any pre-existing completions for the program since we will be handling all of them.
complete -c %[2]s -e 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 # The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results
# which provides the program's completion choices. # which provides the program's completion choices.
# If this doesn't require order preservation, we don't use the -k flag complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
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, `, nameForVar, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
} }
// GenFishCompletion generates fish completion file and writes to the passed writer. // GenFishCompletion generates fish completion file and writes to the passed writer.

4
fish_completions.md Normal file
View file

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

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -23,9 +23,8 @@ import (
) )
const ( const (
requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" requiredAsGroup = "cobra_annotation_required_if_others_set"
oneRequiredAnnotation = "cobra_annotation_one_required" mutuallyExclusive = "cobra_annotation_mutually_exclusive"
mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive"
) )
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors // MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
@ -37,23 +36,7 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
if f == nil { if f == nil {
panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v)) 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, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil { if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], 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. // Only errs if the flag isn't found.
panic(err) panic(err)
} }
@ -70,13 +53,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)) 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. // 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, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil { if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {
panic(err) panic(err)
} }
} }
} }
// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the // ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the
// first error encountered. // first error encountered.
func (c *Command) ValidateFlagGroups() error { func (c *Command) ValidateFlagGroups() error {
if c.DisableFlagParsing { if c.DisableFlagParsing {
@ -88,20 +71,15 @@ func (c *Command) ValidateFlagGroups() error {
// groupStatus format is the list of flags as a unique ID, // 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. // then a map of each flag name and whether it is set or not.
groupStatus := map[string]map[string]bool{} groupStatus := map[string]map[string]bool{}
oneRequiredGroupStatus := map[string]map[string]bool{}
mutuallyExclusiveGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
flags.VisitAll(func(pflag *flag.Flag) { flags.VisitAll(func(pflag *flag.Flag) {
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
}) })
if err := validateRequiredFlagGroups(groupStatus); err != nil { if err := validateRequiredFlagGroups(groupStatus); err != nil {
return err return err
} }
if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {
return err
}
if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
return err return err
} }
@ -130,7 +108,7 @@ func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annota
continue continue
} }
groupStatus[group] = make(map[string]bool, len(flagnames)) groupStatus[group] = map[string]bool{}
for _, name := range flagnames { for _, name := range flagnames {
groupStatus[group][name] = false groupStatus[group][name] = false
} }
@ -164,27 +142,6 @@ func validateRequiredFlagGroups(data map[string]map[string]bool) error {
return nil 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 { func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
keys := sortedKeys(data) keys := sortedKeys(data)
for _, flagList := range keys { for _, flagList := range keys {
@ -219,7 +176,6 @@ func sortedKeys(m map[string]map[string]bool) []string {
// enforceFlagGroupsForCompletion will do the following: // enforceFlagGroupsForCompletion will do the following:
// - when a flag in a group is present, other flags in the group will be marked required // - 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 // - 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 // This allows the standard completion logic to behave appropriately for flag groups
func (c *Command) enforceFlagGroupsForCompletion() { func (c *Command) enforceFlagGroupsForCompletion() {
@ -229,12 +185,10 @@ func (c *Command) enforceFlagGroupsForCompletion() {
flags := c.Flags() flags := c.Flags()
groupStatus := map[string]map[string]bool{} groupStatus := map[string]map[string]bool{}
oneRequiredGroupStatus := map[string]map[string]bool{}
mutuallyExclusiveGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
c.Flags().VisitAll(func(pflag *flag.Flag) { c.Flags().VisitAll(func(pflag *flag.Flag) {
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
}) })
// If a flag that is part of a group is present, we make all the other flags // If a flag that is part of a group is present, we make all the other flags
@ -250,26 +204,6 @@ 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 // 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 // flags of that group so the shell completion does not suggest them
for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {

View file

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

6
go.mod
View file

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

12
go.sum
View file

@ -1,11 +1,11 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 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/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View file

@ -1,4 +1,4 @@
// Copyright 2013-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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) { func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
// Variables should not contain a '-' or ':' character // Variables should not contain a '-' or ':' character
nameForVar := name nameForVar := name
nameForVar = strings.ReplaceAll(nameForVar, "-", "_") nameForVar = strings.Replace(nameForVar, "-", "_", -1)
nameForVar = strings.ReplaceAll(nameForVar, ":", "_") nameForVar = strings.Replace(nameForVar, ":", "_", -1)
compCmd := ShellCompRequestCmd compCmd := ShellCompRequestCmd
if !includeDesc { if !includeDesc {
@ -47,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` `+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
} }
[scriptblock]${__%[2]sCompleterBlock} = { [scriptblock]$__%[2]sCompleterBlock = {
param( param(
$WordToComplete, $WordToComplete,
$CommandAst, $CommandAst,
@ -77,7 +77,6 @@ filter __%[1]s_escapeStringWithSpecialChars {
$ShellCompDirectiveNoFileComp=%[6]d $ShellCompDirectiveNoFileComp=%[6]d
$ShellCompDirectiveFilterFileExt=%[7]d $ShellCompDirectiveFilterFileExt=%[7]d
$ShellCompDirectiveFilterDirs=%[8]d $ShellCompDirectiveFilterDirs=%[8]d
$ShellCompDirectiveKeepOrder=%[9]d
# Prepare the command to request completions for the program. # Prepare the command to request completions for the program.
# Split the command at the first space to separate the program and arguments. # Split the command at the first space to separate the program and arguments.
@ -107,22 +106,13 @@ filter __%[1]s_escapeStringWithSpecialChars {
# If the last parameter is complete (there is a space following it) # 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. # We add an extra empty parameter so we can indicate this to the go method.
__%[1]s_debug "Adding extra empty parameter" __%[1]s_debug "Adding extra empty parameter"
# PowerShell 7.2+ changed the way how the arguments are passed to executables, `+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+`
# so for pre-7.2 or when Legacy argument passing is enabled we need to use `+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
`+" # `\"`\" 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" __%[1]s_debug "Calling $RequestComp"
# First disable ActiveHelp which is not supported for Powershell # First disable ActiveHelp which is not supported for Powershell
${env:%[10]s}=0 $env:%[9]s=0
#call the command store the output in $out and redirect stderr and stdout to null #call the command store the output in $out and redirect stderr and stdout to null
# $Out is an array contains each line per element # $Out is an array contains each line per element
@ -147,7 +137,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
} }
$Longest = 0 $Longest = 0
[Array]$Values = $Out | ForEach-Object { $Values = $Out | ForEach-Object {
#Split the output in name and description #Split the output in name and description
`+" $Name, $Description = $_.Split(\"`t\",2)"+` `+" $Name, $Description = $_.Split(\"`t\",2)"+`
__%[1]s_debug "Name: $Name Description: $Description" __%[1]s_debug "Name: $Name Description: $Description"
@ -162,10 +152,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
if (-Not $Description) { if (-Not $Description) {
$Description = " " $Description = " "
} }
New-Object -TypeName PSCustomObject -Property @{ @{Name="$Name";Description="$Description"}
Name = "$Name"
Description = "$Description"
}
} }
@ -195,11 +182,6 @@ 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 ) { if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
__%[1]s_debug "ShellCompDirectiveNoFileComp is called" __%[1]s_debug "ShellCompDirectiveNoFileComp is called"
@ -243,12 +225,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
__%[1]s_debug "Only one completion left" __%[1]s_debug "Only one completion left"
# insert space after value # insert space after value
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
} else { } else {
# Add the proper number of spaces to align the descriptions # Add the proper number of spaces to align the descriptions
@ -263,12 +240,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
$Description = " ($($comp.Description))" $Description = " ($($comp.Description))"
} }
$CompletionText = "$($comp.Name)$Description" [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
} }
} }
@ -277,13 +249,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
# insert space after value # insert space after value
# MenuComplete will automatically show the ToolTip of # MenuComplete will automatically show the ToolTip of
# the highlighted value at the bottom of the suggestions. # the highlighted value at the bottom of the suggestions.
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
} }
# TabCompleteNext and in case we get something unknown # TabCompleteNext and in case we get something unknown
@ -291,23 +257,17 @@ filter __%[1]s_escapeStringWithSpecialChars {
# Like MenuComplete but we don't want to add a space here because # Like MenuComplete but we don't want to add a space here because
# the user need to press space anyway to get the completion. # the user need to press space anyway to get the completion.
# Description will not be shown because that's not possible with TabCompleteNext # Description will not be shown because that's not possible with TabCompleteNext
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars)
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
} }
} }
} }
} }
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock
`, name, nameForVar, compCmd, `, name, nameForVar, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
} }
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {

View file

@ -0,0 +1,3 @@
# 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-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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 // check that active help is being disabled
activeHelpVar := activeHelpEnvVar(c.Name()) activeHelpVar := activeHelpEnvVar(c.Name())
check(t, output, fmt.Sprintf("${env:%s}=0", activeHelpVar)) check(t, output, fmt.Sprintf("%s=0", activeHelpVar))
} }

View file

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

View file

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

View file

@ -8,8 +8,7 @@ The currently supported shells are:
- PowerShell - PowerShell
Cobra will automatically provide your program with a fully functional `completion` command, Cobra will automatically provide your program with a fully functional `completion` command,
similarly to how it provides the `help` command. If there are no other subcommands, the similarly to how it provides the `help` command.
default `completion` command will be hidden, but still functional.
## Creating your own completion command ## Creating your own completion command
@ -72,7 +71,7 @@ PowerShell:
`,cmd.Root().Name()), `,cmd.Root().Name()),
DisableFlagsInUseLine: true, DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
switch args[0] { switch args[0] {
case "bash": case "bash":
@ -163,7 +162,16 @@ cmd := &cobra.Command{
} }
``` ```
The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`. 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`.
### Dynamic completion of nouns ### Dynamic completion of nouns
@ -178,7 +186,7 @@ cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) { RunE: func(cmd *cobra.Command, args []string) {
RunGet(args[0]) RunGet(args[0])
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 { if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
} }
@ -212,7 +220,7 @@ ShellCompDirectiveNoFileComp
// Indicates that the returned completions should be used as file extension filters. // Indicates that the returned completions should be used as file extension filters.
// For example, to complete only files of the form *.json or *.yaml: // For example, to complete only files of the form *.json or *.yaml:
// return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt // return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt
// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() // For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
// is a shortcut to using this directive explicitly. // is a shortcut to using this directive explicitly.
// //
@ -220,19 +228,15 @@ ShellCompDirectiveFilterFileExt
// Indicates that only directory names should be provided in file completion. // Indicates that only directory names should be provided in file completion.
// For example: // For example:
// return nil, cobra.ShellCompDirectiveFilterDirs // return nil, ShellCompDirectiveFilterDirs
// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. // For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
// //
// To request directory names within another directory, the returned completions // To request directory names within another directory, the returned completions
// should specify a single directory name within which to search. For example, // should specify a single directory name within which to search. For example,
// to complete directories within "themes/": // to complete directories within "themes/":
// return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs // return []string{"themes"}, ShellCompDirectiveFilterDirs
// //
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. ***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.
@ -260,7 +264,7 @@ Calling the `__complete` command directly allows you to run the Go debugger to t
```go ```go
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE // Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
// is set to a file path) and optionally prints to stderr. // is set to a file path) and optionally prints to stderr.
cobra.CompDebug(msg string, printToStdErr bool) cobra.CompDebug(msg string, printToStdErr bool) {
cobra.CompDebugln(msg string, printToStdErr bool) cobra.CompDebugln(msg string, printToStdErr bool)
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE // Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
@ -294,8 +298,8 @@ As for nouns, Cobra provides a way of defining dynamic completion of flags. To
```go ```go
flagName := "output" flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []cobra.Completion{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
}) })
``` ```
Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
@ -328,8 +332,8 @@ cmd.MarkFlagFilename(flagName, "yaml", "json")
or or
```go ```go
flagName := "output" flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt}) return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
``` ```
### Limit flag completions to directory names ### Limit flag completions to directory names
@ -342,15 +346,15 @@ cmd.MarkFlagDirname(flagName)
or or
```go ```go
flagName := "output" flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveFilterDirs return nil, cobra.ShellCompDirectiveFilterDirs
}) })
``` ```
To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:
```go ```go
flagName := "output" flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
}) })
``` ```
### Descriptions for completions ### Descriptions for completions
@ -371,38 +375,16 @@ $ helm s[tab]
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
``` ```
Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. Cobra provides the helper function `CompletionWithDesc(string, string)` to create a completion with a description. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
```go ```go
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []cobra.Completion{ return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
cobra.CompletionWithDesc("harbor", "An image registry"),
cobra.CompletionWithDesc("thanos", "Long-term metrics")
}, cobra.ShellCompDirectiveNoFileComp
}} }}
``` ```
or or
```go ```go
ValidArgs: []cobra.Completion{ ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
cobra.CompletionWithDesc("bash", "Completions for bash"),
cobra.CompletionWithDesc("zsh", "Completions 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 ## Bash completions
### Dependencies ### Dependencies
@ -426,7 +408,7 @@ completion firstcommand secondcommand
### Bash legacy dynamic completions ### Bash legacy dynamic completions
For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
Please refer to [Bash Completions](bash.md) for details. Please refer to [Bash Completions](bash_completions.md) for details.
### Bash completion V2 ### Bash completion V2
@ -435,13 +417,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 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 `GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion
(see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion (see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion
solution described in this document. solution described in this document.
Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash 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: completion V2 solution which provides the following extra features:
- Supports completion descriptions (like the other shells) - 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) - 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()` `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 you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra
@ -458,7 +440,7 @@ show (show information of a chart)
$ helm s[tab][tab] $ helm s[tab][tab]
search show status 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 ## Zsh completions
Cobra supports native zsh completion generated from the root `cobra.Command`. Cobra supports native zsh completion generated from the root `cobra.Command`.
@ -492,7 +474,7 @@ search show status
### Zsh completions standardization ### 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. 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.md) for details. Please refer to [Zsh Completions](zsh_completions.md) for details.
## fish completions ## fish completions
@ -545,7 +527,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. # With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
$ helm s[tab] $ helm s[tab]
search show status search show status
search for a keyword in charts search for a keyword in charts

View file

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

View file

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

View file

@ -3,14 +3,14 @@
While you are welcome to provide your own organization, typically a Cobra-based While you are welcome to provide your own organization, typically a Cobra-based
application will follow the following organizational structure: application will follow the following organizational structure:
```console ```
▾ appName/ ▾ appName/
▾ cmd/ ▾ cmd/
add.go add.go
your.go your.go
commands.go commands.go
here.go here.go
main.go main.go
``` ```
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
@ -18,7 +18,9 @@ In a Cobra app, typically the main.go file is very bare. It serves one purpose:
```go ```go
package main package main
import "{pathToYourApp}/cmd" import (
"{pathToYourApp}/cmd"
)
func main() { func main() {
cmd.Execute() cmd.Execute()
@ -27,8 +29,8 @@ func main() {
## Using the Cobra Generator ## Using the Cobra Generator
Cobra-CLI is its own program that will create your application and add any commands you want. Cobra-CLI is its own program that will create your application and add any
It's the easiest way to incorporate Cobra into your application. 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) 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)
@ -146,7 +148,9 @@ In a Cobra app, typically the main.go file is very bare. It serves one purpose:
```go ```go
package main package main
import "{pathToYourApp}/cmd" import (
"{pathToYourApp}/cmd"
)
func main() { func main() {
cmd.Execute() cmd.Execute()
@ -184,37 +188,6 @@ 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:
```console
├── 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 ### Returning and handling errors
If you wish to return an error to the caller of a command, `RunE` can be used. If you wish to return an error to the caller of a command, `RunE` can be used.
@ -297,7 +270,6 @@ command := cobra.Command{
### Bind Flags with Config ### Bind Flags with Config
You can also bind your flags with [viper](https://github.com/spf13/viper): You can also bind your flags with [viper](https://github.com/spf13/viper):
```go ```go
var author string var author string
@ -317,14 +289,12 @@ 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 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: when a flag has not been set, mark it as required:
```go ```go
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkFlagRequired("region") rootCmd.MarkFlagRequired("region")
``` ```
Or, for persistent flags: Or, for persistent flags:
```go ```go
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkPersistentFlagRequired("region") rootCmd.MarkPersistentFlagRequired("region")
@ -334,7 +304,6 @@ 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 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: Cobra can enforce that requirement:
```go ```go
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
@ -343,24 +312,13 @@ rootCmd.MarkFlagsRequiredTogether("username", "password")
You can also prevent different flags from being provided together if they represent mutually 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: exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
```go ```go
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml") rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
``` ```
If you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`. In both of these cases:
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 - both local and persistent flags can be used
- **NOTE:** the group is only enforced on commands where every flag is defined - **NOTE:** the group is only enforced on commands where every flag is defined
- a flag may appear in multiple groups - a flag may appear in multiple groups
@ -391,7 +349,7 @@ shown below:
```go ```go
var cmd = &cobra.Command{ var cmd = &cobra.Command{
Short: "hello", Short: "hello",
Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs), Args: MatchAll(ExactArgs(2), OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!") fmt.Println("Hello, World!")
}, },
@ -430,7 +388,7 @@ by not providing a 'Run' for the 'rootCmd'.
We have only defined one flag for a single command. 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 ```go
package main package main
@ -504,42 +462,40 @@ create' is called. Every command will automatically have the '--help' flag adde
The following output is automatically generated by Cobra. Nothing beyond the The following output is automatically generated by Cobra. Nothing beyond the
command and flag definitions are needed. command and flag definitions are needed.
```console $ cobra-cli help
$ cobra-cli help
Cobra is a CLI library for Go that empowers applications. Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files This application is a tool to generate the needed files
to quickly create a Cobra application. to quickly create a Cobra application.
Usage: Usage:
cobra-cli [command] cobra-cli [command]
Available Commands: Available Commands:
add Add a command to a Cobra Application add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell completion Generate the autocompletion script for the specified shell
help Help about any command help Help about any command
init Initialize a Cobra Application init Initialize a Cobra Application
Flags: Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME") -a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml) --config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra-cli -h, --help help for cobra-cli
-l, --license string name of license for the project -l, --license string name of license for the project
--viper use Viper for configuration --viper use Viper for configuration
Use "cobra-cli [command] --help" for more information about a command.
Use "cobra-cli [command] --help" for more information about a command.
```
Help is just a command like any other. There is no special logic or behavior Help is just a command like any other. There is no special logic or behavior
around it. In fact, you can provide your own if you want. around it. In fact, you can provide your own if you want.
### Grouping commands in help ### Grouping commands in help
Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly Cobra supports grouping of available commands. Groups must be explicitly defined by `AddGroup` and set by
defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element the `GroupId` element of a subcommand. The groups will appear in the same order as they are defined.
of that subcommand. The groups will appear in the help output in the same order as they are defined using different If you use the generated `help` or `completion` commands, you can set the group ids by `SetHelpCommandGroupId`
calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using and `SetCompletionCommandGroupId`, respectively.
`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.
### Defining your own help ### Defining your own help
@ -554,9 +510,6 @@ cmd.SetHelpTemplate(s string)
The latter two will also apply to any children commands. The latter two will also apply to any children commands.
Note that templates specified with `SetHelpTemplate` are evaluated using
`text/template` which can increase the size of the compiled executable.
## Usage Message ## Usage Message
When the user provides an invalid flag or invalid command, Cobra responds by When the user provides an invalid flag or invalid command, Cobra responds by
@ -566,30 +519,27 @@ showing the user the 'usage'.
You may recognize this from the help above. That's because the default help You may recognize this from the help above. That's because the default help
embeds the usage as part of its output. embeds the usage as part of its output.
```console $ cobra-cli --invalid
$ cobra-cli --invalid Error: unknown flag: --invalid
Error: unknown flag: --invalid Usage:
Usage: cobra-cli [command]
cobra-cli [command]
Available Commands: Available Commands:
add Add a command to a Cobra Application add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell completion Generate the autocompletion script for the specified shell
help Help about any command help Help about any command
init Initialize a Cobra Application init Initialize a Cobra Application
Flags: Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME") -a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml) --config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra-cli -h, --help help for cobra-cli
-l, --license string name of license for the project -l, --license string name of license for the project
--viper use Viper for configuration --viper use Viper for configuration
Use "cobra [command] --help" for more information about a command. Use "cobra [command] --help" for more information about a command.
```
### Defining your own usage ### Defining your own usage
You can provide your own usage function or template for Cobra to use. You can provide your own usage function or template for Cobra to use.
Like help, the function and template are overridable through public methods: Like help, the function and template are overridable through public methods:
@ -598,9 +548,6 @@ cmd.SetUsageFunc(f func(*Command) error)
cmd.SetUsageTemplate(s string) cmd.SetUsageTemplate(s string)
``` ```
Note that templates specified with `SetUsageTemplate` are evaluated using
`text/template` which can increase the size of the compiled executable.
## Version Flag ## Version Flag
Cobra adds a top-level '--version' flag if the Version field is set on the root command. Cobra adds a top-level '--version' flag if the Version field is set on the root command.
@ -608,18 +555,9 @@ Running an application with the '--version' flag will print the version to stdou
the version template. The template can be customized using the the version template. The template can be customized using the
`cmd.SetVersionTemplate(s string)` function. `cmd.SetVersionTemplate(s string)` function.
Note that templates specified with `SetVersionTemplate` are evaluated using
`text/template` which can increase the size of the compiled executable.
## 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 ## 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. 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: 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:
- `PersistentPreRun` - `PersistentPreRun`
- `PreRun` - `PreRun`
@ -702,15 +640,11 @@ Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun 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 ## 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: 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:
```console ```
$ hugo srever $ hugo srever
Error: unknown command "srever" for "hugo" Error: unknown command "srever" for "hugo"
@ -737,7 +671,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 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: you don't want aliases. Example:
```console ```
$ kubectl remove $ kubectl remove
Error: unknown command "remove" for "kubectl" Error: unknown command "remove" for "kubectl"
@ -749,71 +683,12 @@ Run 'kubectl help' for usage.
## Generating documentation for your command ## Generating documentation for your command
Cobra can generate documentation based on subcommands, flags, etc. Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
Read more about it in the [docs generation documentation](docgen/_index.md).
## Generating shell completions ## Generating shell completions
Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. 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).
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 ## Providing Active Help
Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. 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).
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:
```console
$ 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-2023 The Cobra Authors // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@ -90,7 +90,6 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
compCmd = ShellCompNoDescRequestCmd compCmd = ShellCompNoDescRequestCmd
} }
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
compdef _%[1]s %[1]s
# zsh completion for %-36[1]s -*- shell-script -*- # zsh completion for %-36[1]s -*- shell-script -*-
@ -109,9 +108,8 @@ _%[1]s()
local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveNoFileComp=%[5]d
local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterFileExt=%[6]d
local shellCompDirectiveFilterDirs=%[7]d local shellCompDirectiveFilterDirs=%[7]d
local shellCompDirectiveKeepOrder=%[8]d
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
local -a completions local -a completions
__%[1]s_debug "\n========= starting completion logic ==========" __%[1]s_debug "\n========= starting completion logic =========="
@ -179,7 +177,7 @@ _%[1]s()
return return
fi fi
local activeHelpMarker="%[9]s" local activeHelpMarker="%[8]s"
local endIndex=${#activeHelpMarker} local endIndex=${#activeHelpMarker}
local startIndex=$((${#activeHelpMarker}+1)) local startIndex=$((${#activeHelpMarker}+1))
local hasActiveHelp=0 local hasActiveHelp=0
@ -229,11 +227,6 @@ _%[1]s()
noSpace="-S ''" noSpace="-S ''"
fi fi
if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
__%[1]s_debug "Activating keep order."
keepOrder="-V"
fi
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
# File extension filtering # File extension filtering
local filteringCmd local filteringCmd
@ -269,7 +262,7 @@ _%[1]s()
return $result return $result
else else
__%[1]s_debug "Calling _describe" __%[1]s_debug "Calling _describe"
if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then if eval _describe "completions" completions $flagPrefix $noSpace; then
__%[1]s_debug "_describe found some completions" __%[1]s_debug "_describe found some completions"
# Return the success of having called _describe # Return the success of having called _describe
@ -303,6 +296,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then
fi fi
`, name, compCmd, `, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
activeHelpMarker)) activeHelpMarker))
} }

View file

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

View file

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