mirror of
https://github.com/spf13/cobra
synced 2025-05-04 20:37:24 +00:00
Compare commits
60 commits
Author | SHA1 | Date | |
---|---|---|---|
|
ceb39aba25 | ||
|
c25b598345 | ||
|
4f9ef8cdbb | ||
|
1995054b00 | ||
|
f98cf4216d | ||
|
0d417d8f77 | ||
|
40b5bc1437 | ||
|
a97f9fd47b | ||
|
5f9c40898e | ||
|
24ada7fe71 | ||
|
680936a220 | ||
|
8cb30f9ca5 | ||
|
17b6dca2ff | ||
|
ab5cadcc1b | ||
|
4ba5566f57 | ||
|
41b26ec8bb | ||
|
611e16c322 | ||
|
09d5664f34 | ||
|
6c3c1163c6 | ||
|
01ffff4eca | ||
|
0745e55762 | ||
|
d1e9d85fcf | ||
|
9f9056765c | ||
|
8519630750 | ||
|
02326d52c0 | ||
|
5a138f143f | ||
|
3a5efaede9 | ||
|
5bef9d8d87 | ||
|
ff7c561cf7 | ||
|
11ab62158a | ||
|
78bfc837fe | ||
|
511af59cb3 | ||
|
756ba6dad6 | ||
|
371ae25d2c | ||
|
e94f6d0dd9 | ||
|
8003b74a10 | ||
|
5c2c1d627d | ||
|
5a1acea321 | ||
|
0fc86c2ffd | ||
|
6b5f577ebc | ||
|
bd914e58d6 | ||
|
1f80fa2e23 | ||
|
c69ae4c36b | ||
|
a30cee5e5a | ||
|
f34069ccf5 | ||
|
bd2655e76c | ||
|
bcfcff729e | ||
|
4fb0a66a34 | ||
|
0dec88e793 | ||
|
cbcf75eab9 | ||
|
199b7abe12 | ||
|
531ce793e3 | ||
|
c054701f6a | ||
|
41227856cd | ||
|
a73b9c391a | ||
|
df547f5fc6 | ||
|
e63925d321 | ||
|
236f3c0418 | ||
|
3d8ac432bd | ||
|
283e32d889 |
36 changed files with 1899 additions and 413 deletions
19
.github/labeler.yml
vendored
19
.github/labeler.yml
vendored
|
@ -1,17 +1,24 @@
|
|||
# changes to documentation generation
|
||||
"area/docs-generation": doc/**/*
|
||||
"area/docs-generation":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'doc/**'
|
||||
|
||||
# changes to the core cobra command
|
||||
"area/cobra-command":
|
||||
- any: ['./cobra.go', './cobra_test.go', './*command*.go']
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: ['./cobra.go', './cobra_test.go', './*command*.go']
|
||||
|
||||
# changes made to command flags/args
|
||||
"area/flags": ./args*.go
|
||||
"area/flags":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: './args*.go'
|
||||
|
||||
# changes to Github workflows
|
||||
"area/github": .github/**/*
|
||||
"area/github":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: '.github/**'
|
||||
|
||||
# changes to shell completions
|
||||
"area/shell-completion":
|
||||
- ./*completions*
|
||||
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: './*completions*'
|
||||
|
|
2
.github/workflows/labeler.yml
vendored
2
.github/workflows/labeler.yml
vendored
|
@ -12,7 +12,7 @@ jobs:
|
|||
pull-requests: write # for actions/labeler to add labels to PRs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v4
|
||||
- uses: actions/labeler@v5
|
||||
with:
|
||||
repo-token: "${{ github.token }}"
|
||||
|
||||
|
|
33
.github/workflows/size-labeler.yml
vendored
33
.github/workflows/size-labeler.yml
vendored
|
@ -1,33 +0,0 @@
|
|||
# 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.’
|
15
.github/workflows/test.yml
vendored
15
.github/workflows/test.yml
vendored
|
@ -41,15 +41,13 @@ jobs:
|
|||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '^1.21'
|
||||
go-version: '^1.22'
|
||||
check-latest: true
|
||||
cache: true
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: golangci/golangci-lint-action@v3.7.0
|
||||
- uses: golangci/golangci-lint-action@v4.0.0
|
||||
with:
|
||||
version: latest
|
||||
args: --verbose
|
||||
|
@ -68,13 +66,16 @@ jobs:
|
|||
- 19
|
||||
- 20
|
||||
- 21
|
||||
- 22
|
||||
- 23
|
||||
- 24
|
||||
name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'
|
||||
runs-on: ${{ matrix.platform }}-latest
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.${{ matrix.go }}.x
|
||||
cache: true
|
||||
|
@ -110,7 +111,7 @@ jobs:
|
|||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/cache@v3
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-${{ matrix.go }}-${{ hashFiles('**/go.sum') }}
|
||||
|
|
|
@ -26,33 +26,28 @@ linters:
|
|||
- errcheck
|
||||
#- exhaustive
|
||||
#- funlen
|
||||
- gas
|
||||
#- gochecknoinits
|
||||
- goconst
|
||||
#- gocritic
|
||||
- gocritic
|
||||
#- gocyclo
|
||||
#- gofmt
|
||||
- gofmt
|
||||
- goimports
|
||||
- golint
|
||||
#- gomnd
|
||||
#- goprintffuncname
|
||||
#- gosec
|
||||
#- gosimple
|
||||
- gosec
|
||||
- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- interfacer
|
||||
#- lll
|
||||
- maligned
|
||||
- megacheck
|
||||
#- misspell
|
||||
- misspell
|
||||
#- nakedret
|
||||
#- noctx
|
||||
#- nolintlint
|
||||
- nolintlint
|
||||
#- rowserrcheck
|
||||
#- scopelint
|
||||
#- staticcheck
|
||||
- staticcheck
|
||||
#- structcheck ! deprecated since v1.49.0; replaced by 'unused'
|
||||
#- stylecheck
|
||||
- stylecheck
|
||||
#- typecheck
|
||||
- unconvert
|
||||
#- unparam
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||

|
||||
|
||||

