Merge branch 'main' into doc-slash-commands

* main: (39 commits)
  Add '--version' flag to Help output (#1707)
  Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)
  Document option to hide the default completion cmd (#1779)
  ci: add workflow_dispatch (#1387)
  add missing license headers (#1809)
  ci: use action/setup-go's cache (#1783)
  Adjustments to documentation (#1656)
  Rename Powershell completion tests (#1803)
  Support for case-insensitive command names (#1802)
  Deprecate ExactValidArgs() and test combinations of args validators (#1643)
  Use correct stale action `exempt-` yaml keys (#1800)
  With go 1.18, we must use go install for a binary (#1726)
  Clarify SetContext documentation (#1748)
  ci: test on Golang 1.19 (#1782)
  fix: show flags that shadow parent persistent flag in child help (#1776)
  Update gopkg.in/yaml.v2 to gopkg.in/yaml.v3 (#1766)
  fix(bash-v2): activeHelp length check syntax (#1762)
  fix: correct command path in see_also for YAML doc (#1771)
  build(deps): bump github.com/inconshreveable/mousetrap (#1774)
  docs: add zitadel to the list (#1772)
  ...
This commit is contained in:
Jim Schubert 2022-10-02 21:14:54 -04:00
commit b5bc3e3275
50 changed files with 2160 additions and 171 deletions

View file

@ -39,8 +39,8 @@ jobs:
days-before-close: 30 days-before-close: 30
stale-issue-label: 'lifecycle/stale' stale-issue-label: 'lifecycle/stale'
stale-pr-label: 'lifecycle/stale' stale-pr-label: 'lifecycle/stale'
exempt-issue-label: 'lifecycle/frozen' exempt-issue-labels: 'lifecycle/frozen'
exempt-pr-label: 'lifecycle/frozen' exempt-pr-labels: 'lifecycle/frozen'
close-issue-label: 'lifecycle/rotten' close-issue-label: 'lifecycle/rotten'
close-pr-label: 'lifecycle/rotten' close-pr-label: 'lifecycle/rotten'

View file

@ -3,27 +3,52 @@ name: Test
on: on:
push: push:
pull_request: pull_request:
workflow_dispatch:
env: env:
GO111MODULE: on GO111MODULE: on
jobs: jobs:
lic-headers:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: >-
docker run
-v $(pwd):/wrk -w /wrk
ghcr.io/google/addlicense
-c 'The Cobra Authors'
-y '2013-2022'
-l apache
-ignore '.github/**'
-check
.
golangci-lint: golangci-lint:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/setup-go@v2 - uses: actions/checkout@v3
- uses: actions/setup-go@v3
with: with:
go-version: '1.17' go-version: '^1.19'
check-latest: true
cache: true
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: golangci/golangci-lint-action@v3.1.0 - uses: golangci/golangci-lint-action@v3.2.0
with: with:
version: latest version: latest
args: --verbose args: --verbose
test-unix: test-unix:
strategy: strategy:
fail-fast: false fail-fast: false
@ -32,38 +57,34 @@ jobs:
- ubuntu - ubuntu
- macOS - macOS
go: go:
- 14
- 15 - 15
- 16 - 16
- 17 - 17
- 18 - 18
- 19
name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x' name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'
runs-on: ${{ matrix.platform }}-latest runs-on: ${{ matrix.platform }}-latest
steps: steps:
- uses: actions/setup-go@v2
with:
go-version: 1.${{ matrix.go }}.x
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: actions/cache@v3 - uses: actions/setup-go@v3
with: with:
path: ~/go/pkg/mod go-version: 1.${{ matrix.go }}.x
key: ${{ runner.os }}-1.${{ matrix.go }}.x-${{ hashFiles('**/go.sum') }} cache: true
restore-keys: ${{ runner.os }}-1.${{ matrix.go }}.x-
- run: | - run: |
export GOBIN=$HOME/go/bin export GOBIN=$HOME/go/bin
case "${{ matrix.go }}" in case "${{ matrix.go }}" in
16|17|18) _version='@latest';; 14|15) _version='';;
*) _version='';; *) _version='@latest';;
esac esac
go install github.com/kyoh86/richgo"${_version}" go install github.com/kyoh86/richgo"${_version}"
go install github.com/mitchellh/gox"${_version}" go install github.com/mitchellh/gox"${_version}"
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make test - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make test
test-win: test-win:
name: MINGW64 name: MINGW64
defaults: defaults:

View file

@ -1,3 +1,17 @@
# Copyright 2013-2022 The Cobra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
run: run:
deadline: 5m deadline: 5m

View file

@ -6,7 +6,7 @@ $(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://insta
endif endif
ifeq (, $(shell which richgo)) ifeq (, $(shell which richgo))
$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo") $(warning "could not find richgo in $(PATH), run: go install github.com/kyoh86/richgo@latest")
endif endif
.PHONY: fmt lint test install_deps clean .PHONY: fmt lint test install_deps clean

View file

@ -2,8 +2,8 @@
Cobra is a library for creating powerful modern CLI applications. Cobra is a library for creating powerful modern CLI applications.
Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/), Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to [Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) [![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
@ -28,7 +28,7 @@ Cobra provides:
* Automatically generated man pages for your application * Automatically generated man pages for your application
* Command aliases so you can change things without breaking them * Command aliases so you can change things without breaking them
* The flexibility to define your own help, usage, etc. * The flexibility to define your own help, usage, etc.
* Optional seamless integration with [viper](http://github.com/spf13/viper) for 12-factor apps * Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps
# Concepts # Concepts
@ -40,9 +40,9 @@ The best applications read like sentences when used, and as a result, users
intuitively know how to interact with them. intuitively know how to interact with them.
The pattern to follow is The pattern to follow is
`APPNAME VERB NOUN --ADJECTIVE.` `APPNAME VERB NOUN --ADJECTIVE`
or or
`APPNAME COMMAND ARG --FLAG` `APPNAME COMMAND ARG --FLAG`.
A few good real world examples may better illustrate this point. A few good real world examples may better illustrate this point.

63
active_help.go Normal file
View file

@ -0,0 +1,63 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra
import (
"fmt"
"os"
"strings"
)
const (
activeHelpMarker = "_activeHelp_ "
// The below values should not be changed: programs will be using them explicitly
// in their user documentation, and users will be using them explicitly.
activeHelpEnvVarSuffix = "_ACTIVE_HELP"
activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
activeHelpGlobalDisable = "0"
)
// 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.
// The array parameter should be the array that will contain the completions.
// 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 {
return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
}
// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
// case, with all - replaced by _.
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
// is set to "0".
func GetActiveHelpConfig(cmd *Command) string {
activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar)
if activeHelpCfg != activeHelpGlobalDisable {
activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))
}
return activeHelpCfg
}
// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
// variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
// root command in upper case, with all - replaced by _.
func activeHelpEnvVar(name string) string {
// This format should not be changed: users will be using it explicitly.
activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
return strings.ReplaceAll(activeHelpEnvVar, "-", "_")
}

157
active_help.md Normal file
View file

@ -0,0 +1,157 @@
# Active Help
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]
You must choose a name for the repo you are adding.
bash-5.1$ bin/helm package [tab]
Please specify the path to the chart to package
bash-5.1$ 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.
- 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).
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.
### Active Help for nouns
Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:
```go
cmd := &cobra.Command{
Use: "add [NAME] [URL]",
Short: "add a chart repository",
Args: require.ExactArgs(2),
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
if len(args) == 0 {
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
} else if len(args) == 1 {
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
} else {
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
}
return comps, cobra.ShellCompDirectiveNoFileComp
},
}
```
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]
You must choose a name for the repo you are adding
bash-5.1$ 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]
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) {
if len(args) != 2 {
return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
}
return compVersionFlag(args[1], toComplete)
})
```
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]
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]
2.0.1 2.0.2 2.0.3
```
## User control of Active Help
You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.
Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.
The way to configure Active Help is to use the program's Active Help environment
variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your
program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever
Active Help configuration values are supported by the program.
For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user
would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.
For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the
Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages
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) {
activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
var comps []string
if len(args) == 0 {
if activeHelpLevel != "off" {
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
}
} else if len(args) == 1 {
if activeHelpLevel != "off" {
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
}
} else {
if activeHelpLevel == "local" {
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
}
}
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.
When using the default `completion` command, Active Help is configurable in the same
fashion as described above using environment variables. You may wish to document this in more
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.
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
```
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
bitnami/haproxy
bitnami/harbor
_activeHelp_ WARNING: cannot re-use a name that is still in use
:0
Completion ended with directive: ShellCompDirectiveDefault
$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
bitnami/haproxy
bitnami/harbor
:0
Completion ended with directive: ShellCompDirectiveDefault
```

400
active_help_test.go Normal file
View file

@ -0,0 +1,400 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra
import (
"fmt"
"os"
"strings"
"testing"
)
const (
activeHelpMessage = "This is an activeHelp message"
activeHelpMessage2 = "This is the rest of the activeHelp message"
)
func TestActiveHelpAlone(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
activeHelpFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := AppendActiveHelp(nil, activeHelpMessage)
return comps, ShellCompDirectiveDefault
}
// Test that activeHelp can be added to a root command
rootCmd.ValidArgsFunction = activeHelpFunc
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
rootCmd.ValidArgsFunction = nil
// Test that activeHelp can be added to a child command
childCmd := &Command{
Use: "thechild",
Short: "The child command",
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
childCmd.ValidArgsFunction = activeHelpFunc
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected = strings.Join([]string{
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
func TestActiveHelpWithComps(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "thechild",
Short: "The child command",
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
// Test that activeHelp can be added following other completions
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := []string{"first", "second"}
comps = AppendActiveHelp(comps, activeHelpMessage)
return comps, ShellCompDirectiveDefault
}
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
"first",
"second",
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
// Test that activeHelp can be added preceding other completions
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
var comps []string
comps = AppendActiveHelp(comps, activeHelpMessage)
comps = append(comps, []string{"first", "second"}...)
return comps, ShellCompDirectiveDefault
}
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected = strings.Join([]string{
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
"first",
"second",
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
// Test that activeHelp can be added interleaved with other completions
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := []string{"first"}
comps = AppendActiveHelp(comps, activeHelpMessage)
comps = append(comps, "second")
return comps, ShellCompDirectiveDefault
}
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected = strings.Join([]string{
"first",
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
"second",
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
func TestMultiActiveHelp(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "thechild",
Short: "The child command",
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
// Test that multiple activeHelp message can be added
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := AppendActiveHelp(nil, activeHelpMessage)
comps = AppendActiveHelp(comps, activeHelpMessage2)
return comps, ShellCompDirectiveNoFileComp
}
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
// Test that multiple activeHelp messages can be used along with completions
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := []string{"first"}
comps = AppendActiveHelp(comps, activeHelpMessage)
comps = append(comps, "second")
comps = AppendActiveHelp(comps, activeHelpMessage2)
return comps, ShellCompDirectiveNoFileComp
}
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected = strings.Join([]string{
"first",
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
"second",
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
func TestActiveHelpForFlag(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
flagname := "flag"
rootCmd.Flags().String(flagname, "", "A flag")
// Test that multiple activeHelp message can be added
_ = rootCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := []string{"first"}
comps = AppendActiveHelp(comps, activeHelpMessage)
comps = append(comps, "second")
comps = AppendActiveHelp(comps, activeHelpMessage2)
return comps, ShellCompDirectiveNoFileComp
})
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--flag", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := strings.Join([]string{
"first",
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
"second",
fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}
func TestConfigActiveHelp(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "thechild",
Short: "The child command",
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
activeHelpCfg := "someconfig,anotherconfig"
// Set the variable that the user would be setting
os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
receivedActiveHelpCfg := GetActiveHelpConfig(cmd)
if receivedActiveHelpCfg != activeHelpCfg {
t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)
}
return nil, ShellCompDirectiveDefault
}
_, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// Test active help config for a flag
activeHelpCfg = "a config for a flag"
// Set the variable that the completions scripts will be setting
os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)
flagname := "flag"
childCmd.Flags().String(flagname, "", "A flag")
// Test that multiple activeHelp message can be added
_ = childCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
receivedActiveHelpCfg := GetActiveHelpConfig(cmd)
if receivedActiveHelpCfg != activeHelpCfg {
t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)
}
return nil, ShellCompDirectiveDefault
})
_, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "--flag", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestDisableActiveHelp(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "thechild",
Short: "The child command",
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
// Test the disabling of activeHelp using the specific program
// environment variable that the completions scripts will be setting.
// Make sure the disabling value is "0" by hard-coding it in the tests;
// this is for backwards-compatibility as programs will be using this value.
os.Setenv(activeHelpEnvVar(rootCmd.Name()), "0")
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
comps := []string{"first"}
comps = AppendActiveHelp(comps, activeHelpMessage)
return comps, ShellCompDirectiveDefault
}
output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
os.Unsetenv(activeHelpEnvVar(rootCmd.Name()))
// Make sure there is no ActiveHelp in the output
expected := strings.Join([]string{
"first",
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
// Now test the global disabling of ActiveHelp
os.Setenv(activeHelpGlobalEnvVar, "0")
// Set the specific variable, to make sure it is ignored when the global env
// var is set properly
os.Setenv(activeHelpEnvVar(rootCmd.Name()), "1")
output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// Make sure there is no ActiveHelp in the output
expected = strings.Join([]string{
"first",
":0",
"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
// Make sure that if the global env variable is set to anything else than
// the disable value it is ignored
os.Setenv(activeHelpGlobalEnvVar, "on")
// Set the specific variable, to make sure it is used (while ignoring the global env var)
activeHelpCfg := "1"
os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)
childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
receivedActiveHelpCfg := GetActiveHelpConfig(cmd)
if receivedActiveHelpCfg != activeHelpCfg {
t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)
}
return nil, ShellCompDirectiveDefault
}
_, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}

38
args.go
View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -32,7 +46,8 @@ func NoArgs(cmd *Command, args []string) error {
return nil return nil
} }
// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. // OnlyValidArgs returns an error if there are any positional args that are not in
// the `ValidArgs` field of `Command`
func OnlyValidArgs(cmd *Command, args []string) error { func OnlyValidArgs(cmd *Command, args []string) error {
if len(cmd.ValidArgs) > 0 { if len(cmd.ValidArgs) > 0 {
// Remove any description that may be included in ValidArgs. // Remove any description that may be included in ValidArgs.
@ -41,7 +56,6 @@ func OnlyValidArgs(cmd *Command, args []string) error {
for _, v := range cmd.ValidArgs { for _, v := range cmd.ValidArgs {
validArgs = append(validArgs, strings.Split(v, "\t")[0]) validArgs = append(validArgs, strings.Split(v, "\t")[0])
} }
for _, v := range args { for _, v := range args {
if !stringInSlice(v, validArgs) { if !stringInSlice(v, validArgs) {
return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
@ -86,18 +100,6 @@ func ExactArgs(n int) PositionalArgs {
} }
} }
// ExactValidArgs returns an error if
// there are not exactly N positional args OR
// there are any positional args that are not in the `ValidArgs` field of `Command`
func ExactValidArgs(n int) PositionalArgs {
return func(cmd *Command, args []string) error {
if err := ExactArgs(n)(cmd, args); err != nil {
return err
}
return OnlyValidArgs(cmd, args)
}
}
// RangeArgs returns an error if the number of args is not within the expected range. // RangeArgs returns an error if the number of args is not within the expected range.
func RangeArgs(min int, max int) PositionalArgs { func RangeArgs(min int, max int) PositionalArgs {
return func(cmd *Command, args []string) error { return func(cmd *Command, args []string) error {
@ -119,3 +121,11 @@ func MatchAll(pargs ...PositionalArgs) PositionalArgs {
return nil return nil
} }
} }
// ExactValidArgs returns an error if there are not exactly N positional args OR
// there are any positional args that are not in the `ValidArgs` field of `Command`
//
// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead
func ExactValidArgs(n int) PositionalArgs {
return MatchAll(ExactArgs(n), OnlyValidArgs)
}

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -27,7 +41,7 @@ func expectSuccess(output string, err error, t *testing.T) {
} }
} }
func validWithInvalidArgs(err error, t *testing.T) { func validOnlyWithInvalidArgs(err error, t *testing.T) {
if err == nil { if err == nil {
t.Fatal("Expected an error") t.Fatal("Expected an error")
} }
@ -38,12 +52,12 @@ func validWithInvalidArgs(err error, t *testing.T) {
} }
} }
func noArgsWithArgs(err error, t *testing.T) { func noArgsWithArgs(err error, t *testing.T, arg string) {
if err == nil { if err == nil {
t.Fatal("Expected an error") t.Fatal("Expected an error")
} }
got := err.Error() got := err.Error()
expected := `unknown command "illegal" for "c"` expected := `unknown command "` + arg + `" for "c"`
if got != expected { if got != expected {
t.Errorf("Expected: %q, got: %q", expected, got) t.Errorf("Expected: %q, got: %q", expected, got)
} }
@ -93,102 +107,280 @@ func rangeArgsWithInvalidCount(err error, t *testing.T) {
} }
} }
// NoArgs
func TestNoArgs(t *testing.T) { func TestNoArgs(t *testing.T) {
c := getCommand(NoArgs, false) c := getCommand(NoArgs, false)
output, err := executeCommand(c) output, err := executeCommand(c)
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestNoArgsWithArgs(t *testing.T) { func TestNoArgs_WithArgs(t *testing.T) {
c := getCommand(NoArgs, false) c := getCommand(NoArgs, false)
_, err := executeCommand(c, "illegal") _, err := executeCommand(c, "one")
noArgsWithArgs(err, t) noArgsWithArgs(err, t, "one")
} }
func TestNoArgs_WithValid_WithArgs(t *testing.T) {
c := getCommand(NoArgs, true)
_, err := executeCommand(c, "one")
noArgsWithArgs(err, t, "one")
}
func TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(NoArgs, true)
_, err := executeCommand(c, "a")
noArgsWithArgs(err, t, "a")
}
func TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, NoArgs), true)
_, err := executeCommand(c, "a")
validOnlyWithInvalidArgs(err, t)
}
// OnlyValidArgs
func TestOnlyValidArgs(t *testing.T) { func TestOnlyValidArgs(t *testing.T) {
c := getCommand(OnlyValidArgs, true) c := getCommand(OnlyValidArgs, true)
output, err := executeCommand(c, "one", "two") output, err := executeCommand(c, "one", "two")
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestOnlyValidArgsWithInvalidArgs(t *testing.T) { func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {
c := getCommand(OnlyValidArgs, true) c := getCommand(OnlyValidArgs, true)
_, err := executeCommand(c, "a") _, err := executeCommand(c, "a")
validWithInvalidArgs(err, t) validOnlyWithInvalidArgs(err, t)
} }
// ArbitraryArgs
func TestArbitraryArgs(t *testing.T) { func TestArbitraryArgs(t *testing.T) {
c := getCommand(ArbitraryArgs, false) c := getCommand(ArbitraryArgs, false)
output, err := executeCommand(c, "a", "b") output, err := executeCommand(c, "a", "b")
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestArbitraryArgs_WithValid(t *testing.T) {
c := getCommand(ArbitraryArgs, true)
output, err := executeCommand(c, "one", "two")
expectSuccess(output, err, t)
}
func TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(ArbitraryArgs, true)
output, err := executeCommand(c, "a")
expectSuccess(output, err, t)
}
func TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, ArbitraryArgs), true)
_, err := executeCommand(c, "a")
validOnlyWithInvalidArgs(err, t)
}
// MinimumNArgs
func TestMinimumNArgs(t *testing.T) { func TestMinimumNArgs(t *testing.T) {
c := getCommand(MinimumNArgs(2), false) c := getCommand(MinimumNArgs(2), false)
output, err := executeCommand(c, "a", "b", "c") output, err := executeCommand(c, "a", "b", "c")
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestMinimumNArgsWithLessArgs(t *testing.T) { func TestMinimumNArgs_WithValid(t *testing.T) {
c := getCommand(MinimumNArgs(2), true)
output, err := executeCommand(c, "one", "three")
expectSuccess(output, err, t)
}
func TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) {
c := getCommand(MinimumNArgs(2), true)
output, err := executeCommand(c, "a", "b")
expectSuccess(output, err, t)
}
func TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)
_, err := executeCommand(c, "a", "b")
validOnlyWithInvalidArgs(err, t)
}
func TestMinimumNArgs_WithLessArgs(t *testing.T) {
c := getCommand(MinimumNArgs(2), false) c := getCommand(MinimumNArgs(2), false)
_, err := executeCommand(c, "a") _, err := executeCommand(c, "a")
minimumNArgsWithLessArgs(err, t) minimumNArgsWithLessArgs(err, t)
} }
func TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) {
c := getCommand(MinimumNArgs(2), true)
_, err := executeCommand(c, "one")
minimumNArgsWithLessArgs(err, t)
}
func TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(MinimumNArgs(2), true)
_, err := executeCommand(c, "a")
minimumNArgsWithLessArgs(err, t)
}
func TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)
_, err := executeCommand(c, "a")
validOnlyWithInvalidArgs(err, t)
}
// MaximumNArgs
func TestMaximumNArgs(t *testing.T) { func TestMaximumNArgs(t *testing.T) {
c := getCommand(MaximumNArgs(3), false) c := getCommand(MaximumNArgs(3), false)
output, err := executeCommand(c, "a", "b") output, err := executeCommand(c, "a", "b")
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestMaximumNArgsWithMoreArgs(t *testing.T) { func TestMaximumNArgs_WithValid(t *testing.T) {
c := getCommand(MaximumNArgs(2), true)
output, err := executeCommand(c, "one", "three")
expectSuccess(output, err, t)
}
func TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(MaximumNArgs(2), true)
output, err := executeCommand(c, "a", "b")
expectSuccess(output, err, t)
}
func TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)
_, err := executeCommand(c, "a", "b")
validOnlyWithInvalidArgs(err, t)
}
func TestMaximumNArgs_WithMoreArgs(t *testing.T) {
c := getCommand(MaximumNArgs(2), false) c := getCommand(MaximumNArgs(2), false)
_, err := executeCommand(c, "a", "b", "c") _, err := executeCommand(c, "a", "b", "c")
maximumNArgsWithMoreArgs(err, t) maximumNArgsWithMoreArgs(err, t)
} }
func TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) {
c := getCommand(MaximumNArgs(2), true)
_, err := executeCommand(c, "one", "three", "two")
maximumNArgsWithMoreArgs(err, t)
}
func TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(MaximumNArgs(2), true)
_, err := executeCommand(c, "a", "b", "c")
maximumNArgsWithMoreArgs(err, t)
}
func TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)
_, err := executeCommand(c, "a", "b", "c")
validOnlyWithInvalidArgs(err, t)
}
// ExactArgs
func TestExactArgs(t *testing.T) { func TestExactArgs(t *testing.T) {
c := getCommand(ExactArgs(3), false) c := getCommand(ExactArgs(3), false)
output, err := executeCommand(c, "a", "b", "c") output, err := executeCommand(c, "a", "b", "c")
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestExactArgsWithInvalidCount(t *testing.T) { func TestExactArgs_WithValid(t *testing.T) {
c := getCommand(ExactArgs(3), true)
output, err := executeCommand(c, "three", "one", "two")
expectSuccess(output, err, t)
}
func TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(ExactArgs(3), true)
output, err := executeCommand(c, "three", "a", "two")
expectSuccess(output, err, t)
}
func TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(3)), true)
_, err := executeCommand(c, "three", "a", "two")
validOnlyWithInvalidArgs(err, t)
}
func TestExactArgs_WithInvalidCount(t *testing.T) {
c := getCommand(ExactArgs(2), false) c := getCommand(ExactArgs(2), false)
_, err := executeCommand(c, "a", "b", "c") _, err := executeCommand(c, "a", "b", "c")
exactArgsWithInvalidCount(err, t) exactArgsWithInvalidCount(err, t)
} }
func TestExactValidArgs(t *testing.T) { func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {
c := getCommand(ExactValidArgs(3), true) c := getCommand(ExactArgs(2), true)
output, err := executeCommand(c, "three", "one", "two")
expectSuccess(output, err, t)
}
func TestExactValidArgsWithInvalidCount(t *testing.T) {
c := getCommand(ExactValidArgs(2), false)
_, err := executeCommand(c, "three", "one", "two") _, err := executeCommand(c, "three", "one", "two")
exactArgsWithInvalidCount(err, t) exactArgsWithInvalidCount(err, t)
} }
func TestExactValidArgsWithInvalidArgs(t *testing.T) { func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(ExactValidArgs(3), true) c := getCommand(ExactArgs(2), true)
_, err := executeCommand(c, "three", "a", "two") _, err := executeCommand(c, "three", "a", "two")
validWithInvalidArgs(err, t) exactArgsWithInvalidCount(err, t)
} }
func TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(2)), true)
_, err := executeCommand(c, "three", "a", "two")
validOnlyWithInvalidArgs(err, t)
}
// RangeArgs
func TestRangeArgs(t *testing.T) { func TestRangeArgs(t *testing.T) {
c := getCommand(RangeArgs(2, 4), false) c := getCommand(RangeArgs(2, 4), false)
output, err := executeCommand(c, "a", "b", "c") output, err := executeCommand(c, "a", "b", "c")
expectSuccess(output, err, t) expectSuccess(output, err, t)
} }
func TestRangeArgsWithInvalidCount(t *testing.T) { func TestRangeArgs_WithValid(t *testing.T) {
c := getCommand(RangeArgs(2, 4), true)
output, err := executeCommand(c, "three", "one", "two")
expectSuccess(output, err, t)
}
func TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(RangeArgs(2, 4), true)
output, err := executeCommand(c, "three", "a", "two")
expectSuccess(output, err, t)
}
func TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)
_, err := executeCommand(c, "three", "a", "two")
validOnlyWithInvalidArgs(err, t)
}
func TestRangeArgs_WithInvalidCount(t *testing.T) {
c := getCommand(RangeArgs(2, 4), false) c := getCommand(RangeArgs(2, 4), false)
_, err := executeCommand(c, "a") _, err := executeCommand(c, "a")
rangeArgsWithInvalidCount(err, t) rangeArgsWithInvalidCount(err, t)
} }
func TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) {
c := getCommand(RangeArgs(2, 4), true)
_, err := executeCommand(c, "two")
rangeArgsWithInvalidCount(err, t)
}
func TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {
c := getCommand(RangeArgs(2, 4), true)
_, err := executeCommand(c, "a")
rangeArgsWithInvalidCount(err, t)
}
func TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {
c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)
_, err := executeCommand(c, "a")
validOnlyWithInvalidArgs(err, t)
}
// Takes(No)Args
func TestRootTakesNoArgs(t *testing.T) { func TestRootTakesNoArgs(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun} rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun} childCmd := &Command{Use: "child", Run: emptyRun}
@ -293,6 +485,32 @@ func TestMatchAll(t *testing.T) {
} }
} }
// DEPRECATED
func TestExactValidArgs(t *testing.T) {
c := getCommand(ExactValidArgs(3), true)
output, err := executeCommand(c, "three", "one", "two")
expectSuccess(output, err, t)
}
func TestExactValidArgs_WithInvalidCount(t *testing.T) {
c := getCommand(ExactValidArgs(2), false)
_, err := executeCommand(c, "three", "one", "two")
exactArgsWithInvalidCount(err, t)
}
func TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) {
c := getCommand(ExactValidArgs(2), true)
_, err := executeCommand(c, "three", "a", "two")
exactArgsWithInvalidCount(err, t)
}
func TestExactValidArgs_WithInvalidArgs(t *testing.T) {
c := getCommand(ExactValidArgs(2), true)
_, err := executeCommand(c, "three", "a")
validOnlyWithInvalidArgs(err, t)
}
// This test make sure we keep backwards-compatibility with respect // This test make sure we keep backwards-compatibility with respect
// to the legacyArgs() function. // to the legacyArgs() function.
// It makes sure the root command accepts arguments if it does not have // It makes sure the root command accepts arguments if it does not have

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -73,7 +87,8 @@ __%[1]s_handle_go_custom_completion()
# Prepare the command to request completions for the program. # Prepare the command to request completions for the program.
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases # Calling ${words[0]} instead of directly %[1]s allows to handle aliases
args=("${words[@]:1}") args=("${words[@]:1}")
requestComp="${words[0]} %[2]s ${args[*]}" # Disable ActiveHelp which is not supported for bash completion v1
requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"
lastParam=${words[$((${#words[@]}-1))]} lastParam=${words[$((${#words[@]}-1))]}
lastChar=${lastParam:$((${#lastParam}-1)):1} lastChar=${lastParam:$((${#lastParam}-1)):1}
@ -383,7 +398,7 @@ __%[1]s_handle_word()
`, name, ShellCompNoDescRequestCmd, `, name, ShellCompNoDescRequestCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
} }
func writePostscript(buf io.StringWriter, name string) { func writePostscript(buf io.StringWriter, name string) {

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -111,13 +125,18 @@ __%[1]s_process_completion_results() {
fi fi
fi fi
# Separate activeHelp from normal completions
local completions=()
local activeHelp=()
__%[1]s_extract_activeHelp
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
# File extension filtering # File extension filtering
local fullFilter filter filteringCmd local fullFilter filter filteringCmd
# Do not use quotes around the $out variable or else newline # Do not use quotes around the $completions variable or else newline
# characters will be kept. # characters will be kept.
for filter in ${out}; do for filter in ${completions[*]}; do
fullFilter+="$filter|" fullFilter+="$filter|"
done done
@ -129,7 +148,7 @@ __%[1]s_process_completion_results() {
# Use printf to strip any trailing newline # Use printf to strip any trailing newline
local subdir local subdir
subdir=$(printf "%%s" "${out}") subdir=$(printf "%%s" "${completions[0]}")
if [ -n "$subdir" ]; then if [ -n "$subdir" ]; then
__%[1]s_debug "Listing directories in $subdir" __%[1]s_debug "Listing directories in $subdir"
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
@ -143,6 +162,43 @@ __%[1]s_process_completion_results() {
__%[1]s_handle_special_char "$cur" : __%[1]s_handle_special_char "$cur" :
__%[1]s_handle_special_char "$cur" = __%[1]s_handle_special_char "$cur" =
# Print the activeHelp statements before we finish
if [ ${#activeHelp[*]} -ne 0 ]; then
printf "\n";
printf "%%s\n" "${activeHelp[@]}"
printf "\n"
# The prompt format is only available from bash 4.4.
# We test if it is available before using it.
if (x=${PS1@P}) 2> /dev/null; then
printf "%%s" "${PS1@P}${COMP_LINE[@]}"
else
# Can't print the prompt. Just print the
# text the user had typed, it is workable enough.
printf "%%s" "${COMP_LINE[@]}"
fi
fi
}
# Separate activeHelp lines from real completions.
# Fills the $activeHelp and $completions arrays.
__%[1]s_extract_activeHelp() {
local activeHelpMarker="%[8]s"
local endIndex=${#activeHelpMarker}
while IFS='' read -r comp; do
if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then
comp=${comp:endIndex}
__%[1]s_debug "ActiveHelp found: $comp"
if [ -n "$comp" ]; then
activeHelp+=("$comp")
fi
else
# Not an activeHelp line but a normal completion
completions+=("$comp")
fi
done < <(printf "%%s\n" "${out}")
} }
__%[1]s_handle_completion_types() { __%[1]s_handle_completion_types() {
@ -163,7 +219,7 @@ __%[1]s_handle_completion_types() {
if [[ $comp == "$cur"* ]]; then if [[ $comp == "$cur"* ]]; then
COMPREPLY+=("$comp") COMPREPLY+=("$comp")
fi fi
done < <(printf "%%s\n" "${out}") done < <(printf "%%s\n" "${completions[@]}")
;; ;;
*) *)
@ -177,10 +233,8 @@ __%[1]s_handle_standard_completion_case() {
local tab=$'\t' comp local tab=$'\t' comp
# Short circuit to optimize if we don't have descriptions # Short circuit to optimize if we don't have descriptions
if [[ $out != *$tab* ]]; then if [[ "${completions[*]}" != *$tab* ]]; then
while IFS='' read -r comp; do IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
COMPREPLY+=("$comp")
done < <(IFS=$'\n' compgen -W "$out" -- "$cur")
return 0 return 0
fi fi
@ -188,6 +242,7 @@ __%[1]s_handle_standard_completion_case() {
local compline local compline
# Look for the longest completion so that we can format things nicely # Look for the longest completion so that we can format things nicely
while IFS='' read -r compline; do while IFS='' read -r compline; do
[[ -z $compline ]] && continue
# Strip any description before checking the length # Strip any description before checking the length
comp=${compline%%%%$tab*} comp=${compline%%%%$tab*}
# Only consider the completions that match # Only consider the completions that match
@ -196,7 +251,7 @@ __%[1]s_handle_standard_completion_case() {
if ((${#comp}>longest)); then if ((${#comp}>longest)); then
longest=${#comp} longest=${#comp}
fi fi
done < <(printf "%%s\n" "${out}") 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
if [ ${#COMPREPLY[*]} -eq 1 ]; then if [ ${#COMPREPLY[*]} -eq 1 ]; then
@ -306,7 +361,8 @@ fi
# ex: ts=4 sw=4 et filetype=sh # ex: ts=4 sw=4 et filetype=sh
`, name, compCmd, `, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
activeHelpMarker))
} }
// GenBashCompletionFileV2 generates Bash completion version 2. // GenBashCompletionFileV2 generates Bash completion version 2.

View file

@ -0,0 +1,33 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra
import (
"bytes"
"fmt"
"testing"
)
func TestBashCompletionV2WithActiveHelp(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
buf := new(bytes.Buffer)
assertNoErr(t, c.GenBashCompletionV2(buf, true))
output := buf.String()
// check that active help is not being disabled
activeHelpVar := activeHelpEnvVar(c.Name())
checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -261,3 +275,15 @@ func TestBashCompletionTraverseChildren(t *testing.T) {
checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`) checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`)
checkOmit(t, output, `local_nonpersistent_flags+=("-b")`) checkOmit(t, output, `local_nonpersistent_flags+=("-b")`)
} }
func TestBashCompletionNoActiveHelp(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
buf := new(bytes.Buffer)
assertNoErr(t, c.GenBashCompletion(buf))
output := buf.String()
// check that active help is being disabled
activeHelpVar := activeHelpEnvVar(c.Name())
check(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}

View file

@ -1,9 +1,10 @@
// Copyright © 2013 Steve Francia <spf@spf13.com>. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
@ -40,14 +41,23 @@ var templateFuncs = template.FuncMap{
var initializers []func() var initializers []func()
const (
defaultPrefixMatching = false
defaultCommandSorting = true
defaultCaseInsensitive = false
)
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing // EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
// to automatically enable in CLI tools. // to automatically enable in CLI tools.
// Set this to true to enable it. // Set this to true to enable it.
var EnablePrefixMatching = false var EnablePrefixMatching = defaultPrefixMatching
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. // EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
// To disable sorting, set it to false. // To disable sorting, set it to false.
var EnableCommandSorting = true var EnableCommandSorting = defaultCommandSorting
// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
var EnableCaseInsensitive = defaultCaseInsensitive
// MousetrapHelpText enables an information splash screen on Windows // MousetrapHelpText enables an information splash screen on Windows
// if the CLI is started from explorer.exe. // if the CLI is started from explorer.exe.

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (

View file

@ -1,9 +1,10 @@
// Copyright © 2013 Steve Francia <spf@spf13.com>. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
@ -18,6 +19,7 @@ package cobra
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -235,8 +237,8 @@ func (c *Command) Context() context.Context {
return c.ctx return c.ctx
} }
// SetContext sets context for the command. It is set to context.Background by default and will be overwritten by // SetContext sets context for the command. This context will be overwritten by
// Command.ExecuteContext or Command.ExecuteContextC // Command.ExecuteContext or Command.ExecuteContextC.
func (c *Command) SetContext(ctx context.Context) { func (c *Command) SetContext(ctx context.Context) {
c.ctx = ctx c.ctx = ctx
} }
@ -675,7 +677,7 @@ func (c *Command) findSuggestions(arg string) string {
func (c *Command) findNext(next string) *Command { func (c *Command) findNext(next string) *Command {
matches := make([]*Command, 0) matches := make([]*Command, 0)
for _, cmd := range c.commands { for _, cmd := range c.commands {
if cmd.Name() == next || cmd.HasAlias(next) { if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {
cmd.commandCalledAs.name = next cmd.commandCalledAs.name = next
return cmd return cmd
} }
@ -860,10 +862,10 @@ func (c *Command) execute(a []string) (err error) {
c.PreRun(c, argWoFlags) c.PreRun(c, argWoFlags)
} }
if err := c.validateRequiredFlags(); err != nil { if err := c.ValidateRequiredFlags(); err != nil {
return err return err
} }
if err := c.validateFlagGroups(); err != nil { if err := c.ValidateFlagGroups(); err != nil {
return err return err
} }
@ -990,7 +992,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
if err != nil { if err != nil {
// Always show help if requested, even if SilenceErrors is in // Always show help if requested, even if SilenceErrors is in
// effect // effect
if err == flag.ErrHelp { if errors.Is(err, flag.ErrHelp) {
cmd.HelpFunc()(cmd, args) cmd.HelpFunc()(cmd, args)
return cmd, nil return cmd, nil
} }
@ -1012,12 +1014,13 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
func (c *Command) ValidateArgs(args []string) error { func (c *Command) ValidateArgs(args []string) error {
if c.Args == nil { if c.Args == nil {
return nil return ArbitraryArgs(c, args)
} }
return c.Args(c, args) return c.Args(c, args)
} }
func (c *Command) validateRequiredFlags() error { // ValidateRequiredFlags validates all required flags are present and returns an error otherwise
func (c *Command) ValidateRequiredFlags() error {
if c.DisableFlagParsing { if c.DisableFlagParsing {
return nil return nil
} }
@ -1120,7 +1123,8 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
c.Printf("Unknown help topic %#q\n", args) c.Printf("Unknown help topic %#q\n", args)
CheckErr(c.Root().Usage()) CheckErr(c.Root().Usage())
} else { } else {
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
CheckErr(cmd.Help()) CheckErr(cmd.Help())
} }
}, },
@ -1327,7 +1331,7 @@ func (c *Command) Name() string {
// HasAlias determines if a given string is an alias of the command. // HasAlias determines if a given string is an alias of the command.
func (c *Command) HasAlias(s string) bool { func (c *Command) HasAlias(s string) bool {
for _, a := range c.Aliases { for _, a := range c.Aliases {
if a == s { if commandNameMatches(a, s) {
return true return true
} }
} }
@ -1504,7 +1508,8 @@ func (c *Command) LocalFlags() *flag.FlagSet {
} }
addToLocal := func(f *flag.Flag) { addToLocal := func(f *flag.Flag) {
if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
c.lflags.AddFlag(f) c.lflags.AddFlag(f)
} }
} }
@ -1693,3 +1698,14 @@ func (c *Command) updateParentsPflags() {
c.parentsPflags.AddFlagSet(parent.PersistentFlags()) c.parentsPflags.AddFlagSet(parent.PersistentFlags())
}) })
} }
// commandNameMatches checks if two command names are equal
// taking into account case sensitivity according to
// EnableCaseInsensitive global configuration.
func commandNameMatches(s string, t string) bool {
if EnableCaseInsensitive {
return strings.EqualFold(s, t)
}
return s == t
}

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !windows //go:build !windows
// +build !windows // +build !windows

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -314,7 +328,7 @@ func TestEnablePrefixMatching(t *testing.T) {
t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got) t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got)
} }
EnablePrefixMatching = false EnablePrefixMatching = defaultPrefixMatching
} }
func TestAliasPrefixMatching(t *testing.T) { func TestAliasPrefixMatching(t *testing.T) {
@ -349,7 +363,7 @@ func TestAliasPrefixMatching(t *testing.T) {
t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got) t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)
} }
EnablePrefixMatching = false EnablePrefixMatching = defaultPrefixMatching
} }
// TestChildSameName checks the correct behaviour of cobra in cases, // TestChildSameName checks the correct behaviour of cobra in cases,
@ -707,10 +721,7 @@ func TestEmptyInputs(t *testing.T) {
} }
} }
func TestOverwrittenFlag(t *testing.T) { func TestChildFlagShadowsParentPersistentFlag(t *testing.T) {
// TODO: This test fails, but should work.
t.Skip()
parent := &Command{Use: "parent", Run: emptyRun} parent := &Command{Use: "parent", Run: emptyRun}
child := &Command{Use: "child", Run: emptyRun} child := &Command{Use: "child", Run: emptyRun}
@ -732,7 +743,7 @@ func TestOverwrittenFlag(t *testing.T) {
} }
if childInherited.Lookup("intf") != nil { if childInherited.Lookup("intf") != nil {
t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`) t.Errorf(`InheritedFlags should not contain shadowed flag "intf"`)
} }
if childLocal.Lookup("intf") == nil { if childLocal.Lookup("intf") == nil {
t.Error(`LocalFlags expected to contain "intf", got "nil"`) t.Error(`LocalFlags expected to contain "intf", got "nil"`)
@ -887,6 +898,38 @@ func TestHelpCommandExecutedOnChild(t *testing.T) {
checkStringContains(t, output, childCmd.Long) checkStringContains(t, output, childCmd.Long)
} }
func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) {
parent := &Command{Use: "parent", Run: emptyRun}
child := &Command{Use: "child", Run: emptyRun}
parent.AddCommand(child)
parent.PersistentFlags().Bool("foo", false, "parent foo usage")
parent.PersistentFlags().Bool("bar", false, "parent bar usage")
child.Flags().Bool("foo", false, "child foo usage") // This shadows parent's foo flag
child.Flags().Bool("baz", false, "child baz usage")
got, err := executeCommand(parent, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := `Usage:
parent child [flags]
Flags:
--baz child baz usage
--foo child foo usage
-h, --help help for child
Global Flags:
--bar parent bar usage
`
if got != expected {
t.Errorf("Help text mismatch.\nExpected:\n%s\n\nGot:\n%s\n", expected, got)
}
}
func TestSetHelpCommand(t *testing.T) { func TestSetHelpCommand(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun} c := &Command{Use: "c", Run: emptyRun}
c.AddCommand(&Command{Use: "empty", Run: emptyRun}) c.AddCommand(&Command{Use: "empty", Run: emptyRun})
@ -1234,6 +1277,113 @@ func TestSuggestions(t *testing.T) {
} }
} }
func TestCaseInsensitive(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun, Aliases: []string{"alternative"}}
granchildCmd := &Command{Use: "GRANDCHILD", Run: emptyRun, Aliases: []string{"ALIAS"}}
childCmd.AddCommand(granchildCmd)
rootCmd.AddCommand(childCmd)
tests := []struct {
args []string
failWithoutEnabling bool
}{
{
args: []string{"child"},
failWithoutEnabling: false,
},
{
args: []string{"CHILD"},
failWithoutEnabling: true,
},
{
args: []string{"chILD"},
failWithoutEnabling: true,
},
{
args: []string{"CHIld"},
failWithoutEnabling: true,
},
{
args: []string{"alternative"},
failWithoutEnabling: false,
},
{
args: []string{"ALTERNATIVE"},
failWithoutEnabling: true,
},
{
args: []string{"ALTernatIVE"},
failWithoutEnabling: true,
},
{
args: []string{"alternatiVE"},
failWithoutEnabling: true,
},
{
args: []string{"child", "GRANDCHILD"},
failWithoutEnabling: false,
},
{
args: []string{"child", "grandchild"},
failWithoutEnabling: true,
},
{
args: []string{"CHIld", "GRANdchild"},
failWithoutEnabling: true,
},
{
args: []string{"alternative", "ALIAS"},
failWithoutEnabling: false,
},
{
args: []string{"alternative", "alias"},
failWithoutEnabling: true,
},
{
args: []string{"CHILD", "alias"},
failWithoutEnabling: true,
},
{
args: []string{"CHIld", "aliAS"},
failWithoutEnabling: true,
},
}
for _, test := range tests {
for _, enableCaseInsensitivity := range []bool{true, false} {
EnableCaseInsensitive = enableCaseInsensitivity
output, err := executeCommand(rootCmd, test.args...)
expectedFailure := test.failWithoutEnabling && !enableCaseInsensitivity
if !expectedFailure && output != "" {
t.Errorf("Unexpected output: %v", output)
}
if !expectedFailure && err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
}
EnableCaseInsensitive = defaultCaseInsensitive
}
// This test make sure we keep backwards-compatibility with respect
// to command names case sensitivity behavior.
func TestCaseSensitivityBackwardCompatibility(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
_, err := executeCommand(rootCmd, strings.ToUpper(childCmd.Use))
if err == nil {
t.Error("Expected error on calling a command in upper case while command names are case sensitive. Got nil.")
}
}
func TestRemoveCommand(t *testing.T) { func TestRemoveCommand(t *testing.T) {
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun} childCmd := &Command{Use: "child", Run: emptyRun}
@ -1593,7 +1743,7 @@ func TestCommandsAreSorted(t *testing.T) {
} }
} }
EnableCommandSorting = true EnableCommandSorting = defaultCommandSorting
} }
func TestEnableCommandSortingIsDisabled(t *testing.T) { func TestEnableCommandSortingIsDisabled(t *testing.T) {
@ -1614,7 +1764,7 @@ func TestEnableCommandSortingIsDisabled(t *testing.T) {
} }
} }
EnableCommandSorting = true EnableCommandSorting = defaultCommandSorting
} }
func TestSetOutput(t *testing.T) { func TestSetOutput(t *testing.T) {
@ -1723,6 +1873,38 @@ func TestFlagErrorFunc(t *testing.T) {
} }
} }
func TestFlagErrorFuncHelp(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
c.PersistentFlags().Bool("help", false, "help for c")
c.SetFlagErrorFunc(func(_ *Command, err error) error {
return fmt.Errorf("wrap error: %w", err)
})
out, err := executeCommand(c, "--help")
if err != nil {
t.Errorf("--help should not fail: %v", err)
}
expected := `Usage:
c [flags]
Flags:
--help help for c
`
if out != expected {
t.Errorf("Expected: %v, got: %v", expected, out)
}
out, err = executeCommand(c, "-h")
if err != nil {
t.Errorf("-h should not fail: %v", err)
}
if out != expected {
t.Errorf("Expected: %v, got: %v", expected, out)
}
}
// TestSortedFlags checks, // TestSortedFlags checks,
// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false. // if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
// Related to https://github.com/spf13/cobra/issues/404. // Related to https://github.com/spf13/cobra/issues/404.
@ -2161,3 +2343,90 @@ func TestSetContextPersistentPreRun(t *testing.T) {
t.Error(err) t.Error(err)
} }
} }
const VersionFlag = "--version"
const HelpFlag = "--help"
func TestNoRootRunCommandExecutedWithVersionSet(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0", Long: "Long description"}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
checkStringContains(t, output, HelpFlag)
checkStringContains(t, output, VersionFlag)
}
func TestNoRootRunCommandExecutedWithoutVersionSet(t *testing.T) {
rootCmd := &Command{Use: "root", Long: "Long description"}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
checkStringContains(t, output, HelpFlag)
checkStringOmits(t, output, VersionFlag)
}
func TestHelpCommandExecutedWithVersionSet(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd, "help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
checkStringContains(t, output, HelpFlag)
checkStringContains(t, output, VersionFlag)
}
func TestHelpCommandExecutedWithoutVersionSet(t *testing.T) {
rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd, "help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
checkStringContains(t, output, HelpFlag)
checkStringOmits(t, output, VersionFlag)
}
func TestHelpflagCommandExecutedWithVersionSet(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd, HelpFlag)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
checkStringContains(t, output, HelpFlag)
checkStringContains(t, output, VersionFlag)
}
func TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) {
rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd, HelpFlag)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
checkStringContains(t, output, HelpFlag)
checkStringOmits(t, output, VersionFlag)
}

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows //go:build windows
// +build windows // +build windows

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -178,6 +192,12 @@ func (c *Command) initCompleteCmd(args []string) {
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
for _, comp := range completions { for _, comp := range completions {
if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
// Remove all activeHelp entries in this case
if strings.HasPrefix(comp, activeHelpMarker) {
continue
}
}
if noDescriptions { if noDescriptions {
// Remove any description that may be included following a tab character. // Remove any description that may be included following a tab character.
comp = strings.Split(comp, "\t")[0] comp = strings.Split(comp, "\t")[0]
@ -319,6 +339,9 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
var completions []string var completions []string
var directive ShellCompDirective var directive ShellCompDirective
// Enforce flag groups before doing flag completions
finalCmd.enforceFlagGroupsForCompletion()
// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true; // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;
// doing this allows for completion of persistent flag names even for commands that disable flag parsing. // doing this allows for completion of persistent flag names even for commands that disable flag parsing.
// //
@ -652,7 +675,7 @@ To load completions for every new session, execute once:
#### macOS: #### macOS:
%[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
You will need to start a new shell for this setup to take effect. You will need to start a new shell for this setup to take effect.
`, c.Root().Name()), `, c.Root().Name()),
@ -689,7 +712,7 @@ To load completions for every new session, execute once:
#### macOS: #### macOS:
%[1]s completion zsh > /usr/local/share/zsh/site-functions/_%[1]s %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s
You will need to start a new shell for this setup to take effect. You will need to start a new shell for this setup to take effect.
`, c.Root().Name()), `, c.Root().Name()),

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -2691,3 +2705,189 @@ func TestFixedCompletions(t *testing.T) {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
} }
func TestCompletionForGroupedFlags(t *testing.T) {
getCmd := func() *Command {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "child",
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"subArg"}, ShellCompDirectiveNoFileComp
},
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
rootCmd.PersistentFlags().Int("ingroup1", -1, "ingroup1")
rootCmd.PersistentFlags().String("ingroup2", "", "ingroup2")
childCmd.Flags().Bool("ingroup3", false, "ingroup3")
childCmd.Flags().Bool("nogroup", false, "nogroup")
// Add flags to a group
childCmd.MarkFlagsRequiredTogether("ingroup1", "ingroup2", "ingroup3")
return rootCmd
}
// Each test case uses a unique command from the function above.
testcases := []struct {
desc string
args []string
expectedOutput string
}{
{
desc: "flags in group not suggested without - prefix",
args: []string{"child", ""},
expectedOutput: strings.Join([]string{
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "flags in group suggested with - prefix",
args: []string{"child", "-"},
expectedOutput: strings.Join([]string{
"--ingroup1",
"--ingroup2",
"--ingroup3",
"--nogroup",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "when flag in group present, other flags in group suggested even without - prefix",
args: []string{"child", "--ingroup2", "value", ""},
expectedOutput: strings.Join([]string{
"--ingroup1",
"--ingroup3",
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "when all flags in group present, flags not suggested without - prefix",
args: []string{"child", "--ingroup1", "8", "--ingroup2", "value2", "--ingroup3", ""},
expectedOutput: strings.Join([]string{
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "group ignored if some flags not applicable",
args: []string{"--ingroup2", "value", ""},
expectedOutput: strings.Join([]string{
"child",
"completion",
"help",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
}
for _, tc := range testcases {
t.Run(tc.desc, func(t *testing.T) {
c := getCmd()
args := []string{ShellCompNoDescRequestCmd}
args = append(args, tc.args...)
output, err := executeCommand(c, args...)
switch {
case err == nil && output != tc.expectedOutput:
t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)
case err != nil:
t.Errorf("Unexpected error %q", err)
}
})
}
}
func TestCompletionForMutuallyExclusiveFlags(t *testing.T) {
getCmd := func() *Command {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
childCmd := &Command{
Use: "child",
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"subArg"}, ShellCompDirectiveNoFileComp
},
Run: emptyRun,
}
rootCmd.AddCommand(childCmd)
rootCmd.PersistentFlags().IntSlice("ingroup1", []int{1}, "ingroup1")
rootCmd.PersistentFlags().String("ingroup2", "", "ingroup2")
childCmd.Flags().Bool("ingroup3", false, "ingroup3")
childCmd.Flags().Bool("nogroup", false, "nogroup")
// Add flags to a group
childCmd.MarkFlagsMutuallyExclusive("ingroup1", "ingroup2", "ingroup3")
return rootCmd
}
// Each test case uses a unique command from the function above.
testcases := []struct {
desc string
args []string
expectedOutput string
}{
{
desc: "flags in mutually exclusive group not suggested without the - prefix",
args: []string{"child", ""},
expectedOutput: strings.Join([]string{
"subArg",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "flags in mutually exclusive group suggested with the - prefix",
args: []string{"child", "-"},
expectedOutput: strings.Join([]string{
"--ingroup1",
"--ingroup2",
"--ingroup3",
"--nogroup",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "when flag in mutually exclusive group present, other flags in group not suggested even with the - prefix",
args: []string{"child", "--ingroup1", "8", "-"},
expectedOutput: strings.Join([]string{
"--ingroup1", // Should be suggested again since it is a slice
"--nogroup",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
{
desc: "group ignored if some flags not applicable",
args: []string{"--ingroup1", "8", "-"},
expectedOutput: strings.Join([]string{
"--ingroup1",
"--ingroup2",
":4",
"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),
},
}
for _, tc := range testcases {
t.Run(tc.desc, func(t *testing.T) {
c := getCmd()
args := []string{ShellCompNoDescRequestCmd}
args = append(args, tc.args...)
output, err := executeCommand(c, args...)
switch {
case err == nil && output != tc.expectedOutput:
t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)
case err != nil:
t.Errorf("Unexpected error %q", err)
}
})
}
}

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc package doc
import ( import (

View file

@ -1,9 +1,10 @@
// Copyright 2015 Red Hat Inc. All rights reserved. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc package doc
import ( import (

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc_test package doc_test
import ( import (

View file

@ -1,9 +1,10 @@
// Copyright 2015 Red Hat Inc. All rights reserved. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

View file

@ -85,7 +85,7 @@ func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string)
} }
``` ```
The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):
```go ```go
const fmTemplate = `--- const fmTemplate = `---

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc package doc
import ( import (

View file

@ -1,9 +1,10 @@
// Copyright 2015 Red Hat Inc. All rights reserved. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

View file

@ -85,7 +85,7 @@ func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, str
} }
``` ```
The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):
```go ```go
const fmTemplate = `--- const fmTemplate = `---

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc package doc
import ( import (

View file

@ -1,9 +1,10 @@
// Copyright 2015 Red Hat Inc. All rights reserved. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

View file

@ -1,9 +1,10 @@
// Copyright 2016 French Ben. All rights reserved. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
@ -22,7 +23,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v3"
) )
type cmdOption struct { type cmdOption struct {
@ -127,7 +128,7 @@ func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) str
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
continue continue
} }
result = append(result, child.Name()+" - "+child.Short) result = append(result, child.CommandPath()+" - "+child.Short)
} }
yamlDoc.SeeAlso = result yamlDoc.SeeAlso = result
} }

View file

@ -82,7 +82,7 @@ func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) str
} }
``` ```
The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):
```go ```go
const fmTemplate = `--- const fmTemplate = `---

View file

@ -1,7 +1,22 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc package doc
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -24,6 +39,7 @@ func TestGenYamlDoc(t *testing.T) {
checkStringContains(t, output, "rootflag") checkStringContains(t, output, "rootflag")
checkStringContains(t, output, rootCmd.Short) checkStringContains(t, output, rootCmd.Short)
checkStringContains(t, output, echoSubCmd.Short) checkStringContains(t, output, echoSubCmd.Short)
checkStringContains(t, output, fmt.Sprintf("- %s - %s", echoSubCmd.CommandPath(), echoSubCmd.Short))
} }
func TestGenYamlNoTag(t *testing.T) { func TestGenYamlNoTag(t *testing.T) {

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -38,7 +52,8 @@ function __%[1]s_perform_completion
__%[1]s_debug "args: $args" __%[1]s_debug "args: $args"
__%[1]s_debug "last arg: $lastArg" __%[1]s_debug "last arg: $lastArg"
set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg" # Disable ActiveHelp which is not supported for fish shell
set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
__%[1]s_debug "Calling $requestComp" __%[1]s_debug "Calling $requestComp"
set -l results (eval $requestComp 2> /dev/null) set -l results (eval $requestComp 2> /dev/null)
@ -196,7 +211,7 @@ complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
`, nameForVar, name, compCmd, `, nameForVar, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
} }
// GenFishCompletion generates fish completion file and writes to the passed writer. // GenFishCompletion generates fish completion file and writes to the passed writer.

View file

@ -1,7 +1,24 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
"bytes" "bytes"
"fmt"
"log"
"os"
"testing" "testing"
) )
@ -67,3 +84,69 @@ func TestProgWithColon(t *testing.T) {
check(t, output, "-c root:colon") check(t, output, "-c root:colon")
checkOmit(t, output, "-c root_colon") checkOmit(t, output, "-c root_colon")
} }
func TestFishCompletionNoActiveHelp(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
buf := new(bytes.Buffer)
assertNoErr(t, c.GenFishCompletion(buf, true))
output := buf.String()
// check that active help is being disabled
activeHelpVar := activeHelpEnvVar(c.Name())
check(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}
func TestGenFishCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0755)
if err != nil {
log.Fatal(err.Error())
}
defer os.RemoveAll("./tmp")
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child := &Command{
Use: "child",
ValidArgsFunction: validArgsFunc,
Run: emptyRun,
}
rootCmd.AddCommand(child)
assertNoErr(t, rootCmd.GenFishCompletionFile("./tmp/test", false))
}
func TestFailGenFishCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0755)
if err != nil {
log.Fatal(err.Error())
}
defer os.RemoveAll("./tmp")
f, _ := os.OpenFile("./tmp/test", os.O_CREATE, 0400)
defer f.Close()
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child := &Command{
Use: "child",
ValidArgsFunction: validArgsFunc,
Run: emptyRun,
}
rootCmd.AddCommand(child)
got := rootCmd.GenFishCompletionFile("./tmp/test", false)
if got == nil {
t.Error("should raise permission denied error")
}
if os.Getenv("MSYSTEM") == "MINGW64" {
if got.Error() != "open ./tmp/test: Access is denied." {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: Access is denied.")
}
} else {
if got.Error() != "open ./tmp/test: permission denied" {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: permission denied")
}
}
}

View file

@ -1,9 +1,10 @@
// Copyright © 2022 Steve Francia <spf@spf13.com>. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
@ -58,9 +59,9 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
} }
} }
// validateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the // ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the
// first error encountered. // first error encountered.
func (c *Command) validateFlagGroups() error { func (c *Command) ValidateFlagGroups() error {
if c.DisableFlagParsing { if c.DisableFlagParsing {
return nil return nil
} }
@ -172,3 +173,52 @@ func sortedKeys(m map[string]map[string]bool) []string {
sort.Strings(keys) sort.Strings(keys)
return keys return keys
} }
// enforceFlagGroupsForCompletion will do the following:
// - when a flag in a group is present, other flags in the group will be marked required
// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
// This allows the standard completion logic to behave appropriately for flag groups
func (c *Command) enforceFlagGroupsForCompletion() {
if c.DisableFlagParsing {
return
}
flags := c.Flags()
groupStatus := 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, mutuallyExclusive, mutuallyExclusiveGroupStatus)
})
// If a flag that is part of a group is present, we make all the other flags
// of that group required so that the shell completion suggests them automatically
for flagList, flagnameAndStatus := range groupStatus {
for _, isSet := range flagnameAndStatus {
if isSet {
// One of the flags of the group is set, mark the other ones as required
for _, fName := range strings.Split(flagList, " ") {
_ = c.MarkFlagRequired(fName)
}
}
}
}
// If a flag that is mutually exclusive to others is present, we hide the other
// flags of that group so the shell completion does not suggest them
for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {
for flagName, isSet := range flagnameAndStatus {
if isSet {
// One of the flags of the mutually exclusive group is set, mark the other ones as hidden
// Don't mark the flag that is already set as hidden because it may be an
// array or slice flag and therefore must continue being suggested
for _, fName := range strings.Split(flagList, " ") {
if fName != flagName {
flag := c.Flags().Lookup(fName)
flag.Hidden = true
}
}
}
}
}
}

View file

@ -1,9 +1,10 @@
// Copyright © 2022 Steve Francia <spf@spf13.com>. // Copyright 2013-2022 The Cobra Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0 //
// http://www.apache.org/licenses/LICENSE-2.0
// //
// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

4
go.mod
View file

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/cpuguy83/go-md2man/v2 v2.0.2 github.com/cpuguy83/go-md2man/v2 v2.0.2
github.com/inconshreveable/mousetrap v1.0.0 github.com/inconshreveable/mousetrap v1.0.1
github.com/spf13/pflag v1.0.5 github.com/spf13/pflag v1.0.5
gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v3 v3.0.1
) )

8
go.sum
View file

@ -1,12 +1,12 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 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.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but // The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
// can be downloaded separately for windows 7 or 8.1). // can be downloaded separately for windows 7 or 8.1).
@ -61,6 +75,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
# Prepare the command to request completions for the program. # Prepare the command to request completions for the program.
# Split the command at the first space to separate the program and arguments. # Split the command at the first space to separate the program and arguments.
$Program,$Arguments = $Command.Split(" ",2) $Program,$Arguments = $Command.Split(" ",2)
$RequestComp="$Program %[2]s $Arguments" $RequestComp="$Program %[2]s $Arguments"
__%[1]s_debug "RequestComp: $RequestComp" __%[1]s_debug "RequestComp: $RequestComp"
@ -90,11 +105,13 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
} }
__%[1]s_debug "Calling $RequestComp" __%[1]s_debug "Calling $RequestComp"
# First disable ActiveHelp which is not supported for Powershell
$env:%[8]s=0
#call the command store the output in $out and redirect stderr and stdout to null #call the command store the output in $out and redirect stderr and stdout to null
# $Out is an array contains each line per element # $Out is an array contains each line per element
Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
# get directive from last line # get directive from last line
[int]$Directive = $Out[-1].TrimStart(':') [int]$Directive = $Out[-1].TrimStart(':')
if ($Directive -eq "") { if ($Directive -eq "") {
@ -242,7 +259,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
} }
`, name, compCmd, `, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
} }
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {

View file

@ -0,0 +1,33 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra
import (
"bytes"
"fmt"
"testing"
)
func TestPwshCompletionNoActiveHelp(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
buf := new(bytes.Buffer)
assertNoErr(t, c.GenPowerShellCompletion(buf))
output := buf.String()
// check that active help is being disabled
activeHelpVar := activeHelpEnvVar(c.Name())
check(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}

View file

@ -1,8 +1,10 @@
## Projects using Cobra ## Projects using Cobra
- [Arduino CLI](https://github.com/arduino/arduino-cli) - [Arduino CLI](https://github.com/arduino/arduino-cli)
- [Bleve](http://www.blevesearch.com/) - [Bleve](https://blevesearch.com/)
- [CockroachDB](http://www.cockroachlabs.com/) - [Cilium](https://cilium.io/)
- [CloudQuery](https://github.com/cloudquery/cloudquery)
- [CockroachDB](https://www.cockroachlabs.com/)
- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) - [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)
- [Datree](https://github.com/datreeio/datree) - [Datree](https://github.com/datreeio/datree)
- [Delve](https://github.com/derekparker/delve) - [Delve](https://github.com/derekparker/delve)
@ -11,18 +13,19 @@
- [Gardener](https://github.com/gardener/gardenctl) - [Gardener](https://github.com/gardener/gardenctl)
- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) - [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)
- [Git Bump](https://github.com/erdaltsksn/git-bump) - [Git Bump](https://github.com/erdaltsksn/git-bump)
- [Github CLI](https://github.com/cli/cli) - [GitHub CLI](https://github.com/cli/cli)
- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) - [GitHub Labeler](https://github.com/erdaltsksn/gh-label)
- [Golangci-lint](https://golangci-lint.run) - [Golangci-lint](https://golangci-lint.run)
- [GopherJS](http://www.gopherjs.org/) - [GopherJS](https://github.com/gopherjs/gopherjs)
- [GoReleaser](https://goreleaser.com) - [GoReleaser](https://goreleaser.com)
- [Helm](https://helm.sh) - [Helm](https://helm.sh)
- [Hugo](https://gohugo.io) - [Hugo](https://gohugo.io)
- [Infracost](https://github.com/infracost/infracost) - [Infracost](https://github.com/infracost/infracost)
- [Istio](https://istio.io) - [Istio](https://istio.io)
- [Kool](https://github.com/kool-dev/kool) - [Kool](https://github.com/kool-dev/kool)
- [Kubernetes](http://kubernetes.io/) - [Kubernetes](https://kubernetes.io/)
- [Kubescape](https://github.com/armosec/kubescape) - [Kubescape](https://github.com/armosec/kubescape)
- [KubeVirt](https://github.com/kubevirt/kubevirt)
- [Linkerd](https://linkerd.io/) - [Linkerd](https://linkerd.io/)
- [Mattermost-server](https://github.com/mattermost/mattermost-server) - [Mattermost-server](https://github.com/mattermost/mattermost-server)
- [Mercure](https://mercure.rocks/) - [Mercure](https://mercure.rocks/)
@ -33,14 +36,16 @@
- [Multi-gitter](https://github.com/lindell/multi-gitter) - [Multi-gitter](https://github.com/lindell/multi-gitter)
- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) - [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
- [nFPM](https://nfpm.goreleaser.com) - [nFPM](https://nfpm.goreleaser.com)
- [Okteto](https://github.com/okteto/okteto)
- [OpenShift](https://www.openshift.com/) - [OpenShift](https://www.openshift.com/)
- [Ory Hydra](https://github.com/ory/hydra) - [Ory Hydra](https://github.com/ory/hydra)
- [Ory Kratos](https://github.com/ory/kratos) - [Ory Kratos](https://github.com/ory/kratos)
- [Pixie](https://github.com/pixie-io/pixie) - [Pixie](https://github.com/pixie-io/pixie)
- [Polygon Edge](https://github.com/0xPolygon/polygon-edge) - [Polygon Edge](https://github.com/0xPolygon/polygon-edge)
- [Pouch](https://github.com/alibaba/pouch) - [Pouch](https://github.com/alibaba/pouch)
- [ProjectAtomic (enterprise)](http://www.projectatomic.io/) - [ProjectAtomic (enterprise)](https://www.projectatomic.io/)
- [Prototool](https://github.com/uber/prototool) - [Prototool](https://github.com/uber/prototool)
- [Pulumi](https://www.pulumi.com)
- [QRcp](https://github.com/claudiodangelis/qrcp) - [QRcp](https://github.com/claudiodangelis/qrcp)
- [Random](https://github.com/erdaltsksn/random) - [Random](https://github.com/erdaltsksn/random)
- [Rclone](https://rclone.org/) - [Rclone](https://rclone.org/)
@ -51,3 +56,4 @@
- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli) - [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)
- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework) - VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)
- [Werf](https://werf.io/) - [Werf](https://werf.io/)
- [ZITADEL](https://github.com/zitadel/zitadel)

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (

View file

@ -40,7 +40,7 @@ Bash:
# Linux: # Linux:
$ %[1]s completion bash > /etc/bash_completion.d/%[1]s $ %[1]s completion bash > /etc/bash_completion.d/%[1]s
# macOS: # macOS:
$ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
Zsh: Zsh:
@ -99,6 +99,11 @@ To tell Cobra *not* to provide the default `completion` command:
rootCmd.CompletionOptions.DisableDefaultCmd = true rootCmd.CompletionOptions.DisableDefaultCmd = true
``` ```
To tell Cobra to mark the default `completion` command as *hidden*:
```
rootCmd.CompletionOptions.HiddenDefaultCmd = true
```
To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:
``` ```
rootCmd.CompletionOptions.DisableNoDescFlag = true rootCmd.CompletionOptions.DisableNoDescFlag = true

View file

@ -51,7 +51,7 @@ var rootCmd = &cobra.Command{
Short: "Hugo is a very fast static site generator", Short: "Hugo is a very fast static site generator",
Long: `A Fast and Flexible Static Site Generator built with Long: `A Fast and Flexible Static Site Generator built with
love by spf13 and friends in Go. love by spf13 and friends in Go.
Complete documentation is available at http://hugo.spf13.com`, Complete documentation is available at https://gohugo.io/documentation/`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here // Do Stuff Here
}, },
@ -302,15 +302,15 @@ rootCmd.MarkPersistentFlagRequired("region")
### Flag Groups ### Flag Groups
If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then
Cobra can enforce that requirement: Cobra can enforce that requirement:
```go ```go
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
rootCmd.MarkFlagsRequiredTogether("username", "password") rootCmd.MarkFlagsRequiredTogether("username", "password")
``` ```
You can also prevent different flags from being provided together if they represent mutually You can also prevent different flags from being provided together if they represent mutually
exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
```go ```go
rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON") rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")
@ -326,30 +326,48 @@ In both of these cases:
## Positional and Custom Arguments ## Positional and Custom Arguments
Validation of positional arguments can be specified using the `Args` field Validation of positional arguments can be specified using the `Args` field of `Command`.
of `Command`.
The following validators are built in: The following validators are built in:
- `NoArgs` - the command will report an error if there are any positional args. - Number of arguments:
- `ArbitraryArgs` - the command will accept any args. - `NoArgs` - report an error if there are any positional args.
- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. - `ArbitraryArgs` - accept any number of args.
- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. - `MinimumNArgs(int)` - report an error if less than N positional args are provided.
- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. - `MaximumNArgs(int)` - report an error if more than N positional args are provided.
- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. - `ExactArgs(int)` - report an error if there are not exactly N positional args.
- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command` - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.
- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. - Content of the arguments:
- `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities). - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.
An example of setting the custom validator: If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.
Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.
For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional
args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as
shown below:
```go
var cmd = &cobra.Command{
Short: "hello",
Args: MatchAll(ExactArgs(2), OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
}
```
It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.
For example:
```go ```go
var cmd = &cobra.Command{ var cmd = &cobra.Command{
Short: "hello", Short: "hello",
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 { // Optionally run one of the validators provided by cobra
return errors.New("requires a color argument") if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
return err
} }
// Run the custom validation logic
if myapp.IsValidColor(args[0]) { if myapp.IsValidColor(args[0]) {
return nil return nil
} }
@ -429,7 +447,7 @@ a count and a string.`,
} }
``` ```
For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).
## Help Command ## Help Command
@ -444,28 +462,29 @@ create' is called. Every command will automatically have the '--help' flag adde
The following output is automatically generated by Cobra. Nothing beyond the The following output is automatically generated by Cobra. Nothing beyond the
command and flag definitions are needed. command and flag definitions are needed.
$ cobra help $ cobra-cli help
Cobra is a CLI library for Go that empowers applications. Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files This application is a tool to generate the needed files
to quickly create a Cobra application. to quickly create a Cobra application.
Usage: Usage:
cobra [command] cobra-cli [command]
Available Commands: Available Commands:
add Add a command to a Cobra Application add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell
help Help about any command help Help about any command
init Initialize a Cobra Application init Initialize a Cobra Application
Flags: Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME") -a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml) --config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra -h, --help help for cobra-cli
-l, --license string name of license for the project -l, --license string name of license for the project
--viper use Viper for configuration (default true) --viper use Viper for configuration
Use "cobra [command] --help" for more information about a command. Use "cobra-cli [command] --help" for more information about a command.
Help is just a command like any other. There is no special logic or behavior Help is just a command like any other. There is no special logic or behavior
@ -474,7 +493,7 @@ around it. In fact, you can provide your own if you want.
### Defining your own help ### Defining your own help
You can provide your own Help command or your own template for the default command to use You can provide your own Help command or your own template for the default command to use
with following functions: with the following functions:
```go ```go
cmd.SetHelpCommand(cmd *Command) cmd.SetHelpCommand(cmd *Command)
@ -493,22 +512,23 @@ showing the user the 'usage'.
You may recognize this from the help above. That's because the default help You may recognize this from the help above. That's because the default help
embeds the usage as part of its output. embeds the usage as part of its output.
$ cobra --invalid $ cobra-cli --invalid
Error: unknown flag: --invalid Error: unknown flag: --invalid
Usage: Usage:
cobra [command] cobra-cli [command]
Available Commands: Available Commands:
add Add a command to a Cobra Application add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell
help Help about any command help Help about any command
init Initialize a Cobra Application init Initialize a Cobra Application
Flags: Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME") -a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml) --config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra -h, --help help for cobra-cli
-l, --license string name of license for the project -l, --license string name of license for the project
--viper use Viper for configuration (default true) --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.
@ -627,7 +647,7 @@ Did you mean this?
Run 'hugo --help' for usage. Run 'hugo --help' for usage.
``` ```
Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
If you need to disable suggestions or tweak the string distance in your command, use: If you need to disable suggestions or tweak the string distance in your command, use:
@ -641,7 +661,8 @@ or
command.SuggestionsMinimumDistance = 1 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 makes sense in your set of commands and for some which you don't want aliases. Example: 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:
``` ```
$ kubectl remove $ kubectl remove
@ -660,3 +681,7 @@ Cobra can generate documentation based on subcommands, flags, etc. Read more abo
## Generating shell completions ## Generating shell completions
Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).
## Providing Active Help
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).

View file

@ -1,3 +1,17 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra package cobra
import ( import (
@ -75,7 +89,7 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
if !includeDesc { if !includeDesc {
compCmd = ShellCompNoDescRequestCmd compCmd = ShellCompNoDescRequestCmd
} }
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
# zsh completion for %-36[1]s -*- shell-script -*- # zsh completion for %-36[1]s -*- shell-script -*-
@ -163,7 +177,24 @@ _%[1]s()
return return
fi fi
local activeHelpMarker="%[8]s"
local endIndex=${#activeHelpMarker}
local startIndex=$((${#activeHelpMarker}+1))
local hasActiveHelp=0
while IFS='\n' read -r comp; do while IFS='\n' read -r comp; do
# Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
__%[1]s_debug "ActiveHelp found: $comp"
comp="${comp[$startIndex,-1]}"
if [ -n "$comp" ]; then
compadd -x "${comp}"
__%[1]s_debug "ActiveHelp will need delimiter"
hasActiveHelp=1
fi
continue
fi
if [ -n "$comp" ]; then if [ -n "$comp" ]; then
# If requested, completions are returned with a description. # If requested, completions are returned with a description.
# The description is preceded by a TAB character. # The description is preceded by a TAB character.
@ -180,6 +211,17 @@ _%[1]s()
fi fi
done < <(printf "%%s\n" "${out[@]}") done < <(printf "%%s\n" "${out[@]}")
# Add a delimiter after the activeHelp statements, but only if:
# - there are completions following the activeHelp statements, or
# - file completion will be performed (so there will be choices after the activeHelp)
if [ $hasActiveHelp -eq 1 ]; then
if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
__%[1]s_debug "Adding activeHelp delimiter"
compadd -x "--"
hasActiveHelp=0
fi
fi
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
__%[1]s_debug "Activating nospace." __%[1]s_debug "Activating nospace."
noSpace="-S ''" noSpace="-S ''"
@ -254,5 +296,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then
fi fi
`, name, compCmd, `, name, compCmd,
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
activeHelpMarker))
} }

33
zsh_completions_test.go Normal file
View file

@ -0,0 +1,33 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra
import (
"bytes"
"fmt"
"testing"
)
func TestZshCompletionWithActiveHelp(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
buf := new(bytes.Buffer)
assertNoErr(t, c.GenZshCompletion(buf))
output := buf.String()
// check that active help is not being disabled
activeHelpVar := activeHelpEnvVar(c.Name())
checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}