|
||||
|
||||
Cobra is a library for creating powerful modern CLI applications.
|
||||
|
||||
|
@ -105,7 +106,7 @@ go install github.com/spf13/cobra-cli@latest
|
|||
|
||||
For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
|
||||
|
||||
For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md).
|
||||
For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md).
|
||||
|
||||
# License
|
||||
|
||||
|
|
105
SECURITY.md
Normal file
105
SECURITY.md
Normal file
|
@ -0,0 +1,105 @@
|
|||
# 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.*
|
|
@ -17,21 +17,17 @@ package cobra
|
|||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
activeHelpMarker = "_activeHelp_ "
|
||||
// The below values should not be changed: programs will be using them explicitly
|
||||
// in their user documentation, and users will be using them explicitly.
|
||||
activeHelpEnvVarSuffix = "_ACTIVE_HELP"
|
||||
activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
|
||||
activeHelpEnvVarSuffix = "ACTIVE_HELP"
|
||||
activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix
|
||||
activeHelpGlobalDisable = "0"
|
||||
)
|
||||
|
||||
var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
|
||||
|
||||
// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
|
||||
// Such strings will be processed by the completion script and will be shown as ActiveHelp
|
||||
// to the user.
|
||||
|
@ -39,7 +35,7 @@ var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
|
|||
// 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
|
||||
// ActiveHelp line will be shown below the previous ones when completion is triggered.
|
||||
func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
|
||||
func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion {
|
||||
return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
|
||||
}
|
||||
|
||||
|
@ -60,8 +56,5 @@ func GetActiveHelpConfig(cmd *Command) string {
|
|||
// 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 `_`.
|
||||
func activeHelpEnvVar(name string) string {
|
||||
// This format should not be changed: users will be using it explicitly.
|
||||
activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
|
||||
activeHelpEnvVar = activeHelpEnvVarPrefixSubstRegexp.ReplaceAllString(activeHelpEnvVar, "_")
|
||||
return activeHelpEnvVar
|
||||
return configEnvVar(name, activeHelpEnvVarSuffix)
|
||||
}
|
||||
|
|
4
args.go
4
args.go
|
@ -52,9 +52,9 @@ func OnlyValidArgs(cmd *Command, args []string) error {
|
|||
if len(cmd.ValidArgs) > 0 {
|
||||
// Remove any description that may be included in ValidArgs.
|
||||
// A description is following a tab character.
|
||||
var validArgs []string
|
||||
validArgs := make([]string, 0, len(cmd.ValidArgs))
|
||||
for _, v := range cmd.ValidArgs {
|
||||
validArgs = append(validArgs, strings.Split(v, "\t")[0])
|
||||
validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0])
|
||||
}
|
||||
for _, v := range args {
|
||||
if !stringInSlice(v, validArgs) {
|
||||
|
|
|
@ -597,19 +597,16 @@ func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
|
|||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
for key := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
if flag.Value.Type() != "bool" {
|
||||
format += "="
|
||||
}
|
||||
format += cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
|
||||
if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok {
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
if flag.Value.Type() != "bool" {
|
||||
format += "="
|
||||
}
|
||||
format += cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
|
||||
|
||||
if len(flag.Shorthand) > 0 {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
|
||||
}
|
||||
if len(flag.Shorthand) > 0 {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
@ -621,7 +618,7 @@ func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
|
|||
for _, value := range cmd.ValidArgs {
|
||||
// Remove any description that may be included following a tab character.
|
||||
// Descriptions are not supported by bash completion.
|
||||
value = strings.Split(value, "\t")[0]
|
||||
value = strings.SplitN(value, "\t", 2)[0]
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
|
||||
}
|
||||
if cmd.ValidArgsFunction != nil {
|
||||
|
|
|
@ -146,7 +146,7 @@ __%[1]s_process_completion_results() {
|
|||
|
||||
if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
|
||||
# File extension filtering
|
||||
local fullFilter filter filteringCmd
|
||||
local fullFilter="" filter filteringCmd
|
||||
|
||||
# Do not use quotes around the $completions variable or else newline
|
||||
# characters will be kept.
|
||||
|
@ -177,20 +177,71 @@ __%[1]s_process_completion_results() {
|
|||
__%[1]s_handle_special_char "$cur" =
|
||||
|
||||
# Print the activeHelp statements before we finish
|
||||
if ((${#activeHelp[*]} != 0)); then
|
||||
printf "\n";
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
printf "\n"
|
||||
__%[1]s_handle_activeHelp
|
||||
}
|
||||
|
||||
# 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[@]}"
|
||||
__%[1]s_handle_activeHelp() {
|
||||
# Print the activeHelp statements
|
||||
if ((${#activeHelp[*]} != 0)); then
|
||||
if [ -z $COMP_TYPE ]; then
|
||||
# Bash v3 does not set the COMP_TYPE variable.
|
||||
printf "\n";
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
printf "\n"
|
||||
__%[1]s_reprint_commandLine
|
||||
return
|
||||
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
|
||||
}
|
||||
|
||||
|
@ -201,6 +252,8 @@ __%[1]s_extract_activeHelp() {
|
|||
local endIndex=${#activeHelpMarker}
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
[[ -z $comp ]] && continue
|
||||
|
||||
if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
|
||||
comp=${comp:endIndex}
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
|
@ -223,16 +276,21 @@ __%[1]s_handle_completion_types() {
|
|||
# If the user requested inserting one completion at a time, or all
|
||||
# completions at once on the command-line we must remove the descriptions.
|
||||
# https://github.com/spf13/cobra/issues/1508
|
||||
local tab=$'\t' comp
|
||||
while IFS='' read -r comp; do
|
||||
[[ -z $comp ]] && continue
|
||||
# Strip any description
|
||||
comp=${comp%%%%$tab*}
|
||||
# Only consider the completions that match
|
||||
if [[ $comp == "$cur"* ]]; then
|
||||
COMPREPLY+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
|
||||
# If there are no completions, we don't need to do anything
|
||||
(( ${#completions[@]} == 0 )) && return 0
|
||||
|
||||
local tab=$'\t'
|
||||
|
||||
# Strip any description and escape the completion to handled special characters
|
||||
IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}")
|
||||
|
||||
# Only consider the completions that match
|
||||
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[@]}")
|
||||
;;
|
||||
|
||||
*)
|
||||
|
@ -243,11 +301,25 @@ __%[1]s_handle_completion_types() {
|
|||
}
|
||||
|
||||
__%[1]s_handle_standard_completion_case() {
|
||||
local tab=$'\t' comp
|
||||
local tab=$'\t'
|
||||
|
||||
# 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
|
||||
if [[ "${completions[*]}" != *$tab* ]]; then
|
||||
IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
|
||||
# First, escape the completions to handle special characters
|
||||
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
|
||||
fi
|
||||
|
||||
|
@ -256,23 +328,39 @@ __%[1]s_handle_standard_completion_case() {
|
|||
# Look for the longest completion so that we can format things nicely
|
||||
while IFS='' read -r compline; do
|
||||
[[ -z $compline ]] && continue
|
||||
# Strip any description before checking the length
|
||||
comp=${compline%%%%$tab*}
|
||||
|
||||
# Before checking if the completion matches what the user typed,
|
||||
# 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
|
||||
[[ $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")
|
||||
|
||||
# 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
|
||||
longest=${#comp}
|
||||
fi
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
|
||||
# If there is a single completion left, remove the description text
|
||||
# If there is a single completion left, remove the description text and escape any special characters
|
||||
if ((${#COMPREPLY[*]} == 1)); then
|
||||
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
|
||||
comp="${COMPREPLY[0]%%%%$tab*}"
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
|
||||
COMPREPLY[0]=$comp
|
||||
else # Format the descriptions
|
||||
COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}")
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}"
|
||||
else
|
||||
# Format the descriptions
|
||||
__%[1]s_format_comp_descriptions $longest
|
||||
fi
|
||||
}
|
||||
|
|
18
cobra.go
18
cobra.go
|
@ -176,12 +176,16 @@ func rpad(s string, padding int) string {
|
|||
return fmt.Sprintf(formattedString, s)
|
||||
}
|
||||
|
||||
// tmpl executes the given template text on data, writing the result to w.
|
||||
func tmpl(w io.Writer, text string, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(templateFuncs)
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
func tmpl(text string) *tmplFunc {
|
||||
return &tmplFunc{
|
||||
tmpl: text,
|
||||
fn: func(w io.Writer, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(templateFuncs)
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
|
@ -193,8 +197,6 @@ func ld(s, t string, ignoreCase bool) int {
|
|||
d := make([][]int, len(s)+1)
|
||||
for i := range d {
|
||||
d[i] = make([]int, len(t)+1)
|
||||
}
|
||||
for i := range d {
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := range d[0] {
|
||||
|
|
259
cobra_test.go
259
cobra_test.go
|
@ -15,6 +15,11 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"text/template"
|
||||
)
|
||||
|
@ -40,3 +45,257 @@ func TestAddTemplateFunctions(t *testing.T) {
|
|||
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLevenshteinDistance(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
s string
|
||||
t string
|
||||
ignoreCase bool
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "Equal strings (case-sensitive)",
|
||||
s: "hello",
|
||||
t: "hello",
|
||||
ignoreCase: false,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "Equal strings (case-insensitive)",
|
||||
s: "Hello",
|
||||
t: "hello",
|
||||
ignoreCase: true,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "Different strings (case-sensitive)",
|
||||
s: "kitten",
|
||||
t: "sitting",
|
||||
ignoreCase: false,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "Different strings (case-insensitive)",
|
||||
s: "Kitten",
|
||||
t: "Sitting",
|
||||
ignoreCase: true,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "Empty strings",
|
||||
s: "",
|
||||
t: "",
|
||||
ignoreCase: false,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "One empty string",
|
||||
s: "abc",
|
||||
t: "",
|
||||
ignoreCase: false,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "Both empty strings",
|
||||
s: "",
|
||||
t: "",
|
||||
ignoreCase: true,
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Act
|
||||
got := ld(tt.s, tt.t, tt.ignoreCase)
|
||||
|
||||
// Assert
|
||||
if got != tt.expected {
|
||||
t.Errorf("Expected ld: %v\nGot: %v", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringInSlice(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
a string
|
||||
list []string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "String in slice (case-sensitive)",
|
||||
a: "apple",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "String not in slice (case-sensitive)",
|
||||
a: "pear",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "String in slice (case-insensitive)",
|
||||
a: "APPLE",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Empty slice",
|
||||
a: "apple",
|
||||
list: []string{},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Empty string",
|
||||
a: "",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Empty strings match",
|
||||
a: "",
|
||||
list: []string{"orange", ""},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Empty string in empty slice",
|
||||
a: "",
|
||||
list: []string{},
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Act
|
||||
got := stringInSlice(tt.a, tt.list)
|
||||
|
||||
// Assert
|
||||
if got != tt.expected {
|
||||
t.Errorf("Expected stringInSlice: %v\nGot: %v", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRpad(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inputString string
|
||||
padding int
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "Padding required",
|
||||
inputString: "Hello",
|
||||
padding: 10,
|
||||
expected: "Hello ",
|
||||
},
|
||||
{
|
||||
name: "No padding required",
|
||||
inputString: "World",
|
||||
padding: 5,
|
||||
expected: "World",
|
||||
},
|
||||
{
|
||||
name: "Empty string",
|
||||
inputString: "",
|
||||
padding: 8,
|
||||
expected: " ",
|
||||
},
|
||||
{
|
||||
name: "Zero padding",
|
||||
inputString: "cobra",
|
||||
padding: 0,
|
||||
expected: "cobra",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Act
|
||||
got := rpad(tt.inputString, tt.padding)
|
||||
|
||||
// Assert
|
||||
if got != tt.expected {
|
||||
t.Errorf("Expected rpad: %v\nGot: %v", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
|
|
361
command.go
361
command.go
|
@ -33,6 +33,9 @@ import (
|
|||
const (
|
||||
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
|
||||
|
@ -80,11 +83,11 @@ type Command struct {
|
|||
Example string
|
||||
|
||||
// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
|
||||
ValidArgs []string
|
||||
ValidArgs []Completion
|
||||
// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.
|
||||
// It is a dynamic version of using ValidArgs.
|
||||
// Only one of ValidArgs and ValidArgsFunction can be used for a command.
|
||||
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
ValidArgsFunction CompletionFunc
|
||||
|
||||
// Expected arguments
|
||||
Args PositionalArgs
|
||||
|
@ -154,8 +157,10 @@ type Command struct {
|
|||
// pflags contains persistent flags.
|
||||
pflags *flag.FlagSet
|
||||
// lflags contains local flags.
|
||||
// This field does not represent internal state, it's used as a cache to optimise LocalFlags function call
|
||||
lflags *flag.FlagSet
|
||||
// iflags contains inherited flags.
|
||||
// This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call
|
||||
iflags *flag.FlagSet
|
||||
// parentsPflags is all persistent flags of cmd's parents.
|
||||
parentsPflags *flag.FlagSet
|
||||
|
@ -166,12 +171,12 @@ type Command struct {
|
|||
// usageFunc is usage func defined by user.
|
||||
usageFunc func(*Command) error
|
||||
// usageTemplate is usage template defined by user.
|
||||
usageTemplate string
|
||||
usageTemplate *tmplFunc
|
||||
// flagErrorFunc is func defined by user and it's called when the parsing of
|
||||
// flags returns an error.
|
||||
flagErrorFunc func(*Command, error) error
|
||||
// helpTemplate is help template defined by user.
|
||||
helpTemplate string
|
||||
helpTemplate *tmplFunc
|
||||
// helpFunc is help func defined by user.
|
||||
helpFunc func(*Command, []string)
|
||||
// helpCommand is command with usage 'help'. If it's not defined by user,
|
||||
|
@ -184,7 +189,7 @@ type Command struct {
|
|||
completionCommandGroupID string
|
||||
|
||||
// versionTemplate is the version template defined by user.
|
||||
versionTemplate string
|
||||
versionTemplate *tmplFunc
|
||||
|
||||
// errPrefix is the error message prefix defined by user.
|
||||
errPrefix string
|
||||
|
@ -279,6 +284,7 @@ func (c *Command) SetArgs(a []string) {
|
|||
|
||||
// SetOutput sets the destination for usage and error messages.
|
||||
// If output is nil, os.Stderr is used.
|
||||
//
|
||||
// Deprecated: Use SetOut and/or SetErr instead
|
||||
func (c *Command) SetOutput(output io.Writer) {
|
||||
c.outWriter = output
|
||||
|
@ -310,7 +316,11 @@ func (c *Command) SetUsageFunc(f func(*Command) error) {
|
|||
|
||||
// SetUsageTemplate sets usage template. Can be defined by Application.
|
||||
func (c *Command) SetUsageTemplate(s string) {
|
||||
c.usageTemplate = s
|
||||
if s == "" {
|
||||
c.usageTemplate = nil
|
||||
return
|
||||
}
|
||||
c.usageTemplate = tmpl(s)
|
||||
}
|
||||
|
||||
// SetFlagErrorFunc sets a function to generate an error when flag parsing
|
||||
|
@ -346,12 +356,20 @@ func (c *Command) SetCompletionCommandGroupID(groupID string) {
|
|||
|
||||
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
|
||||
func (c *Command) SetHelpTemplate(s string) {
|
||||
c.helpTemplate = s
|
||||
if s == "" {
|
||||
c.helpTemplate = nil
|
||||
return
|
||||
}
|
||||
c.helpTemplate = tmpl(s)
|
||||
}
|
||||
|
||||
// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
|
||||
func (c *Command) SetVersionTemplate(s string) {
|
||||
c.versionTemplate = s
|
||||
if 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.
|
||||
|
@ -432,7 +450,8 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
|
|||
}
|
||||
return func(c *Command) error {
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
|
||||
fn := c.getUsageTemplateFunc()
|
||||
err := fn(c.OutOrStderr(), c)
|
||||
if err != nil {
|
||||
c.PrintErrln(err)
|
||||
}
|
||||
|
@ -440,6 +459,19 @@ 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.
|
||||
// Used when a user provides invalid input.
|
||||
// Can be defined by user by overriding UsageFunc.
|
||||
|
@ -458,15 +490,30 @@ func (c *Command) HelpFunc() func(*Command, []string) {
|
|||
}
|
||||
return func(c *Command, a []string) {
|
||||
c.mergePersistentFlags()
|
||||
fn := c.getHelpTemplateFunc()
|
||||
// The help should be sent to stdout
|
||||
// See https://github.com/spf13/cobra/issues/1002
|
||||
err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
|
||||
err := fn(c.OutOrStdout(), c)
|
||||
if err != nil {
|
||||
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.
|
||||
// Used when a user calls help [command].
|
||||
// Can be defined by user by overriding HelpFunc.
|
||||
|
@ -541,71 +588,55 @@ func (c *Command) NamePadding() int {
|
|||
}
|
||||
|
||||
// UsageTemplate returns usage template for the command.
|
||||
// This function is kept for backwards-compatibility reasons.
|
||||
func (c *Command) UsageTemplate() string {
|
||||
if c.usageTemplate != "" {
|
||||
return c.usageTemplate
|
||||
if c.usageTemplate != nil {
|
||||
return c.usageTemplate.tmpl
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.UsageTemplate()
|
||||
}
|
||||
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}}
|
||||
`
|
||||
return defaultUsageTemplate
|
||||
}
|
||||
|
||||
// HelpTemplate return help template for the command.
|
||||
// This function is kept for backwards-compatibility reasons.
|
||||
func (c *Command) HelpTemplate() string {
|
||||
if c.helpTemplate != "" {
|
||||
return c.helpTemplate
|
||||
if c.helpTemplate != nil {
|
||||
return c.helpTemplate.tmpl
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.HelpTemplate()
|
||||
}
|
||||
return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
|
||||
|
||||
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
|
||||
return defaultHelpTemplate
|
||||
}
|
||||
|
||||
// VersionTemplate return version template for the command.
|
||||
// This function is kept for backwards-compatibility reasons.
|
||||
func (c *Command) VersionTemplate() string {
|
||||
if c.versionTemplate != "" {
|
||||
return c.versionTemplate
|
||||
if c.versionTemplate != nil {
|
||||
return c.versionTemplate.tmpl
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.VersionTemplate()
|
||||
}
|
||||
return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
|
||||
`
|
||||
return defaultVersionTemplate
|
||||
}
|
||||
|
||||
// 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
|
||||
|
@ -706,7 +737,7 @@ Loop:
|
|||
// 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 := []string{}
|
||||
ret := make([]string, 0, len(args)-1)
|
||||
ret = append(ret, args[:pos]...)
|
||||
ret = append(ret, args[pos+1:]...)
|
||||
return ret
|
||||
|
@ -754,14 +785,14 @@ func (c *Command) findSuggestions(arg string) string {
|
|||
if c.SuggestionsMinimumDistance <= 0 {
|
||||
c.SuggestionsMinimumDistance = 2
|
||||
}
|
||||
suggestionsString := ""
|
||||
var sb strings.Builder
|
||||
if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
|
||||
suggestionsString += "\n\nDid you mean this?\n"
|
||||
sb.WriteString("\n\nDid you mean this?\n")
|
||||
for _, s := range suggestions {
|
||||
suggestionsString += fmt.Sprintf("\t%v\n", s)
|
||||
_, _ = fmt.Fprintf(&sb, "\t%v\n", s)
|
||||
}
|
||||
}
|
||||
return suggestionsString
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (c *Command) findNext(next string) *Command {
|
||||
|
@ -873,7 +904,7 @@ func (c *Command) ArgsLenAtDash() int {
|
|||
|
||||
func (c *Command) execute(a []string) (err error) {
|
||||
if c == nil {
|
||||
return fmt.Errorf("Called Execute() on a nil Command")
|
||||
return fmt.Errorf("called Execute() on a nil Command")
|
||||
}
|
||||
|
||||
if len(c.Deprecated) > 0 {
|
||||
|
@ -892,7 +923,7 @@ func (c *Command) execute(a []string) (err error) {
|
|||
|
||||
// If help is called, regardless of other flags, return we want help.
|
||||
// Also say we need help if the command isn't runnable.
|
||||
helpVal, err := c.Flags().GetBool("help")
|
||||
helpVal, err := c.Flags().GetBool(helpFlagName)
|
||||
if err != nil {
|
||||
// should be impossible to get here as we always declare a help
|
||||
// flag in InitDefaultHelpFlag()
|
||||
|
@ -912,7 +943,8 @@ func (c *Command) execute(a []string) (err error) {
|
|||
return err
|
||||
}
|
||||
if versionVal {
|
||||
err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)
|
||||
fn := c.getVersionTemplateFunc()
|
||||
err := fn(c.OutOrStdout(), c)
|
||||
if err != nil {
|
||||
c.Println(err)
|
||||
}
|
||||
|
@ -1066,12 +1098,6 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
|
||||
// initialize help at the last point to allow for user overriding
|
||||
c.InitDefaultHelpCmd()
|
||||
// initialize completion at the last point to allow for user overriding
|
||||
c.InitDefaultCompletionCmd()
|
||||
|
||||
// Now that all commands have been created, let's make sure all groups
|
||||
// are properly created also
|
||||
c.checkCommandGroups()
|
||||
|
||||
args := c.args
|
||||
|
||||
|
@ -1080,9 +1106,16 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
args = os.Args[1:]
|
||||
}
|
||||
|
||||
// initialize the hidden command to be used for shell completion
|
||||
// initialize the __complete command to be used for shell completion
|
||||
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
|
||||
if c.TraverseChildren {
|
||||
cmd, flags, err = c.Traverse(args)
|
||||
|
@ -1185,15 +1218,16 @@ func (c *Command) checkCommandGroups() {
|
|||
// If c already has help flag, it will do nothing.
|
||||
func (c *Command) InitDefaultHelpFlag() {
|
||||
c.mergePersistentFlags()
|
||||
if c.Flags().Lookup("help") == nil {
|
||||
if c.Flags().Lookup(helpFlagName) == nil {
|
||||
usage := "help for "
|
||||
if c.Name() == "" {
|
||||
name := c.DisplayName()
|
||||
if name == "" {
|
||||
usage += "this command"
|
||||
} else {
|
||||
usage += c.Name()
|
||||
usage += name
|
||||
}
|
||||
c.Flags().BoolP("help", "h", false, usage)
|
||||
_ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
|
||||
c.Flags().BoolP(helpFlagName, "h", false, usage)
|
||||
_ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1212,7 +1246,7 @@ func (c *Command) InitDefaultVersionFlag() {
|
|||
if c.Name() == "" {
|
||||
usage += "this command"
|
||||
} else {
|
||||
usage += c.Name()
|
||||
usage += c.DisplayName()
|
||||
}
|
||||
if c.Flags().ShorthandLookup("v") == nil {
|
||||
c.Flags().BoolP("version", "v", false, usage)
|
||||
|
@ -1236,9 +1270,9 @@ func (c *Command) InitDefaultHelpCmd() {
|
|||
Use: "help [command]",
|
||||
Short: "Help about any command",
|
||||
Long: `Help provides help for any command in the application.
|
||||
Simply type ` + c.Name() + ` help [path to command] for full details.`,
|
||||
ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
var completions []string
|
||||
Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
|
||||
ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {
|
||||
var completions []Completion
|
||||
cmd, _, e := c.Root().Find(args)
|
||||
if e != nil {
|
||||
return nil, ShellCompDirectiveNoFileComp
|
||||
|
@ -1250,7 +1284,7 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
|
|||
for _, subCmd := range cmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {
|
||||
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1262,6 +1296,11 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
|
|||
c.Printf("Unknown help topic %#q\n", args)
|
||||
CheckErr(c.Root().Usage())
|
||||
} 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.InitDefaultVersionFlag() // make possible 'version' flag to be shown
|
||||
CheckErr(cmd.Help())
|
||||
|
@ -1427,6 +1466,12 @@ func (c *Command) CommandPath() string {
|
|||
if c.HasParent() {
|
||||
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
|
||||
}
|
||||
|
@ -1436,10 +1481,11 @@ func (c *Command) CommandPath() string {
|
|||
// UseLine puts out the full usage for a given command (including parents).
|
||||
func (c *Command) UseLine() string {
|
||||
var useline string
|
||||
use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)
|
||||
if c.HasParent() {
|
||||
useline = c.parent.CommandPath() + " " + c.Use
|
||||
useline = c.parent.CommandPath() + " " + use
|
||||
} else {
|
||||
useline = c.Use
|
||||
useline = use
|
||||
}
|
||||
if c.DisableFlagsInUseLine {
|
||||
return useline
|
||||
|
@ -1452,7 +1498,6 @@ func (c *Command) UseLine() string {
|
|||
|
||||
// DebugFlags used to determine which flags have been assigned to which commands
|
||||
// and which persist.
|
||||
// nolint:goconst
|
||||
func (c *Command) DebugFlags() {
|
||||
c.Println("DebugFlags called on", c.Name())
|
||||
var debugflags func(*Command)
|
||||
|
@ -1642,7 +1687,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f
|
|||
// to this command (local and persistent declared here and by all parents).
|
||||
func (c *Command) Flags() *flag.FlagSet {
|
||||
if c.flags == nil {
|
||||
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
if c.flagErrorBuf == nil {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
}
|
||||
|
@ -1653,10 +1698,11 @@ func (c *Command) Flags() *flag.FlagSet {
|
|||
}
|
||||
|
||||
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
|
||||
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
||||
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
||||
persistentFlags := c.PersistentFlags()
|
||||
|
||||
out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
c.LocalFlags().VisitAll(func(f *flag.Flag) {
|
||||
if persistentFlags.Lookup(f.Name) == nil {
|
||||
out.AddFlag(f)
|
||||
|
@ -1666,11 +1712,12 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
|||
}
|
||||
|
||||
// LocalFlags returns the local FlagSet specifically set in the current command.
|
||||
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
||||
func (c *Command) LocalFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
if c.lflags == nil {
|
||||
c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
if c.flagErrorBuf == nil {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
}
|
||||
|
@ -1693,11 +1740,12 @@ func (c *Command) LocalFlags() *flag.FlagSet {
|
|||
}
|
||||
|
||||
// InheritedFlags returns all flags which were inherited from parent commands.
|
||||
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
||||
func (c *Command) InheritedFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
if c.iflags == nil {
|
||||
c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
if c.flagErrorBuf == nil {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
}
|
||||
|
@ -1718,6 +1766,7 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
|
|||
}
|
||||
|
||||
// NonInheritedFlags returns all flags which were not inherited from parent commands.
|
||||
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
||||
func (c *Command) NonInheritedFlags() *flag.FlagSet {
|
||||
return c.LocalFlags()
|
||||
}
|
||||
|
@ -1725,7 +1774,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet {
|
|||
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
|
||||
func (c *Command) PersistentFlags() *flag.FlagSet {
|
||||
if c.pflags == nil {
|
||||
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
if c.flagErrorBuf == nil {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
}
|
||||
|
@ -1738,9 +1787,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
|
|||
func (c *Command) ResetFlags() {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
c.flagErrorBuf.Reset()
|
||||
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
c.flags.SetOutput(c.flagErrorBuf)
|
||||
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
c.pflags.SetOutput(c.flagErrorBuf)
|
||||
|
||||
c.lflags = nil
|
||||
|
@ -1857,7 +1906,7 @@ func (c *Command) mergePersistentFlags() {
|
|||
// If c.parentsPflags == nil, it makes new.
|
||||
func (c *Command) updateParentsPflags() {
|
||||
if c.parentsPflags == nil {
|
||||
c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
||||
c.parentsPflags.SetOutput(c.flagErrorBuf)
|
||||
c.parentsPflags.SortFlags = false
|
||||
}
|
||||
|
@ -1883,3 +1932,141 @@ func commandNameMatches(s string, t string) bool {
|
|||
|
||||
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
|
||||
}
|
||||
|
|
178
command_test.go
178
command_test.go
|
@ -18,7 +18,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
@ -370,9 +370,32 @@ func TestAliasPrefixMatching(t *testing.T) {
|
|||
// 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: "plugin",
|
||||
Args: NoArgs,
|
||||
Use: "kubectl-plugin",
|
||||
Version: "1.0.0",
|
||||
Args: NoArgs,
|
||||
Annotations: map[string]string{
|
||||
CommandDisplayNameAnnotation: "kubectl plugin",
|
||||
},
|
||||
|
@ -387,6 +410,9 @@ func TestPlugin(t *testing.T) {
|
|||
}
|
||||
|
||||
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 {
|
||||
|
@ -394,6 +420,15 @@ func TestPlugin(t *testing.T) {
|
|||
}
|
||||
|
||||
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,
|
||||
|
@ -983,6 +1018,49 @@ 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) {
|
||||
rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
|
||||
|
||||
|
@ -1048,6 +1126,45 @@ func TestHelpExecutedOnNonRunnableChild(t *testing.T) {
|
|||
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) {
|
||||
rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}
|
||||
|
||||
|
@ -1059,6 +1176,24 @@ func TestVersionFlagExecuted(t *testing.T) {
|
|||
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) {
|
||||
rootCmd := &Command{Version: "1.0.0", Run: emptyRun}
|
||||
|
||||
|
@ -2061,12 +2196,12 @@ func TestCommandPrintRedirection(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
gotErrBytes, err := ioutil.ReadAll(errBuff)
|
||||
gotErrBytes, err := io.ReadAll(errBuff)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
gotOutBytes, err := ioutil.ReadAll(outBuff)
|
||||
gotOutBytes, err := io.ReadAll(outBuff)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
@ -2746,7 +2881,7 @@ func TestFind(t *testing.T) {
|
|||
|
||||
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`
|
||||
// {"--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"},
|
||||
|
@ -2786,3 +2921,34 @@ func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
|
186
completions.go
186
completions.go
|
@ -17,6 +17,8 @@ package cobra
|
|||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
|
@ -33,7 +35,7 @@ const (
|
|||
)
|
||||
|
||||
// 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]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
|
||||
var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{}
|
||||
|
||||
// lock for reading and writing from flagCompletionFunctions
|
||||
var flagCompletionMutex = &sync.RWMutex{}
|
||||
|
@ -115,22 +117,50 @@ type CompletionOptions struct {
|
|||
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
|
||||
// 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
|
||||
}
|
||||
|
||||
// FixedCompletions can be used to create a completion function which always
|
||||
// returns the same results.
|
||||
func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
//
|
||||
// This method returns a function that satisfies [CompletionFunc]
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
|
||||
|
@ -146,7 +176,7 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman
|
|||
}
|
||||
|
||||
// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.
|
||||
func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) {
|
||||
func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) {
|
||||
flag := c.Flag(flagName)
|
||||
if flag == nil {
|
||||
return nil, false
|
||||
|
@ -211,24 +241,29 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
// 2- Even without completions, we need to print the directive
|
||||
}
|
||||
|
||||
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
|
||||
noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd
|
||||
if !noDescriptions {
|
||||
if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {
|
||||
noDescriptions = !doDescriptions
|
||||
}
|
||||
}
|
||||
noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable
|
||||
out := finalCmd.OutOrStdout()
|
||||
for _, comp := range completions {
|
||||
if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
|
||||
// Remove all activeHelp entries in this case
|
||||
if strings.HasPrefix(comp, activeHelpMarker) {
|
||||
continue
|
||||
}
|
||||
if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {
|
||||
// Remove all activeHelp entries if it's disabled.
|
||||
continue
|
||||
}
|
||||
if noDescriptions {
|
||||
// Remove any description that may be included following a tab character.
|
||||
comp = strings.Split(comp, "\t")[0]
|
||||
comp = strings.SplitN(comp, "\t", 2)[0]
|
||||
}
|
||||
|
||||
// Make sure we only write the first line to the output.
|
||||
// This is needed if a description contains a linebreak.
|
||||
// Otherwise the shell scripts will interpret the other lines as new flags
|
||||
// and could therefore provide a wrong completion.
|
||||
comp = strings.Split(comp, "\n")[0]
|
||||
comp = strings.SplitN(comp, "\n", 2)[0]
|
||||
|
||||
// Finally trim the completion. This is especially important to get rid
|
||||
// of a trailing tab when there are no description following it.
|
||||
|
@ -237,14 +272,14 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
// although there is no description).
|
||||
comp = strings.TrimSpace(comp)
|
||||
|
||||
// Print each possible completion to stdout for the completion script to consume.
|
||||
fmt.Fprintln(finalCmd.OutOrStdout(), comp)
|
||||
// Print each possible completion to the output for the completion script to consume.
|
||||
fmt.Fprintln(out, comp)
|
||||
}
|
||||
|
||||
// As the last printout, print the completion directive for the completion script to parse.
|
||||
// The directive integer must be that last character following a single colon (:).
|
||||
// The completion script expects :<directive>
|
||||
fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
|
||||
fmt.Fprintf(out, ":%d\n", directive)
|
||||
|
||||
// Print some helpful info to stderr for the user to understand.
|
||||
// Output from stderr must be ignored by the completion script.
|
||||
|
@ -263,7 +298,15 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
}
|
||||
}
|
||||
|
||||
func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
|
||||
// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect
|
||||
// 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,
|
||||
// should not be part of the list of arguments
|
||||
toComplete := args[len(args)-1]
|
||||
|
@ -291,7 +334,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
}
|
||||
if err != nil {
|
||||
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
|
||||
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
|
||||
return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)
|
||||
}
|
||||
finalCmd.ctx = c.ctx
|
||||
|
||||
|
@ -321,7 +364,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
|
||||
// Parse the flags early so we can check if required flags are set
|
||||
if err = finalCmd.ParseFlags(finalArgs); err != nil {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
}
|
||||
|
||||
realArgCount := finalCmd.Flags().NArg()
|
||||
|
@ -333,14 +376,14 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
if flagErr != nil {
|
||||
// If error type is flagCompError and we don't want flagCompletion we should ignore the error
|
||||
if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
// Look for the --help or --version flags. If they are present,
|
||||
// there should be no further completions.
|
||||
if helpOrVersionFlagPresent(finalCmd) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil
|
||||
}
|
||||
|
||||
// We only remove the flags from the arguments if DisableFlagParsing is not set.
|
||||
|
@ -369,11 +412,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil
|
||||
}
|
||||
// Directory completion
|
||||
return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil
|
||||
}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
var completions []Completion
|
||||
var directive ShellCompDirective
|
||||
|
||||
// Enforce flag groups before doing flag completions
|
||||
|
@ -392,10 +435,14 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
// If we have not found any required flags, only then can we show regular flags
|
||||
if len(completions) == 0 {
|
||||
doCompleteFlags := func(flag *pflag.Flag) {
|
||||
if !flag.Changed ||
|
||||
_, acceptsMultiple := flag.Value.(SliceValue)
|
||||
acceptsMultiple = acceptsMultiple ||
|
||||
strings.Contains(flag.Value.Type(), "Slice") ||
|
||||
strings.Contains(flag.Value.Type(), "Array") {
|
||||
// If the flag is not already present, or if it can be specified multiple times (Array or Slice)
|
||||
strings.Contains(flag.Value.Type(), "Array") ||
|
||||
strings.HasPrefix(flag.Value.Type(), "stringTo")
|
||||
|
||||
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
|
||||
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
|
||||
}
|
||||
|
@ -455,7 +502,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
for _, subCmd := range finalCmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
|
||||
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
@ -500,7 +547,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
}
|
||||
|
||||
// Find the completion function for the flag or command
|
||||
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
var completionFn CompletionFunc
|
||||
if flag != nil && flagCompletion {
|
||||
flagCompletionMutex.RLock()
|
||||
completionFn = flagCompletionFunctions[flag]
|
||||
|
@ -511,7 +558,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
if completionFn != nil {
|
||||
// Go custom completion defined for this flag or command.
|
||||
// Call the registered completion function to get the completions.
|
||||
var comps []string
|
||||
var comps []Completion
|
||||
comps, directive = completionFn(finalCmd, finalArgs, toComplete)
|
||||
completions = append(completions, comps...)
|
||||
}
|
||||
|
@ -524,23 +571,23 @@ func helpOrVersionFlagPresent(cmd *Command) bool {
|
|||
len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
|
||||
return true
|
||||
}
|
||||
if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&
|
||||
if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil &&
|
||||
len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {
|
||||
if nonCompletableFlag(flag) {
|
||||
return []string{}
|
||||
return []Completion{}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
var completions []Completion
|
||||
flagName := "--" + flag.Name
|
||||
if strings.HasPrefix(flagName, toComplete) {
|
||||
// Flag without the =
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
completions = append(completions, CompletionWithDesc(flagName, flag.Usage))
|
||||
|
||||
// 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.
|
||||
|
@ -552,20 +599,20 @@ func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
|||
// if len(flag.NoOptDefVal) == 0 {
|
||||
// // Flag requires a value, so it can be suffixed with =
|
||||
// flagName += "="
|
||||
// completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
// completions = append(completions, CompletionWithDesc(flagName, flag.Usage))
|
||||
// }
|
||||
}
|
||||
|
||||
flagName = "-" + flag.Shorthand
|
||||
if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
completions = append(completions, CompletionWithDesc(flagName, flag.Usage))
|
||||
}
|
||||
|
||||
return completions
|
||||
}
|
||||
|
||||
func completeRequireFlags(finalCmd *Command, toComplete string) []string {
|
||||
var completions []string
|
||||
func completeRequireFlags(finalCmd *Command, toComplete string) []Completion {
|
||||
var completions []Completion
|
||||
|
||||
doCompleteRequiredFlags := func(flag *pflag.Flag) {
|
||||
if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {
|
||||
|
@ -680,8 +727,8 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
// 1- the feature has been explicitly disabled by the program,
|
||||
// 2- c has no subcommands (to avoid creating one),
|
||||
// 3- c already has a 'completion' command provided by the program.
|
||||
func (c *Command) InitDefaultCompletionCmd() {
|
||||
if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
|
||||
func (c *Command) InitDefaultCompletionCmd(args ...string) {
|
||||
if c.CompletionOptions.DisableDefaultCmd {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -694,6 +741,16 @@ func (c *Command) InitDefaultCompletionCmd() {
|
|||
|
||||
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{
|
||||
Use: compCmdName,
|
||||
Short: "Generate the autocompletion script for the specified shell",
|
||||
|
@ -707,6 +764,22 @@ See each sub-command's help for details on how to use the generated script.
|
|||
}
|
||||
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()
|
||||
noDesc := c.CompletionOptions.DisableDescriptions
|
||||
shortDesc := "Generate the autocompletion script for %s"
|
||||
|
@ -899,3 +972,34 @@ func CompError(msg string) {
|
|||
func CompErrorln(msg string) {
|
||||
CompError(fmt.Sprintf("%s\n", msg))
|
||||
}
|
||||
|
||||
// These values should not be changed: users will be using them explicitly.
|
||||
const (
|
||||
configEnvVarGlobalPrefix = "COBRA"
|
||||
configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"
|
||||
)
|
||||
|
||||
var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
|
||||
|
||||
// configEnvVar returns the name of the program-specific configuration environment
|
||||
// variable. It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the
|
||||
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
func configEnvVar(name, suffix string) string {
|
||||
// This format should not be changed: users will be using it explicitly.
|
||||
v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))
|
||||
v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")
|
||||
return v
|
||||
}
|
||||
|
||||
// getEnvConfig returns the value of the configuration environment variable
|
||||
// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper
|
||||
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
// If the value is empty or not set, the value of the environment variable
|
||||
// COBRA_<SUFFIX> is returned instead.
|
||||
func getEnvConfig(cmd *Command, suffix string) string {
|
||||
v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))
|
||||
if v == "" {
|
||||
v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
|
|
@ -18,6 +18,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
@ -670,6 +671,29 @@ func TestFlagNameCompletionInGoWithDesc(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// customMultiString is a custom Value type that accepts multiple values,
|
||||
// but does not include "Slice" or "Array" in its "Type" string.
|
||||
type customMultiString []string
|
||||
|
||||
var _ SliceValue = (*customMultiString)(nil)
|
||||
|
||||
func (s *customMultiString) String() string {
|
||||
return fmt.Sprintf("%v", *s)
|
||||
}
|
||||
|
||||
func (s *customMultiString) Set(v string) error {
|
||||
*s = append(*s, v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *customMultiString) Type() string {
|
||||
return "multi string"
|
||||
}
|
||||
|
||||
func (s *customMultiString) GetSlice() []string {
|
||||
return *s
|
||||
}
|
||||
|
||||
func TestFlagNameCompletionRepeat(t *testing.T) {
|
||||
rootCmd := &Command{
|
||||
Use: "root",
|
||||
|
@ -692,6 +716,8 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
sliceFlag := rootCmd.Flags().Lookup("slice")
|
||||
rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")
|
||||
bsliceFlag := rootCmd.Flags().Lookup("bslice")
|
||||
rootCmd.Flags().VarP(&customMultiString{}, "multi", "m", "multi string flag")
|
||||
multiFlag := rootCmd.Flags().Lookup("multi")
|
||||
|
||||
// Test that flag names are not repeated unless they are an array or slice
|
||||
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")
|
||||
|
@ -705,6 +731,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
"--array",
|
||||
"--bslice",
|
||||
"--help",
|
||||
"--multi",
|
||||
"--second",
|
||||
"--slice",
|
||||
":4",
|
||||
|
@ -727,6 +754,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
"--array",
|
||||
"--bslice",
|
||||
"--help",
|
||||
"--multi",
|
||||
"--slice",
|
||||
":4",
|
||||
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
|
||||
|
@ -736,7 +764,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
}
|
||||
|
||||
// Test that flag names are not repeated unless they are an array or slice
|
||||
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")
|
||||
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--multi", "val", "--")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
@ -744,12 +772,14 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
sliceFlag.Changed = false
|
||||
arrayFlag.Changed = false
|
||||
bsliceFlag.Changed = false
|
||||
multiFlag.Changed = false
|
||||
|
||||
expected = strings.Join([]string{
|
||||
"--array",
|
||||
"--bslice",
|
||||
"--first",
|
||||
"--help",
|
||||
"--multi",
|
||||
"--second",
|
||||
"--slice",
|
||||
":4",
|
||||
|
@ -767,6 +797,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
// Reset the flag for the next command
|
||||
sliceFlag.Changed = false
|
||||
arrayFlag.Changed = false
|
||||
multiFlag.Changed = false
|
||||
|
||||
expected = strings.Join([]string{
|
||||
"--array",
|
||||
|
@ -777,6 +808,8 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
"-f",
|
||||
"--help",
|
||||
"-h",
|
||||
"--multi",
|
||||
"-m",
|
||||
"--second",
|
||||
"-s",
|
||||
"--slice",
|
||||
|
@ -796,6 +829,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) {
|
|||
// Reset the flag for the next command
|
||||
sliceFlag.Changed = false
|
||||
arrayFlag.Changed = false
|
||||
multiFlag.Changed = false
|
||||
|
||||
expected = strings.Join([]string{
|
||||
"-a",
|
||||
|
@ -2431,7 +2465,7 @@ func TestDefaultCompletionCmd(t *testing.T) {
|
|||
Run: emptyRun,
|
||||
}
|
||||
|
||||
// Test that no completion command is created if there are not other sub-commands
|
||||
// Test that when there are no sub-commands, the completion command is not created if it is not called directly.
|
||||
assertNoErr(t, rootCmd.Execute())
|
||||
for _, cmd := range rootCmd.commands {
|
||||
if cmd.Name() == compCmdName {
|
||||
|
@ -2440,6 +2474,17 @@ func TestDefaultCompletionCmd(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// Test that when there are no sub-commands, the completion command is created when it is called directly.
|
||||
_, err := executeCommand(rootCmd, compCmdName)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
// Reset the arguments
|
||||
rootCmd.args = nil
|
||||
// Remove completion command for the next test
|
||||
removeCompCmd(rootCmd)
|
||||
|
||||
// Add a sub-command
|
||||
subCmd := &Command{
|
||||
Use: "sub",
|
||||
Run: emptyRun,
|
||||
|
@ -2561,6 +2606,42 @@ func TestDefaultCompletionCmd(t *testing.T) {
|
|||
|
||||
func TestCompleteCompletion(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
|
||||
|
||||
// Test that when there are no sub-commands, the 'completion' command is not completed
|
||||
// (because it is not created).
|
||||
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
expected := strings.Join([]string{
|
||||
":0",
|
||||
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
|
||||
|
||||
if output != expected {
|
||||
t.Errorf("expected: %q, got: %q", expected, output)
|
||||
}
|
||||
|
||||
// Test that when there are no sub-commands, completion can be triggered for the default
|
||||
// 'completion' command
|
||||
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
expected = strings.Join([]string{
|
||||
"bash",
|
||||
"fish",
|
||||
"powershell",
|
||||
"zsh",
|
||||
":4",
|
||||
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
|
||||
|
||||
if output != expected {
|
||||
t.Errorf("expected: %q, got: %q", expected, output)
|
||||
}
|
||||
|
||||
// Add a sub-command
|
||||
subCmd := &Command{
|
||||
Use: "sub",
|
||||
Run: emptyRun,
|
||||
|
@ -2568,12 +2649,12 @@ func TestCompleteCompletion(t *testing.T) {
|
|||
rootCmd.AddCommand(subCmd)
|
||||
|
||||
// Test sub-commands of the completion command
|
||||
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")
|
||||
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
expected := strings.Join([]string{
|
||||
expected = strings.Join([]string{
|
||||
"bash",
|
||||
"fish",
|
||||
"powershell",
|
||||
|
@ -2804,13 +2885,99 @@ func TestCompleteWithRootAndLegacyArgs(t *testing.T) {
|
|||
"arg1",
|
||||
"arg2",
|
||||
":4",
|
||||
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
|
||||
"Completion ended with directive: ShellCompDirectiveNoFileComp", "",
|
||||
}, "\n")
|
||||
|
||||
if output != expected {
|
||||
t.Errorf("expected: %q, got: %q", expected, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletionFuncCompatibility(t *testing.T) {
|
||||
t.Run("validate signature", func(t *testing.T) {
|
||||
t.Run("format with []string", func(t *testing.T) {
|
||||
var userComp func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
|
||||
// check against new signature
|
||||
var _ CompletionFunc = userComp
|
||||
|
||||
// check Command accepts
|
||||
cmd := Command{
|
||||
ValidArgsFunction: userComp,
|
||||
}
|
||||
|
||||
_ = cmd.RegisterFlagCompletionFunc("foo", userComp)
|
||||
})
|
||||
|
||||
t.Run("format with []Completion", func(t *testing.T) {
|
||||
var userComp func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)
|
||||
|
||||
// check against new signature
|
||||
var _ CompletionFunc = userComp
|
||||
|
||||
// check Command accepts
|
||||
cmd := Command{
|
||||
ValidArgsFunction: userComp,
|
||||
}
|
||||
|
||||
_ = cmd.RegisterFlagCompletionFunc("foo", userComp)
|
||||
})
|
||||
|
||||
t.Run("format with CompletionFunc", func(t *testing.T) {
|
||||
var userComp CompletionFunc
|
||||
|
||||
// check helper against old signature
|
||||
var _ func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) = userComp
|
||||
var _ func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) = userComp
|
||||
|
||||
// check Command accepts
|
||||
cmd := Command{
|
||||
ValidArgsFunction: userComp,
|
||||
}
|
||||
|
||||
_ = cmd.RegisterFlagCompletionFunc("foo", userComp)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("user defined completion helper", func(t *testing.T) {
|
||||
t.Run("type helper", func(t *testing.T) {
|
||||
// This is a type that may have been defined by the user of the library
|
||||
// This replicates the issue https://github.com/docker/cli/issues/5827
|
||||
// https://github.com/docker/cli/blob/b6e7eba4470ecdca460e4b63270fba8179674ad6/cli/command/completion/functions.go#L18
|
||||
type UserCompletionTypeHelper func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
|
||||
var userComp UserCompletionTypeHelper
|
||||
|
||||
// Here we are validating the existing type validates the CompletionFunc type
|
||||
var _ CompletionFunc = userComp
|
||||
|
||||
cmd := Command{
|
||||
ValidArgsFunction: userComp,
|
||||
}
|
||||
|
||||
_ = cmd.RegisterFlagCompletionFunc("foo", userComp)
|
||||
})
|
||||
|
||||
t.Run("type alias helper", func(t *testing.T) {
|
||||
// This is a type that may have been defined by the user of the library
|
||||
// This replicates the possible fix that was tried here https://github.com/docker/cli/pull/5828
|
||||
// https://github.com/docker/cli/blob/ae3d4db9f658259dace9dee515718be7c1b1f517/cli/command/completion/functions.go#L18
|
||||
type UserCompletionTypeAliasHelper = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
|
||||
var userComp UserCompletionTypeAliasHelper
|
||||
|
||||
// Here we are validating the existing type validates the CompletionFunc type
|
||||
var _ CompletionFunc = userComp
|
||||
|
||||
cmd := Command{
|
||||
ValidArgsFunction: userComp,
|
||||
}
|
||||
|
||||
_ = cmd.RegisterFlagCompletionFunc("foo", userComp)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestFixedCompletions(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
|
||||
choices := []string{"apple", "banana", "orange"}
|
||||
|
@ -2838,6 +3005,56 @@ func TestFixedCompletions(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestFixedCompletionsWithCompletionHelpers(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
|
||||
// here we are mixing string, [Completion] and [CompletionWithDesc]
|
||||
choices := []string{"apple", Completion("banana"), CompletionWithDesc("orange", "orange are orange")}
|
||||
childCmd := &Command{
|
||||
Use: "child",
|
||||
ValidArgsFunction: FixedCompletions(choices, ShellCompDirectiveNoFileComp),
|
||||
Run: emptyRun,
|
||||
}
|
||||
rootCmd.AddCommand(childCmd)
|
||||
|
||||
t.Run("completion with description", func(t *testing.T) {
|
||||
output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "a")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
expected := strings.Join([]string{
|
||||
"apple",
|
||||
"banana",
|
||||
"orange\torange are orange", // this one has the description as expected with [ShellCompRequestCmd] flag
|
||||
":4",
|
||||
"Completion ended with directive: ShellCompDirectiveNoFileComp", "",
|
||||
}, "\n")
|
||||
|
||||
if output != expected {
|
||||
t.Errorf("expected: %q, got: %q", expected, output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("completion with no description", func(t *testing.T) {
|
||||
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "a")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
expected := strings.Join([]string{
|
||||
"apple",
|
||||
"banana",
|
||||
"orange", // the description is absent as expected with [ShellCompNoDescRequestCmd] flag
|
||||
":4",
|
||||
"Completion ended with directive: ShellCompDirectiveNoFileComp", "",
|
||||
}, "\n")
|
||||
|
||||
if output != expected {
|
||||
t.Errorf("expected: %q, got: %q", expected, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompletionForGroupedFlags(t *testing.T) {
|
||||
getCmd := func() *Command {
|
||||
rootCmd := &Command{
|
||||
|
@ -3517,3 +3734,285 @@ func TestGetFlagCompletion(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetEnvConfig(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
use string
|
||||
suffix string
|
||||
cmdVar string
|
||||
globalVar string
|
||||
cmdVal string
|
||||
globalVal string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "Command envvar overrides global",
|
||||
use: "root",
|
||||
suffix: "test",
|
||||
cmdVar: "ROOT_TEST",
|
||||
globalVar: "COBRA_TEST",
|
||||
cmdVal: "cmd",
|
||||
globalVal: "global",
|
||||
expected: "cmd",
|
||||
},
|
||||
{
|
||||
desc: "Missing/empty command envvar falls back to global",
|
||||
use: "root",
|
||||
suffix: "test",
|
||||
cmdVar: "ROOT_TEST",
|
||||
globalVar: "COBRA_TEST",
|
||||
cmdVal: "",
|
||||
globalVal: "global",
|
||||
expected: "global",
|
||||
},
|
||||
{
|
||||
desc: "Missing/empty command and global envvars fall back to empty",
|
||||
use: "root",
|
||||
suffix: "test",
|
||||
cmdVar: "ROOT_TEST",
|
||||
globalVar: "COBRA_TEST",
|
||||
cmdVal: "",
|
||||
globalVal: "",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
desc: "Periods in command use transform to underscores in env var name",
|
||||
use: "foo.bar",
|
||||
suffix: "test",
|
||||
cmdVar: "FOO_BAR_TEST",
|
||||
globalVar: "COBRA_TEST",
|
||||
cmdVal: "cmd",
|
||||
globalVal: "global",
|
||||
expected: "cmd",
|
||||
},
|
||||
{
|
||||
desc: "Dashes in command use transform to underscores in env var name",
|
||||
use: "quux-BAZ",
|
||||
suffix: "test",
|
||||
cmdVar: "QUUX_BAZ_TEST",
|
||||
globalVar: "COBRA_TEST",
|
||||
cmdVal: "cmd",
|
||||
globalVal: "global",
|
||||
expected: "cmd",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
// Could make env handling cleaner with t.Setenv with Go >= 1.17
|
||||
err := os.Setenv(tc.cmdVar, tc.cmdVal)
|
||||
defer func() {
|
||||
assertNoErr(t, os.Unsetenv(tc.cmdVar))
|
||||
}()
|
||||
assertNoErr(t, err)
|
||||
err = os.Setenv(tc.globalVar, tc.globalVal)
|
||||
defer func() {
|
||||
assertNoErr(t, os.Unsetenv(tc.globalVar))
|
||||
}()
|
||||
assertNoErr(t, err)
|
||||
cmd := &Command{Use: tc.use}
|
||||
got := getEnvConfig(cmd, tc.suffix)
|
||||
if got != tc.expected {
|
||||
t.Errorf("expected: %q, got: %q", tc.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisableDescriptions(t *testing.T) {
|
||||
rootCmd := &Command{
|
||||
Use: "root",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
childCmd := &Command{
|
||||
Use: "thechild",
|
||||
Short: "The child command",
|
||||
Run: emptyRun,
|
||||
}
|
||||
rootCmd.AddCommand(childCmd)
|
||||
|
||||
specificDescriptionsEnvVar := configEnvVar(rootCmd.Name(), configEnvVarSuffixDescriptions)
|
||||
globalDescriptionsEnvVar := configEnvVar(configEnvVarGlobalPrefix, configEnvVarSuffixDescriptions)
|
||||
|
||||
const (
|
||||
descLineWithDescription = "first\tdescription"
|
||||
descLineWithoutDescription = "first"
|
||||
)
|
||||
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
comps := []string{descLineWithDescription}
|
||||
return comps, ShellCompDirectiveDefault
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
globalEnvValue string
|
||||
specificEnvValue string
|
||||
expectedLine string
|
||||
}{
|
||||
{
|
||||
"No env variables set",
|
||||
"",
|
||||
"",
|
||||
descLineWithDescription,
|
||||
},
|
||||
{
|
||||
"Global value false",
|
||||
"false",
|
||||
"",
|
||||
descLineWithoutDescription,
|
||||
},
|
||||
{
|
||||
"Specific value false",
|
||||
"",
|
||||
"false",
|
||||
descLineWithoutDescription,
|
||||
},
|
||||
{
|
||||
"Both values false",
|
||||
"false",
|
||||
"false",
|
||||
descLineWithoutDescription,
|
||||
},
|
||||
{
|
||||
"Both values true",
|
||||
"true",
|
||||
"true",
|
||||
descLineWithDescription,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
if err := os.Setenv(specificDescriptionsEnvVar, tc.specificEnvValue); err != nil {
|
||||
t.Errorf("Unexpected error setting %s: %v", specificDescriptionsEnvVar, err)
|
||||
}
|
||||
if err := os.Setenv(globalDescriptionsEnvVar, tc.globalEnvValue); err != nil {
|
||||
t.Errorf("Unexpected error setting %s: %v", globalDescriptionsEnvVar, err)
|
||||
}
|
||||
|
||||
var run = func() {
|
||||
output, err := executeCommand(rootCmd, ShellCompRequestCmd, "thechild", "")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
expected := strings.Join([]string{
|
||||
tc.expectedLine,
|
||||
":0",
|
||||
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
|
||||
if output != expected {
|
||||
t.Errorf("expected: %q, got: %q", expected, output)
|
||||
}
|
||||
}
|
||||
|
||||
run()
|
||||
|
||||
// For empty cases, test also unset state
|
||||
if tc.specificEnvValue == "" {
|
||||
if err := os.Unsetenv(specificDescriptionsEnvVar); err != nil {
|
||||
t.Errorf("Unexpected error unsetting %s: %v", specificDescriptionsEnvVar, err)
|
||||
}
|
||||
run()
|
||||
}
|
||||
if tc.globalEnvValue == "" {
|
||||
if err := os.Unsetenv(globalDescriptionsEnvVar); err != nil {
|
||||
t.Errorf("Unexpected error unsetting %s: %v", globalDescriptionsEnvVar, err)
|
||||
}
|
||||
run()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A test to make sure the InitDefaultCompletionCmd function works as expected
|
||||
// in case a project calls it directly.
|
||||
func TestInitDefaultCompletionCmd(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
hasChildCmd bool
|
||||
args []string
|
||||
expectCompCmd bool
|
||||
}{
|
||||
{
|
||||
desc: "no child command and not calling the completion command",
|
||||
hasChildCmd: false,
|
||||
args: []string{"somearg"},
|
||||
expectCompCmd: false,
|
||||
},
|
||||
{
|
||||
desc: "no child command but calling the completion command",
|
||||
hasChildCmd: false,
|
||||
args: []string{"completion"},
|
||||
expectCompCmd: true,
|
||||
},
|
||||
{
|
||||
desc: "no child command but calling __complete on the root command",
|
||||
hasChildCmd: false,
|
||||
args: []string{"__complete", ""},
|
||||
expectCompCmd: false,
|
||||
},
|
||||
{
|
||||
desc: "no child command but calling __complete on the completion command",
|
||||
hasChildCmd: false,
|
||||
args: []string{"__complete", "completion", ""},
|
||||
expectCompCmd: true,
|
||||
},
|
||||
{
|
||||
desc: "with child command",
|
||||
hasChildCmd: true,
|
||||
args: []string{"child"},
|
||||
expectCompCmd: true,
|
||||
},
|
||||
{
|
||||
desc: "no child command not passing args",
|
||||
hasChildCmd: false,
|
||||
args: nil,
|
||||
expectCompCmd: false,
|
||||
},
|
||||
{
|
||||
desc: "with child command not passing args",
|
||||
hasChildCmd: true,
|
||||
args: nil,
|
||||
expectCompCmd: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", Run: emptyRun}
|
||||
childCmd := &Command{Use: "child", Run: emptyRun}
|
||||
|
||||
expectedNumSubCommands := 0
|
||||
if tc.hasChildCmd {
|
||||
rootCmd.AddCommand(childCmd)
|
||||
expectedNumSubCommands++
|
||||
}
|
||||
|
||||
if tc.expectCompCmd {
|
||||
expectedNumSubCommands++
|
||||
}
|
||||
|
||||
if len(tc.args) > 0 && tc.args[0] == "__complete" {
|
||||
expectedNumSubCommands++
|
||||
}
|
||||
|
||||
// Setup the __complete command to mimic real world scenarios
|
||||
rootCmd.initCompleteCmd(tc.args)
|
||||
|
||||
// Call the InitDefaultCompletionCmd function directly
|
||||
if tc.args == nil {
|
||||
rootCmd.InitDefaultCompletionCmd()
|
||||
} else {
|
||||
rootCmd.InitDefaultCompletionCmd(tc.args...)
|
||||
}
|
||||
|
||||
// Check if the completion command was added
|
||||
if len(rootCmd.Commands()) != expectedNumSubCommands {
|
||||
t.Errorf("Expected %d subcommands, got %d", expectedNumSubCommands, len(rootCmd.Commands()))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -133,7 +133,7 @@ func fillHeader(header *GenManHeader, name string, disableAutoGen bool) error {
|
|||
}
|
||||
header.Date = &now
|
||||
}
|
||||
header.date = (*header.Date).Format("Jan 2006")
|
||||
header.date = header.Date.Format("Jan 2006")
|
||||
if header.Source == "" && !disableAutoGen {
|
||||
header.Source = "Auto generated by spf13/cobra"
|
||||
}
|
||||
|
|
|
@ -18,7 +18,6 @@ import (
|
|||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
@ -142,9 +141,6 @@ func TestGenManSeeAlso(t *testing.T) {
|
|||
if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil {
|
||||
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 {
|
||||
t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
|
||||
}
|
||||
|
@ -168,7 +164,7 @@ func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
|
|||
func TestGenManTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
header := &GenManHeader{Section: "2"}
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-man-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
|
@ -219,7 +215,7 @@ func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
|
|||
}
|
||||
|
||||
func BenchmarkGenManToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -128,7 +128,7 @@ func GenMarkdownTree(cmd *cobra.Command, dir string) error {
|
|||
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
|
||||
}
|
||||
|
||||
// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
|
||||
// GenMarkdownTreeCustom is the same as GenMarkdownTree, but
|
||||
// with custom filePrepender and linkHandler.
|
||||
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
|
|
|
@ -16,7 +16,6 @@ package doc
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
@ -94,7 +93,7 @@ func TestGenMdNoTag(t *testing.T) {
|
|||
|
||||
func TestGenMdTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-md-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %v", err)
|
||||
}
|
||||
|
@ -110,7 +109,7 @@ func TestGenMdTree(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkGenMarkdownToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -140,7 +140,7 @@ func GenReSTTree(cmd *cobra.Command, dir string) error {
|
|||
return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
|
||||
}
|
||||
|
||||
// GenReSTTreeCustom is the the same as GenReSTTree, but
|
||||
// GenReSTTreeCustom is the same as GenReSTTree, but
|
||||
// with custom filePrepender and linkHandler.
|
||||
func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
|
|
|
@ -16,7 +16,6 @@ package doc
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
@ -81,7 +80,7 @@ func TestGenRSTNoTag(t *testing.T) {
|
|||
func TestGenRSTTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-rst-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
|
@ -97,7 +96,7 @@ func TestGenRSTTree(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkGenReSTToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -40,7 +40,7 @@ func hasSeeAlso(cmd *cobra.Command) bool {
|
|||
// that do not contain \n.
|
||||
func forceMultiLine(s string) string {
|
||||
if len(s) > 60 && !strings.Contains(s, "\n") {
|
||||
s = s + "\n"
|
||||
s += "\n"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
|
|
@ -17,7 +17,6 @@ package doc
|
|||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
@ -58,7 +57,7 @@ func TestGenYamlNoTag(t *testing.T) {
|
|||
func TestGenYamlTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-yaml-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
|
@ -85,7 +84,7 @@ func TestGenYamlDocRunnable(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkGenYamlToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -23,9 +23,9 @@ import (
|
|||
)
|
||||
|
||||
const (
|
||||
requiredAsGroup = "cobra_annotation_required_if_others_set"
|
||||
oneRequired = "cobra_annotation_one_required"
|
||||
mutuallyExclusive = "cobra_annotation_mutually_exclusive"
|
||||
requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set"
|
||||
oneRequiredAnnotation = "cobra_annotation_one_required"
|
||||
mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive"
|
||||
)
|
||||
|
||||
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
|
||||
|
@ -37,7 +37,7 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
|
|||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))
|
||||
}
|
||||
if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil {
|
||||
if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil {
|
||||
// Only errs if the flag isn't found.
|
||||
panic(err)
|
||||
}
|
||||
|
@ -53,7 +53,7 @@ func (c *Command) MarkFlagsOneRequired(flagNames ...string) {
|
|||
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, oneRequired, append(f.Annotations[oneRequired], strings.Join(flagNames, " "))); err != nil {
|
||||
if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil {
|
||||
// Only errs if the flag isn't found.
|
||||
panic(err)
|
||||
}
|
||||
|
@ -70,7 +70,7 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
|
|||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))
|
||||
}
|
||||
// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.
|
||||
if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {
|
||||
if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
@ -91,9 +91,9 @@ func (c *Command) ValidateFlagGroups() error {
|
|||
oneRequiredGroupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
flags.VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
if err := validateRequiredFlagGroups(groupStatus); err != nil {
|
||||
|
@ -130,7 +130,7 @@ func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annota
|
|||
continue
|
||||
}
|
||||
|
||||
groupStatus[group] = map[string]bool{}
|
||||
groupStatus[group] = make(map[string]bool, len(flagnames))
|
||||
for _, name := range flagnames {
|
||||
groupStatus[group][name] = false
|
||||
}
|
||||
|
@ -232,9 +232,9 @@ func (c *Command) enforceFlagGroupsForCompletion() {
|
|||
oneRequiredGroupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
c.Flags().VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
// If a flag that is part of a group is present, we make all the other flags
|
||||
|
@ -253,17 +253,17 @@ 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 {
|
||||
set := 0
|
||||
isSet := false
|
||||
|
||||
for _, isSet := range flagnameAndStatus {
|
||||
for _, isSet = range flagnameAndStatus {
|
||||
if isSet {
|
||||
set++
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// None of the flags of the group are set, mark all flags in the group
|
||||
// as required
|
||||
if set == 0 {
|
||||
if !isSet {
|
||||
for _, fName := range strings.Split(flagList, " ") {
|
||||
_ = c.MarkFlagRequired(fName)
|
||||
}
|
||||
|
|
4
go.mod
4
go.mod
|
@ -3,8 +3,8 @@ module github.com/spf13/cobra
|
|||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.3
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6
|
||||
github.com/inconshreveable/mousetrap v1.1.0
|
||||
github.com/spf13/pflag v1.0.5
|
||||
github.com/spf13/pflag v1.0.6
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
|
8
go.sum
8
go.sum
|
@ -1,11 +1,11 @@
|
|||
github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
||||
github.com/spf13/pflag v1.0.6/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/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
|
|
@ -28,8 +28,8 @@ import (
|
|||
func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
|
||||
nameForVar = strings.Replace(nameForVar, ":", "_", -1)
|
||||
nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
|
||||
nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
|
@ -162,7 +162,10 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
if (-Not $Description) {
|
||||
$Description = " "
|
||||
}
|
||||
@{Name="$Name";Description="$Description"}
|
||||
New-Object -TypeName PSCustomObject -Property @{
|
||||
Name = "$Name"
|
||||
Description = "$Description"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -240,7 +243,12 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
__%[1]s_debug "Only one completion left"
|
||||
|
||||
# insert space after value
|
||||
[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
|
||||
}
|
||||
|
||||
} else {
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
|
@ -255,7 +263,12 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
$Description = " ($($comp.Description))"
|
||||
}
|
||||
|
||||
[System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
|
||||
$CompletionText = "$($comp.Name)$Description"
|
||||
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
|
||||
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
|
||||
} else {
|
||||
$CompletionText
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -264,7 +277,13 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
# insert space after value
|
||||
# MenuComplete will automatically show the ToolTip of
|
||||
# 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
|
||||
|
@ -272,7 +291,13 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
# Like MenuComplete but we don't want to add a space here because
|
||||
# the user need to press space anyway to get the completion.
|
||||
# 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -2,28 +2,30 @@
|
|||
|
||||
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,
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
For example,
|
||||
|
||||
```console
|
||||
$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding.
|
||||
|
||||
bash-5.1$ bin/helm package [tab]
|
||||
$ bin/helm package [tab]
|
||||
Please specify the path to the chart to package
|
||||
|
||||
bash-5.1$ bin/helm package [tab][tab]
|
||||
$ bin/helm package [tab][tab]
|
||||
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.
|
||||
|
||||
## Supported shells
|
||||
|
||||
Active Help is currently only supported for the following shells:
|
||||
- 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.
|
||||
- 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.
|
||||
- Zsh
|
||||
|
||||
## 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](shell_completions.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](completions/_index.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.
|
||||
|
||||
|
@ -39,8 +41,8 @@ cmd := &cobra.Command{
|
|||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return addRepo(args)
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
var comps []string
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
var comps []cobra.Completion
|
||||
if len(args) == 0 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
} else if len(args) == 1 {
|
||||
|
@ -52,24 +54,28 @@ 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:
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
|
||||
```console
|
||||
$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana [tab]
|
||||
$ helm repo add grafana [tab]
|
||||
You must specify the URL for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
|
||||
$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
|
||||
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.
|
||||
|
||||
### 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:
|
||||
|
||||
```go
|
||||
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
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
|
||||
}
|
||||
|
@ -77,11 +83,12 @@ _ = 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.
|
||||
```
|
||||
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
|
||||
|
||||
```console
|
||||
$ bin/helm install myrelease --version 2.0.[tab]
|
||||
You must first specify the chart to install before the --version flag can be completed
|
||||
|
||||
bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
|
||||
$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
|
||||
2.0.1 2.0.2 2.0.3
|
||||
```
|
||||
|
||||
|
@ -103,11 +110,12 @@ Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function an
|
|||
should or should not be added (instead of reading the environment variable directly).
|
||||
|
||||
For example:
|
||||
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
|
||||
|
||||
var comps []string
|
||||
var comps []cobra.Completion
|
||||
if len(args) == 0 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
|
@ -124,11 +132,13 @@ ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([
|
|||
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 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.
|
||||
|
||||
## Active Help with Cobra's default completion command
|
||||
|
||||
Cobra provides a default `completion` command for programs that wish to use it.
|
||||
|
@ -138,10 +148,11 @@ details for your users.
|
|||
|
||||
## 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](shell_completions.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](completions/_index.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:
|
||||
```
|
||||
|
||||
```console
|
||||
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
|
|
|
@ -8,7 +8,8 @@ The currently supported shells are:
|
|||
- PowerShell
|
||||
|
||||
Cobra will automatically provide your program with a fully functional `completion` command,
|
||||
similarly to how it provides the `help` command.
|
||||
similarly to how it provides the `help` command. If there are no other subcommands, the
|
||||
default `completion` command will be hidden, but still functional.
|
||||
|
||||
## Creating your own completion command
|
||||
|
||||
|
@ -177,7 +178,7 @@ cmd := &cobra.Command{
|
|||
RunE: func(cmd *cobra.Command, args []string) {
|
||||
RunGet(args[0])
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
if len(args) != 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
@ -211,7 +212,7 @@ ShellCompDirectiveNoFileComp
|
|||
|
||||
// Indicates that the returned completions should be used as file extension filters.
|
||||
// For example, to complete only files of the form *.json or *.yaml:
|
||||
// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt
|
||||
// return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt
|
||||
// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
|
||||
// is a shortcut to using this directive explicitly.
|
||||
//
|
||||
|
@ -219,13 +220,13 @@ ShellCompDirectiveFilterFileExt
|
|||
|
||||
// Indicates that only directory names should be provided in file completion.
|
||||
// For example:
|
||||
// return nil, ShellCompDirectiveFilterDirs
|
||||
// return nil, cobra.ShellCompDirectiveFilterDirs
|
||||
// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
|
||||
//
|
||||
// To request directory names within another directory, the returned completions
|
||||
// should specify a single directory name within which to search. For example,
|
||||
// to complete directories within "themes/":
|
||||
// return []string{"themes"}, ShellCompDirectiveFilterDirs
|
||||
// return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
//
|
||||
ShellCompDirectiveFilterDirs
|
||||
|
||||
|
@ -259,7 +260,7 @@ Calling the `__complete` command directly allows you to run the Go debugger to t
|
|||
```go
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// 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)
|
||||
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
|
@ -293,8 +294,8 @@ As for nouns, Cobra provides a way of defining dynamic completion of flags. To
|
|||
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{"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:
|
||||
|
@ -327,8 +328,8 @@ cmd.MarkFlagFilename(flagName, "yaml", "json")
|
|||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt})
|
||||
```
|
||||
|
||||
### Limit flag completions to directory names
|
||||
|
@ -341,15 +342,15 @@ cmd.MarkFlagDirname(flagName)
|
|||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
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:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
### Descriptions for completions
|
||||
|
@ -370,15 +371,21 @@ $ helm s[tab]
|
|||
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. 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. 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:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{
|
||||
cobra.CompletionWithDesc("harbor", "An image registry"),
|
||||
cobra.CompletionWithDesc("thanos", "Long-term metrics")
|
||||
}, cobra.ShellCompDirectiveNoFileComp
|
||||
}}
|
||||
```
|
||||
or
|
||||
```go
|
||||
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
|
||||
ValidArgs: []cobra.Completion{
|
||||
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:
|
||||
|
@ -393,6 +400,9 @@ $ source <(helm completion bash --no-descriptions)
|
|||
$ helm completion [tab][tab]
|
||||
bash fish powershell zsh
|
||||
```
|
||||
|
||||
Setting the `<PROGRAM>_COMPLETION_DESCRIPTIONS` environment variable (falling back to `COBRA_COMPLETION_DESCRIPTIONS` if empty or not set) to a [falsey value](https://pkg.go.dev/strconv#ParseBool) achieves the same. `<PROGRAM>` is the name of your program with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
|
||||
## Bash completions
|
||||
|
||||
### Dependencies
|
||||
|
|
|
@ -35,7 +35,7 @@ package main
|
|||
|
||||
import (
|
||||
"log"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
|
@ -45,7 +45,7 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)
|
||||
err := doc.GenMarkdownTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
|
|
@ -35,7 +35,7 @@ package main
|
|||
|
||||
import (
|
||||
"log"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
|
@ -45,7 +45,7 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)
|
||||
err := doc.GenReSTTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
|
|
@ -34,7 +34,7 @@ This program can actually generate docs for the kubectl command in the kubernete
|
|||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
|
@ -45,7 +45,7 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)
|
||||
err := doc.GenYamlTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
|
|
@ -3,15 +3,18 @@
|
|||
- [Allero](https://github.com/allero-io/allero)
|
||||
- [Arewefastyet](https://benchmark.vitess.io)
|
||||
- [Arduino CLI](https://github.com/arduino/arduino-cli)
|
||||
- [Azion](https://github.com/aziontech/azion)
|
||||
- [Bleve](https://blevesearch.com/)
|
||||
- [Cilium](https://cilium.io/)
|
||||
- [CloudQuery](https://github.com/cloudquery/cloudquery)
|
||||
- [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)
|
||||
- [Datree](https://github.com/datreeio/datree)
|
||||
- [Delve](https://github.com/derekparker/delve)
|
||||
- [Docker (distribution)](https://github.com/docker/distribution)
|
||||
- [Encore](https://encore.dev)
|
||||
- [Etcd](https://etcd.io/)
|
||||
- [Gardener](https://github.com/gardener/gardenctl)
|
||||
- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)
|
||||
|
@ -23,6 +26,7 @@
|
|||
- [GoReleaser](https://goreleaser.com)
|
||||
- [Helm](https://helm.sh)
|
||||
- [Hugo](https://gohugo.io)
|
||||
- [Incus](https://linuxcontainers.org/incus/)
|
||||
- [Infracost](https://github.com/infracost/infracost)
|
||||
- [Istio](https://istio.io)
|
||||
- [Kool](https://github.com/kool-dev/kool)
|
||||
|
@ -30,6 +34,7 @@
|
|||
- [Kubescape](https://github.com/kubescape/kubescape)
|
||||
- [KubeVirt](https://github.com/kubevirt/kubevirt)
|
||||
- [Linkerd](https://linkerd.io/)
|
||||
- [LXC](https://github.com/canonical/lxd)
|
||||
- [Mattermost-server](https://github.com/mattermost/mattermost-server)
|
||||
- [Mercure](https://mercure.rocks/)
|
||||
- [Meroxa CLI](https://github.com/meroxa/cli)
|
||||
|
@ -55,10 +60,12 @@
|
|||
- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)
|
||||
- [Sia](https://github.com/SiaFoundation/siad)
|
||||
- [Skaffold](https://skaffold.dev/)
|
||||
- [Taikun](https://taikun.cloud/)
|
||||
- [Tendermint](https://github.com/tendermint/tendermint)
|
||||
- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
|
||||
- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)
|
||||
- [Vitess](https://vitess.io)
|
||||
- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)
|
||||
- [Werf](https://werf.io/)
|
||||
- [Zarf](https://github.com/defenseunicorns/zarf)
|
||||
- [ZITADEL](https://github.com/zitadel/zitadel)
|
||||
|
|
|
@ -3,14 +3,14 @@
|
|||
While you are welcome to provide your own organization, typically a Cobra-based
|
||||
application will follow the following organizational structure:
|
||||
|
||||
```
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
```console
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
```
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
|
||||
|
@ -18,9 +18,7 @@ In a Cobra app, typically the main.go file is very bare. It serves one purpose:
|
|||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
import "{pathToYourApp}/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
|
@ -148,9 +146,7 @@ In a Cobra app, typically the main.go file is very bare. It serves one purpose:
|
|||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
import "{pathToYourApp}/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
|
@ -197,7 +193,7 @@ its own go package.
|
|||
The suggested approach is for the parent command to use `AddCommand` to add its most immediate
|
||||
subcommands. For example, consider the following directory structure:
|
||||
|
||||
```text
|
||||
```console
|
||||
├── cmd
|
||||
│ ├── root.go
|
||||
│ └── sub1
|
||||
|
@ -301,6 +297,7 @@ command := cobra.Command{
|
|||
### Bind Flags with Config
|
||||
|
||||
You can also bind your flags with [viper](https://github.com/spf13/viper):
|
||||
|
||||
```go
|
||||
var author string
|
||||
|
||||
|
@ -320,12 +317,14 @@ More in [viper documentation](https://github.com/spf13/viper#working-with-flags)
|
|||
|
||||
Flags are optional by default. If instead you wish your command to report an error
|
||||
when a flag has not been set, mark it as required:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkFlagRequired("region")
|
||||
```
|
||||
|
||||
Or, for persistent flags:
|
||||
|
||||
```go
|
||||
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkPersistentFlagRequired("region")
|
||||
|
@ -335,6 +334,7 @@ rootCmd.MarkPersistentFlagRequired("region")
|
|||
|
||||
If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then
|
||||
Cobra can enforce that requirement:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
|
||||
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
|
||||
|
@ -343,6 +343,7 @@ rootCmd.MarkFlagsRequiredTogether("username", "password")
|
|||
|
||||
You can also prevent different flags from being provided together if they represent mutually
|
||||
exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
|
||||
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
|
||||
|
@ -351,6 +352,7 @@ rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
|
|||
|
||||
If you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`.
|
||||
This can be combined with `MarkFlagsMutuallyExclusive` to enforce exactly one flag from a given group:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
|
||||
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
|
||||
|
@ -428,7 +430,7 @@ by not providing a 'Run' for the 'rootCmd'.
|
|||
|
||||
We have only defined one flag for a single command.
|
||||
|
||||
More documentation about flags is available at https://github.com/spf13/pflag
|
||||
More documentation about flags is available at https://github.com/spf13/pflag.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
@ -502,30 +504,31 @@ create' is called. Every command will automatically have the '--help' flag adde
|
|||
The following output is automatically generated by Cobra. Nothing beyond the
|
||||
command and flag definitions are needed.
|
||||
|
||||
$ cobra-cli help
|
||||
```console
|
||||
$ cobra-cli help
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.
|
||||
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
Use "cobra-cli [command] --help" for more information about a command.
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
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
|
||||
around it. In fact, you can provide your own if you want.
|
||||
|
@ -551,6 +554,9 @@ cmd.SetHelpTemplate(s string)
|
|||
|
||||
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
|
||||
|
||||
When the user provides an invalid flag or invalid command, Cobra responds by
|
||||
|
@ -560,27 +566,30 @@ showing the user the 'usage'.
|
|||
You may recognize this from the help above. That's because the default help
|
||||
embeds the usage as part of its output.
|
||||
|
||||
$ cobra-cli --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
```console
|
||||
$ cobra-cli --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--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
|
||||
|
||||
You can provide your own usage function or template for Cobra to use.
|
||||
Like help, the function and template are overridable through public methods:
|
||||
|
||||
|
@ -589,6 +598,9 @@ cmd.SetUsageFunc(f func(*Command) error)
|
|||
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
|
||||
|
||||
Cobra adds a top-level '--version' flag if the Version field is set on the root command.
|
||||
|
@ -596,6 +608,9 @@ Running an application with the '--version' flag will print the version to stdou
|
|||
the version template. The template can be customized using the
|
||||
`cmd.SetVersionTemplate(s string)` function.
|
||||
|
||||
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.
|
||||
|
@ -695,7 +710,7 @@ Set `EnableTraverseRunHooks` global variable to `true` if you want to execute al
|
|||
|
||||
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
|
||||
Error: unknown command "srever" for "hugo"
|
||||
|
||||
|
@ -722,7 +737,7 @@ command.SuggestionsMinimumDistance = 1
|
|||
You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which
|
||||
you don't want aliases. Example:
|
||||
|
||||
```
|
||||
```console
|
||||
$ kubectl remove
|
||||
Error: unknown command "remove" for "kubectl"
|
||||
|
||||
|
@ -748,3 +763,57 @@ Read more about it in [Shell Completions](completions/_index.md).
|
|||
Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users.
|
||||
Active Help are messages (hints, warnings, etc) printed as the program is being used.
|
||||
Read more about it in [Active Help](active_help.md).
|
||||
|
||||
## Creating a plugin
|
||||
|
||||
When creating a plugin for tools like *kubectl*, the executable is named
|
||||
`kubectl-myplugin`, but it is used as `kubectl myplugin`. To fix help
|
||||
messages and completions, annotate the root command with the
|
||||
`cobra.CommandDisplayNameAnnotation` annotation.
|
||||
|
||||
### Example kubectl plugin
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
rootCmd := &cobra.Command{
|
||||
Use: "kubectl-myplugin",
|
||||
Annotations: map[string]string{
|
||||
cobra.CommandDisplayNameAnnotation: "kubectl myplugin",
|
||||
},
|
||||
}
|
||||
subCmd := &cobra.Command{
|
||||
Use: "subcmd",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("kubectl myplugin subcmd")
|
||||
},
|
||||
}
|
||||
rootCmd.AddCommand(subCmd)
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
Example run as a kubectl plugin:
|
||||
|
||||
```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.
|
||||
```
|
||||
|
|
Loading…
Add table
Reference in a new issue