mirror of
https://github.com/spf13/cobra
synced 2025-05-04 20:37:24 +00:00
Compare commits
198 commits
Author | SHA1 | Date | |
---|---|---|---|
|
ceb39aba25 | ||
|
c25b598345 | ||
|
4f9ef8cdbb | ||
|
1995054b00 | ||
|
f98cf4216d | ||
|
0d417d8f77 | ||
|
40b5bc1437 | ||
|
a97f9fd47b | ||
|
5f9c40898e | ||
|
24ada7fe71 | ||
|
680936a220 | ||
|
8cb30f9ca5 | ||
|
17b6dca2ff | ||
|
ab5cadcc1b | ||
|
4ba5566f57 | ||
|
41b26ec8bb | ||
|
611e16c322 | ||
|
09d5664f34 | ||
|
6c3c1163c6 | ||
|
01ffff4eca | ||
|
0745e55762 | ||
|
d1e9d85fcf | ||
|
9f9056765c | ||
|
8519630750 | ||
|
02326d52c0 | ||
|
5a138f143f | ||
|
3a5efaede9 | ||
|
5bef9d8d87 | ||
|
ff7c561cf7 | ||
|
11ab62158a | ||
|
78bfc837fe | ||
|
511af59cb3 | ||
|
756ba6dad6 | ||
|
371ae25d2c | ||
|
e94f6d0dd9 | ||
|
8003b74a10 | ||
|
5c2c1d627d | ||
|
5a1acea321 | ||
|
0fc86c2ffd | ||
|
6b5f577ebc | ||
|
bd914e58d6 | ||
|
1f80fa2e23 | ||
|
c69ae4c36b | ||
|
a30cee5e5a | ||
|
f34069ccf5 | ||
|
bd2655e76c | ||
|
bcfcff729e | ||
|
4fb0a66a34 | ||
|
0dec88e793 | ||
|
cbcf75eab9 | ||
|
199b7abe12 | ||
|
531ce793e3 | ||
|
c054701f6a | ||
|
41227856cd | ||
|
a73b9c391a | ||
|
df547f5fc6 | ||
|
e63925d321 | ||
|
236f3c0418 | ||
|
3d8ac432bd | ||
|
283e32d889 | ||
|
a0a6ae020b | ||
|
890302a35f | ||
|
48cea5c87b | ||
|
22953d8845 | ||
|
00b68a1c26 | ||
|
b711e8760b | ||
|
8b1eba4761 | ||
|
4cafa37bc4 | ||
|
5c962a221e | ||
|
efe8fa3e44 | ||
|
95d8a1e45d | ||
|
bd4d1655f6 | ||
|
0c72800b8d | ||
|
c5dacb3ea4 | ||
|
285460dca6 | ||
|
4955da7c11 | ||
|
fd865a44e3 | ||
|
60d056d157 | ||
|
66b215ba18 | ||
|
c81c46a015 | ||
|
dcb405a939 | ||
|
cbe4865373 | ||
|
fdee73b4a0 | ||
|
988bd76139 | ||
|
2246fa82e9 | ||
|
0e3a0bfe91 | ||
|
284f410104 | ||
|
4dd4b25de3 | ||
|
45360a55cc | ||
|
c8a20a16ba | ||
|
b197a24504 | ||
|
9e6b58afc7 | ||
|
fb3652402b | ||
|
c7300f0bdd | ||
|
567ea8ebc9 | ||
|
3daa4b9c36 | ||
|
a516d4132c | ||
|
e839bb342f | ||
|
87ebcd8f98 | ||
|
8b8ee8754c | ||
|
d022c0fe2b | ||
|
4fa4fdf5cd | ||
|
b4f979ae35 | ||
|
bf11ab6321 | ||
|
fdffa5a4c7 | ||
|
f25a3c6e0b | ||
|
923592041e | ||
|
a6f198b635 | ||
|
7bb1440003 | ||
|
6200c8e551 | ||
|
c6b9971923 | ||
|
430549841b | ||
|
ad6db7f8f6 | ||
|
6b0bd3076c | ||
|
cc7e235fc2 | ||
|
10cf7be997 | ||
|
4b9d00dfec | ||
|
badcce14f8 | ||
|
1424b7b927 | ||
|
860791844e | ||
|
2169adb574 | ||
|
212ea40783 | ||
|
d4040ad8db | ||
|
23fc5e099f | ||
|
93d1913fb0 | ||
|
07034fee49 | ||
|
3dc9761b36 | ||
|
7039e1fa21 | ||
|
fce8d8aeb0 | ||
|
a281c8b47b | ||
|
459fc5fce3 | ||
|
6d978a911e | ||
|
4065a33bfd | ||
|
7e289f46f1 | ||
|
fe08012edd | ||
|
d689184a42 | ||
|
70e53f62be | ||
|
2e8ba6f308 | ||
|
0580724b5f | ||
|
2a7647ff46 | ||
|
7045405250 | ||
|
22b617914c | ||
|
dbf85f6104 | ||
|
f911c0b89c | ||
|
7790bf97fd | ||
|
6bf8cd8582 | ||
|
965924ac89 | ||
|
162534f92f | ||
|
a0aadc68eb | ||
|
69083f81b2 | ||
|
bba9331d4e | ||
|
3d38d18a23 | ||
|
06b06a9dc9 | ||
|
5f2ec3c897 | ||
|
b9ca5949e2 | ||
|
ea94a3db55 | ||
|
7c9831d376 | ||
|
ed7bb9dda4 | ||
|
f464d6c82e | ||
|
7dc8b004e6 | ||
|
87ea1807f7 | ||
|
ca8e3c2779 | ||
|
37d481d4d4 | ||
|
5b11656e45 | ||
|
ffa8860dbe | ||
|
e1ded5cd94 | ||
|
8afe9d1b56 | ||
|
25f5bb5f97 | ||
|
9e88759b19 | ||
|
fb8031162c | ||
|
95d7df1858 | ||
|
f17e5a27c9 | ||
|
09d6ba690f | ||
|
4f0facbcee | ||
|
2722a75ba3 | ||
|
d8184d3269 | ||
|
b9460ccc12 | ||
|
89d7b832c7 | ||
|
68b6b24f0c | ||
|
bf6cb5804d | ||
|
9d15fe657a | ||
|
5271cf4342 | ||
|
ab42c937ec | ||
|
52e6099aea | ||
|
5414d3d45d | ||
|
cf0df73277 | ||
|
3723151d17 | ||
|
1568491a09 | ||
|
d622355c84 | ||
|
03c3eb73f8 | ||
|
3a1795bc25 | ||
|
f848943afd | ||
|
5d066b77b5 | ||
|
94e552d8d6 | ||
|
8cc7be2119 | ||
|
65b1195d6e | ||
|
37463cff2c | ||
|
81d27c8f8d |
64 changed files with 6294 additions and 795 deletions
19
.github/labeler.yml
vendored
19
.github/labeler.yml
vendored
|
@ -1,17 +1,24 @@
|
|||
# changes to documentation generation
|
||||
"area/docs-generation": doc/**/*
|
||||
"area/docs-generation":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'doc/**'
|
||||
|
||||
# changes to the core cobra command
|
||||
"area/cobra-command":
|
||||
- any: ['./cobra.go', './cobra_test.go', './*command*.go']
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: ['./cobra.go', './cobra_test.go', './*command*.go']
|
||||
|
||||
# changes made to command flags/args
|
||||
"area/flags": ./args*.go
|
||||
"area/flags":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: './args*.go'
|
||||
|
||||
# changes to Github workflows
|
||||
"area/github": .github/**/*
|
||||
"area/github":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: '.github/**'
|
||||
|
||||
# changes to shell completions
|
||||
"area/shell-completion":
|
||||
- ./*completions*
|
||||
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: './*completions*'
|
||||
|
|
8
.github/workflows/labeler.yml
vendored
8
.github/workflows/labeler.yml
vendored
|
@ -2,11 +2,17 @@ name: "Pull Request Labeler"
|
|||
on:
|
||||
- pull_request_target
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
permissions:
|
||||
contents: read # for actions/labeler to determine modified files
|
||||
pull-requests: write # for actions/labeler to add labels to PRs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v3
|
||||
- uses: actions/labeler@v5
|
||||
with:
|
||||
repo-token: "${{ github.token }}"
|
||||
|
||||
|
|
21
.github/workflows/stale.yml
vendored
21
.github/workflows/stale.yml
vendored
|
@ -1,21 +0,0 @@
|
|||
name: Mark stale issues and pull requests
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/stale@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: 'This issue is being marked as stale due to a long period of inactivity'
|
||||
stale-pr-message: 'This PR is being marked as stale due to a long period of inactivity'
|
||||
stale-issue-label: 'kind/stale'
|
||||
stale-pr-label: 'kind/stale'
|
||||
exempt-issue-label: 'kind/stale'
|
||||
exempt-pr-label: 'kind/stale'
|
81
.github/workflows/test.yml
vendored
81
.github/workflows/test.yml
vendored
|
@ -3,27 +3,56 @@ name: Test
|
|||
on:
|
||||
push:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
GO111MODULE: on
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
|
||||
golangci-lint:
|
||||
|
||||
lic-headers:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- uses: actions/setup-go@v2
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- run: >-
|
||||
docker run
|
||||
-v $(pwd):/wrk -w /wrk
|
||||
ghcr.io/google/addlicense
|
||||
-c 'The Cobra Authors'
|
||||
-y '2013-2023'
|
||||
-l apache
|
||||
-ignore '.github/**'
|
||||
-check
|
||||
.
|
||||
|
||||
|
||||
golangci-lint:
|
||||
permissions:
|
||||
contents: read # for actions/checkout to fetch code
|
||||
pull-requests: read # for golangci/golangci-lint-action to fetch pull requests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.17'
|
||||
go-version: '^1.22'
|
||||
check-latest: true
|
||||
cache: true
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- uses: golangci/golangci-lint-action@v2
|
||||
- uses: golangci/golangci-lint-action@v4.0.0
|
||||
with:
|
||||
version: latest
|
||||
args: --verbose
|
||||
|
||||
|
||||
test-unix:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
@ -32,36 +61,32 @@ jobs:
|
|||
- ubuntu
|
||||
- macOS
|
||||
go:
|
||||
- 14
|
||||
- 15
|
||||
- 16
|
||||
- 17
|
||||
- 18
|
||||
- 19
|
||||
- 20
|
||||
- 21
|
||||
- 22
|
||||
- 23
|
||||
- 24
|
||||
name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'
|
||||
runs-on: ${{ matrix.platform }}-latest
|
||||
steps:
|
||||
|
||||
- uses: actions/setup-go@v2
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.${{ matrix.go }}.x
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-1.${{ matrix.go }}.x-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-1.${{ matrix.go }}.x-
|
||||
cache: true
|
||||
|
||||
- run: |
|
||||
export GOBIN=$HOME/go/bin
|
||||
case "${{ matrix.go }}" in
|
||||
16|17) _version='@latest';;
|
||||
*) _version='';;
|
||||
esac
|
||||
go install github.com/kyoh86/richgo"${_version}"
|
||||
go install github.com/mitchellh/gox"${_version}"
|
||||
go install github.com/kyoh86/richgo@latest
|
||||
go install github.com/mitchellh/gox@latest
|
||||
|
||||
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make richtest
|
||||
|
||||
- run: PATH=$HOME/go/bin/:$PATH make test
|
||||
|
||||
test-win:
|
||||
name: MINGW64
|
||||
|
@ -84,9 +109,9 @@ jobs:
|
|||
unzip
|
||||
mingw-w64-x86_64-go
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/cache@v2
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-${{ matrix.go }}-${{ hashFiles('**/go.sum') }}
|
||||
|
@ -97,4 +122,4 @@ jobs:
|
|||
go install github.com/kyoh86/richgo@latest
|
||||
go install github.com/mitchellh/gox@latest
|
||||
|
||||
- run: PATH=$HOME/go/bin:$PATH make test
|
||||
- run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make richtest
|
||||
|
|
|
@ -1,3 +1,17 @@
|
|||
# Copyright 2013-2023 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:
|
||||
deadline: 5m
|
||||
|
||||
|
@ -5,44 +19,39 @@ linters:
|
|||
disable-all: true
|
||||
enable:
|
||||
#- bodyclose
|
||||
- deadcode
|
||||
# - deadcode ! deprecated since v1.49.0; replaced by 'unused'
|
||||
#- depguard
|
||||
#- dogsled
|
||||
#- dupl
|
||||
- errcheck
|
||||
#- exhaustive
|
||||
#- funlen
|
||||
- gas
|
||||
#- gochecknoinits
|
||||
- goconst
|
||||
#- gocritic
|
||||
- gocritic
|
||||
#- gocyclo
|
||||
#- gofmt
|
||||
- gofmt
|
||||
- goimports
|
||||
- golint
|
||||
#- gomnd
|
||||
#- goprintffuncname
|
||||
#- gosec
|
||||
#- gosimple
|
||||
- gosec
|
||||
- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- interfacer
|
||||
#- lll
|
||||
- maligned
|
||||
- megacheck
|
||||
#- misspell
|
||||
- misspell
|
||||
#- nakedret
|
||||
#- noctx
|
||||
#- nolintlint
|
||||
- nolintlint
|
||||
#- rowserrcheck
|
||||
#- scopelint
|
||||
#- staticcheck
|
||||
- structcheck
|
||||
#- stylecheck
|
||||
- staticcheck
|
||||
#- structcheck ! deprecated since v1.49.0; replaced by 'unused'
|
||||
- stylecheck
|
||||
#- typecheck
|
||||
- unconvert
|
||||
#- unparam
|
||||
#- unused
|
||||
- varcheck
|
||||
- unused
|
||||
# - varcheck ! deprecated since v1.49.0; replaced by 'unused'
|
||||
#- whitespace
|
||||
fast: false
|
||||
|
|
51
CHANGELOG.md
51
CHANGELOG.md
|
@ -1,51 +0,0 @@
|
|||
# Cobra Changelog
|
||||
|
||||
## v1.1.3
|
||||
|
||||
* **Fix:** release-branch.cobra1.1 only: Revert "Deprecate Go < 1.14" to maintain backward compatibility
|
||||
|
||||
## v1.1.2
|
||||
|
||||
### Notable Changes
|
||||
|
||||
* Bump license year to 2021 in golden files (#1309) @Bowbaq
|
||||
* Enhance PowerShell completion with custom comp (#1208) @Luap99
|
||||
* Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670
|
||||
* Documentation readability improvements (#1228 etc.) @zaataylor etc.
|
||||
* Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor
|
||||
|
||||
## v1.1.1
|
||||
|
||||
* **Fix:** yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context.
|
||||
* **Fix:** correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context.
|
||||
|
||||
## v1.1.0
|
||||
|
||||
### Notable Changes
|
||||
|
||||
* Extend Go completions and revamp zsh comp (#1070)
|
||||
* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` (#1104) @jpmcb
|
||||
* Add completion for help command (#1136)
|
||||
* Complete subcommands when TraverseChildren is set (#1171)
|
||||
* Fix stderr printing functions (#894)
|
||||
* fix: fish output redirection (#1247)
|
||||
|
||||
## v1.0.0
|
||||
|
||||
Announcing v1.0.0 of Cobra. 🎉
|
||||
|
||||
### Notable Changes
|
||||
* Fish completion (including support for Go custom completion) @marckhouzam
|
||||
* API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam
|
||||
* Remove/replace SetOutput on Command - deprecated @jpmcb
|
||||
* add support for autolabel stale PR @xchapter7x
|
||||
* Add Labeler Actions @xchapter7x
|
||||
* Custom completions coded in Go (instead of Bash) @marckhouzam
|
||||
* Partial Revert of #922 @jharshman
|
||||
* Add Makefile to project @jharshman
|
||||
* Correct documentation for InOrStdin @desponda
|
||||
* Apply formatting to templates @jharshman
|
||||
* Revert change so help is printed on stdout again @marckhouzam
|
||||
* Update md2man to v2.0.0 @pdf
|
||||
* update viper to v1.4.0 @umarcor
|
||||
* Update cmd/root.go example in README.md @jharshman
|
8
Makefile
8
Makefile
|
@ -5,10 +5,6 @@ ifeq (, $(shell which golangci-lint))
|
|||
$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")
|
||||
endif
|
||||
|
||||
ifeq (, $(shell which richgo))
|
||||
$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")
|
||||
endif
|
||||
|
||||
.PHONY: fmt lint test install_deps clean
|
||||
|
||||
default: all
|
||||
|
@ -25,6 +21,10 @@ lint:
|
|||
|
||||
test: install_deps
|
||||
$(info ******************** running tests ********************)
|
||||
go test -v ./...
|
||||
|
||||
richtest: install_deps
|
||||
$(info ******************** running tests with kyoh86/richgo ********************)
|
||||
richgo test -v ./...
|
||||
|
||||
install_deps:
|
||||
|
|
26
README.md
26
README.md
|
@ -1,12 +1,13 @@
|
|||

|
||||
|
||||

|
||||
|
||||
Cobra is a library for creating powerful modern CLI applications.
|
||||
|
||||
Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/),
|
||||
[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to
|
||||
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
|
||||
Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
|
||||
[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
|
||||
name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.
|
||||
|
||||
[](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
|
||||
[](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
|
||||
[](https://pkg.go.dev/github.com/spf13/cobra)
|
||||
[](https://goreportcard.com/report/github.com/spf13/cobra)
|
||||
[](https://gophers.slack.com/archives/CD3LP1199)
|
||||
|
@ -23,12 +24,13 @@ Cobra provides:
|
|||
* Global, local and cascading flags
|
||||
* Intelligent suggestions (`app srver`... did you mean `app server`?)
|
||||
* Automatic help generation for commands and flags
|
||||
* Grouping help for subcommands
|
||||
* Automatic help flag recognition of `-h`, `--help`, etc.
|
||||
* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
|
||||
* Automatically generated man pages for your application
|
||||
* Command aliases so you can change things without breaking them
|
||||
* 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
|
||||
|
||||
|
@ -40,9 +42,9 @@ The best applications read like sentences when used, and as a result, users
|
|||
intuitively know how to interact with them.
|
||||
|
||||
The pattern to follow is
|
||||
`APPNAME VERB NOUN --ADJECTIVE.`
|
||||
`APPNAME VERB NOUN --ADJECTIVE`
|
||||
or
|
||||
`APPNAME COMMAND ARG --FLAG`
|
||||
`APPNAME COMMAND ARG --FLAG`.
|
||||
|
||||
A few good real world examples may better illustrate this point.
|
||||
|
||||
|
@ -79,7 +81,7 @@ which maintains the same interface while adding POSIX compliance.
|
|||
|
||||
# Installing
|
||||
Using Cobra is easy. First, use `go get` to install the latest version
|
||||
of the library.
|
||||
of the library.
|
||||
|
||||
```
|
||||
go get -u github.com/spf13/cobra@latest
|
||||
|
@ -102,10 +104,10 @@ It can be installed by running:
|
|||
go install github.com/spf13/cobra-cli@latest
|
||||
```
|
||||
|
||||
For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/master/README.md)
|
||||
For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
|
||||
|
||||
For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).
|
||||
For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md).
|
||||
|
||||
# License
|
||||
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)
|
||||
|
|
105
SECURITY.md
Normal file
105
SECURITY.md
Normal file
|
@ -0,0 +1,105 @@
|
|||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
The `cobra` maintainers take security issues seriously and
|
||||
we appreciate your efforts to _**responsibly**_ disclose your findings.
|
||||
We will make every effort to swiftly respond and address concerns.
|
||||
|
||||
To report a security vulnerability:
|
||||
|
||||
1. **DO NOT** create a public GitHub issue for the vulnerability!
|
||||
2. **DO NOT** create a public GitHub Pull Request with a fix for the vulnerability!
|
||||
3. Send an email to `cobra-security@googlegroups.com`.
|
||||
4. Include the following details in your report:
|
||||
- Description of the vulnerability
|
||||
- Steps to reproduce
|
||||
- Potential impact of the vulnerability (to your downstream project, to the Go ecosystem, etc.)
|
||||
- Any potential mitigations you've already identified
|
||||
5. Allow up to 7 days for an initial response.
|
||||
You should receive an acknowledgment of your report and an estimated timeline for a fix.
|
||||
6. (Optional) If you have a fix and would like to contribute your patch, please work
|
||||
directly with the maintainers via `cobra-security@googlegroups.com` to
|
||||
coordinate pushing the patch to GitHub, cutting a new release, and disclosing the change.
|
||||
|
||||
## Response Process
|
||||
|
||||
When a security vulnerability report is received, the `cobra` maintainers will:
|
||||
|
||||
1. Confirm receipt of the vulnerability report within 7 days.
|
||||
2. Assess the report to determine if it constitutes a security vulnerability.
|
||||
3. If confirmed, assign the vulnerability a severity level and create a timeline for addressing it.
|
||||
4. Develop and test a fix.
|
||||
5. Patch the vulnerability and make a new GitHub release: the maintainers will coordinate disclosure with the reporter.
|
||||
6. Create a new GitHub Security Advisory to inform the broader Go ecosystem
|
||||
|
||||
## Disclosure Policy
|
||||
|
||||
The `cobra` maintainers follow a coordinated disclosure process:
|
||||
|
||||
1. Security vulnerabilities will be addressed as quickly as possible.
|
||||
2. A CVE (Common Vulnerabilities and Exposures) identifier will be requested for significant vulnerabilities
|
||||
that are within `cobra` itself.
|
||||
3. Once a fix is ready, the maintainers will:
|
||||
- Release a new version containing the fix.
|
||||
- Update the security advisory with details about the vulnerability.
|
||||
- Credit the reporter (unless they wish to remain anonymous).
|
||||
- Credit the fixer (unless they wish to remain anonymous, this may be the same as the reporter).
|
||||
- Announce the vulnerability through appropriate channels
|
||||
(GitHub Security Advisory, mailing lists, GitHub Releases, etc.)
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Security fixes will typically only be released for the most recent major release.
|
||||
|
||||
## Upstream Security Issues
|
||||
|
||||
`cobra` generally will not accept vulnerability reports that originate in upstream
|
||||
dependencies. I.e., if there is a problem in Go code that `cobra` depends on,
|
||||
it is best to engage that project's maintainers and owners.
|
||||
|
||||
This security policy primarily pertains only to `cobra` itself but if you believe you've
|
||||
identified a problem that originates in an upstream dependency and is being widely
|
||||
distributed by `cobra`, please follow the disclosure procedure above: the `cobra`
|
||||
maintainers will work with you to determine the severity and ecosystem impact.
|
||||
|
||||
## Security Updates and CVEs
|
||||
|
||||
Information about known security vulnerabilities and CVEs affecting `cobra` will
|
||||
be published as GitHub Security Advisories at
|
||||
https://github.com/spf13/cobra/security/advisories.
|
||||
|
||||
All users are encouraged to watch the repository and upgrade promptly when
|
||||
security releases are published.
|
||||
|
||||
## `cobra` Security Best Practices for Users
|
||||
|
||||
When using `cobra` in your CLIs, the `cobra` maintainers recommend the following:
|
||||
|
||||
1. Always use the latest version of `cobra`.
|
||||
2. [Use Go modules](https://go.dev/blog/using-go-modules) for dependency management.
|
||||
3. Always use the latest possible version of Go.
|
||||
|
||||
## Security Best Practices for Contributors
|
||||
|
||||
When contributing to `cobra`:
|
||||
|
||||
1. Be mindful of security implications when adding new features or modifying existing ones.
|
||||
2. Be aware of `cobra`'s extremely large reach: it is used in nearly every Go CLI
|
||||
(like Kubernetes, Docker, Prometheus, etc. etc.)
|
||||
3. Write tests that explicitly cover edge cases and potential issues.
|
||||
4. If you discover a security issue while working on `cobra`, please report it
|
||||
following the process above rather than opening a public pull request or issue that
|
||||
addresses the vulnerability.
|
||||
5. Take personal sec-ops seriously and secure your GitHub account: use [two-factor authentication](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa),
|
||||
[sign your commits with a GPG or SSH key](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification),
|
||||
etc.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
The `cobra` maintainers would like to thank all security researchers and
|
||||
community members who help keep cobra, its users, and the entire Go ecosystem secure through responsible disclosures!!
|
||||
|
||||
---
|
||||
|
||||
*This security policy is inspired by the [Open Web Application Security Project (OWASP)](https://owasp.org/) guidelines and security best practices.*
|
60
active_help.go
Normal file
60
active_help.go
Normal file
|
@ -0,0 +1,60 @@
|
|||
// Copyright 2013-2023 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"
|
||||
)
|
||||
|
||||
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 = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix
|
||||
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 []Completion, activeHelpStr string) []Completion {
|
||||
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 non-ASCII-alphanumeric characters replaced by `_`.
|
||||
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
|
||||
// is set to "0".
|
||||
func GetActiveHelpConfig(cmd *Command) string {
|
||||
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 non-ASCII-alphanumeric characters replaced by `_`.
|
||||
func activeHelpEnvVar(name string) string {
|
||||
return configEnvVar(name, activeHelpEnvVarSuffix)
|
||||
}
|
400
active_help_test.go
Normal file
400
active_help_test.go
Normal file
|
@ -0,0 +1,400 @@
|
|||
// Copyright 2013-2023 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)
|
||||
}
|
||||
}
|
44
args.go
44
args.go
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -7,7 +21,7 @@ import (
|
|||
|
||||
type PositionalArgs func(cmd *Command, args []string) error
|
||||
|
||||
// Legacy arg validation has the following behaviour:
|
||||
// legacyArgs validation has the following behaviour:
|
||||
// - root commands with no subcommands can take arbitrary arguments
|
||||
// - root commands with subcommands will do subcommand validity checking
|
||||
// - subcommands will always accept arbitrary arguments
|
||||
|
@ -32,16 +46,16 @@ func NoArgs(cmd *Command, args []string) error {
|
|||
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 {
|
||||
if len(cmd.ValidArgs) > 0 {
|
||||
// Remove any description that may be included in ValidArgs.
|
||||
// A description is following a tab character.
|
||||
var validArgs []string
|
||||
validArgs := make([]string, 0, len(cmd.ValidArgs))
|
||||
for _, v := range cmd.ValidArgs {
|
||||
validArgs = append(validArgs, strings.Split(v, "\t")[0])
|
||||
validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0])
|
||||
}
|
||||
|
||||
for _, v := range args {
|
||||
if !stringInSlice(v, validArgs) {
|
||||
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.
|
||||
func RangeArgs(min int, max int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
|
@ -119,3 +121,11 @@ func MatchAll(pargs ...PositionalArgs) PositionalArgs {
|
|||
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)
|
||||
}
|
||||
|
|
293
args_test.go
293
args_test.go
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -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 {
|
||||
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 {
|
||||
t.Fatal("Expected an error")
|
||||
}
|
||||
got := err.Error()
|
||||
expected := `unknown command "illegal" for "c"`
|
||||
expected := `unknown command "` + arg + `" for "c"`
|
||||
if got != expected {
|
||||
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) {
|
||||
c := getCommand(NoArgs, false)
|
||||
output, err := executeCommand(c)
|
||||
expectSuccess(output, err, t)
|
||||
}
|
||||
|
||||
func TestNoArgsWithArgs(t *testing.T) {
|
||||
func TestNoArgs_WithArgs(t *testing.T) {
|
||||
c := getCommand(NoArgs, false)
|
||||
_, err := executeCommand(c, "illegal")
|
||||
noArgsWithArgs(err, t)
|
||||
_, err := executeCommand(c, "one")
|
||||
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) {
|
||||
c := getCommand(OnlyValidArgs, true)
|
||||
output, err := executeCommand(c, "one", "two")
|
||||
expectSuccess(output, err, t)
|
||||
}
|
||||
|
||||
func TestOnlyValidArgsWithInvalidArgs(t *testing.T) {
|
||||
func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {
|
||||
c := getCommand(OnlyValidArgs, true)
|
||||
_, err := executeCommand(c, "a")
|
||||
validWithInvalidArgs(err, t)
|
||||
validOnlyWithInvalidArgs(err, t)
|
||||
}
|
||||
|
||||
// ArbitraryArgs
|
||||
|
||||
func TestArbitraryArgs(t *testing.T) {
|
||||
c := getCommand(ArbitraryArgs, false)
|
||||
output, err := executeCommand(c, "a", "b")
|
||||
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) {
|
||||
c := getCommand(MinimumNArgs(2), false)
|
||||
output, err := executeCommand(c, "a", "b", "c")
|
||||
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)
|
||||
_, err := executeCommand(c, "a")
|
||||
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) {
|
||||
c := getCommand(MaximumNArgs(3), false)
|
||||
output, err := executeCommand(c, "a", "b")
|
||||
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)
|
||||
_, err := executeCommand(c, "a", "b", "c")
|
||||
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) {
|
||||
c := getCommand(ExactArgs(3), false)
|
||||
output, err := executeCommand(c, "a", "b", "c")
|
||||
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)
|
||||
_, err := executeCommand(c, "a", "b", "c")
|
||||
exactArgsWithInvalidCount(err, t)
|
||||
}
|
||||
|
||||
func TestExactValidArgs(t *testing.T) {
|
||||
c := getCommand(ExactValidArgs(3), true)
|
||||
output, err := executeCommand(c, "three", "one", "two")
|
||||
expectSuccess(output, err, t)
|
||||
}
|
||||
|
||||
func TestExactValidArgsWithInvalidCount(t *testing.T) {
|
||||
c := getCommand(ExactValidArgs(2), false)
|
||||
func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {
|
||||
c := getCommand(ExactArgs(2), true)
|
||||
_, err := executeCommand(c, "three", "one", "two")
|
||||
exactArgsWithInvalidCount(err, t)
|
||||
}
|
||||
|
||||
func TestExactValidArgsWithInvalidArgs(t *testing.T) {
|
||||
c := getCommand(ExactValidArgs(3), true)
|
||||
func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {
|
||||
c := getCommand(ExactArgs(2), true)
|
||||
_, 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) {
|
||||
c := getCommand(RangeArgs(2, 4), false)
|
||||
output, err := executeCommand(c, "a", "b", "c")
|
||||
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)
|
||||
_, err := executeCommand(c, "a")
|
||||
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) {
|
||||
rootCmd := &Command{Use: "root", Run: emptyRun}
|
||||
childCmd := &Command{Use: "child", Run: emptyRun}
|
||||
|
@ -292,3 +484,58 @@ 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
|
||||
// to the legacyArgs() function.
|
||||
// It makes sure the root command accepts arguments if it does not have
|
||||
// sub-commands.
|
||||
func TestLegacyArgsRootAcceptsArgs(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", Args: nil, Run: emptyRun}
|
||||
|
||||
_, err := executeCommand(rootCmd, "somearg")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// This test make sure we keep backwards-compatibility with respect
|
||||
// to the legacyArgs() function.
|
||||
// It makes sure a sub-command accepts arguments and further sub-commands
|
||||
func TestLegacyArgsSubcmdAcceptsArgs(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", Args: nil, Run: emptyRun}
|
||||
childCmd := &Command{Use: "child", Args: nil, Run: emptyRun}
|
||||
grandchildCmd := &Command{Use: "grandchild", Args: nil, Run: emptyRun}
|
||||
rootCmd.AddCommand(childCmd)
|
||||
childCmd.AddCommand(grandchildCmd)
|
||||
|
||||
_, err := executeCommand(rootCmd, "child", "somearg")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
BIN
assets/CobraMain.png
Normal file
BIN
assets/CobraMain.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 72 KiB |
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -71,9 +85,10 @@ __%[1]s_handle_go_custom_completion()
|
|||
local out requestComp lastParam lastChar comp directive args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
|
||||
args=("${words[@]:1}")
|
||||
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))]}
|
||||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
|
@ -99,7 +114,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}"
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
# Error code. No completion.
|
||||
|
@ -125,7 +140,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
local fullFilter filter filteringCmd
|
||||
# Do not use quotes around the $out variable or else newline
|
||||
# characters will be kept.
|
||||
for filter in ${out[*]}; do
|
||||
for filter in ${out}; do
|
||||
fullFilter+="$filter|"
|
||||
done
|
||||
|
||||
|
@ -136,7 +151,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
# File completion for directories only
|
||||
local subdir
|
||||
# Use printf to strip any trailing newline
|
||||
subdir=$(printf "%%s" "${out[0]}")
|
||||
subdir=$(printf "%%s" "${out}")
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
__%[1]s_handle_subdirs_in_dir_flag "$subdir"
|
||||
|
@ -147,7 +162,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
else
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${out[*]}" -- "$cur")
|
||||
done < <(compgen -W "${out}" -- "$cur")
|
||||
fi
|
||||
}
|
||||
|
||||
|
@ -383,11 +398,11 @@ __%[1]s_handle_word()
|
|||
|
||||
`, name, ShellCompNoDescRequestCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func writePostscript(buf io.StringWriter, name string) {
|
||||
name = strings.Replace(name, ":", "__", -1)
|
||||
name = strings.ReplaceAll(name, ":", "__")
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`{
|
||||
local cur prev words cword split
|
||||
|
@ -517,7 +532,7 @@ func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
|
|||
}
|
||||
}
|
||||
|
||||
// Setup annotations for go completions for registered flags
|
||||
// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags
|
||||
func prepareCustomAnnotationsForFlags(cmd *Command) {
|
||||
flagCompletionMutex.RLock()
|
||||
defer flagCompletionMutex.RUnlock()
|
||||
|
@ -582,19 +597,16 @@ func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
|
|||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
for key := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
if flag.Value.Type() != "bool" {
|
||||
format += "="
|
||||
}
|
||||
format += cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
|
||||
if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok {
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
if flag.Value.Type() != "bool" {
|
||||
format += "="
|
||||
}
|
||||
format += cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
|
||||
|
||||
if len(flag.Shorthand) > 0 {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
|
||||
}
|
||||
if len(flag.Shorthand) > 0 {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
@ -606,7 +618,7 @@ func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
|
|||
for _, value := range cmd.ValidArgs {
|
||||
// Remove any description that may be included following a tab character.
|
||||
// Descriptions are not supported by bash completion.
|
||||
value = strings.Split(value, "\t")[0]
|
||||
value = strings.SplitN(value, "\t", 2)[0]
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
|
||||
}
|
||||
if cmd.ValidArgsFunction != nil {
|
||||
|
@ -645,8 +657,8 @@ func gen(buf io.StringWriter, cmd *Command) {
|
|||
gen(buf, c)
|
||||
}
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.Replace(commandName, " ", "_", -1)
|
||||
commandName = strings.Replace(commandName, ":", "__", -1)
|
||||
commandName = strings.ReplaceAll(commandName, " ", "_")
|
||||
commandName = strings.ReplaceAll(commandName, ":", "__")
|
||||
|
||||
if cmd.Root() == cmd {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))
|
||||
|
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -24,7 +38,7 @@ func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
|
|||
|
||||
__%[1]s_debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
@ -43,7 +57,7 @@ __%[1]s_get_completion_results() {
|
|||
local requestComp lastParam lastChar args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
|
||||
args=("${words[@]:1}")
|
||||
requestComp="${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
|
@ -51,7 +65,7 @@ __%[1]s_get_completion_results() {
|
|||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
__%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"
|
||||
|
||||
if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
|
||||
if [[ -z ${cur} && ${lastChar} != = ]]; then
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go method.
|
||||
__%[1]s_debug "Adding extra empty parameter"
|
||||
|
@ -61,7 +75,7 @@ __%[1]s_get_completion_results() {
|
|||
# When completing a flag with an = (e.g., %[1]s -n=<TAB>)
|
||||
# bash focuses on the part after the =, so we need to remove
|
||||
# the flag part from $cur
|
||||
if [[ "${cur}" == -*=* ]]; then
|
||||
if [[ ${cur} == -*=* ]]; then
|
||||
cur="${cur#*=}"
|
||||
fi
|
||||
|
||||
|
@ -73,12 +87,12 @@ __%[1]s_get_completion_results() {
|
|||
directive=${out##*:}
|
||||
# Remove the directive
|
||||
out=${out%%:*}
|
||||
if [ "${directive}" = "${out}" ]; then
|
||||
if [[ ${directive} == "${out}" ]]; then
|
||||
# There is not directive specified
|
||||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "The completion directive is: ${directive}"
|
||||
__%[1]s_debug "The completions are: ${out[*]}"
|
||||
__%[1]s_debug "The completions are: ${out}"
|
||||
}
|
||||
|
||||
__%[1]s_process_completion_results() {
|
||||
|
@ -87,22 +101,36 @@ __%[1]s_process_completion_results() {
|
|||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
local shellCompDirectiveKeepOrder=%[8]d
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
if (((directive & shellCompDirectiveError) != 0)); then
|
||||
# Error code. No completion.
|
||||
__%[1]s_debug "Received error from custom completion go code"
|
||||
return
|
||||
else
|
||||
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
if (((directive & shellCompDirectiveNoSpace) != 0)); then
|
||||
if [[ $(type -t compopt) == builtin ]]; then
|
||||
__%[1]s_debug "Activating no space"
|
||||
compopt -o nospace
|
||||
else
|
||||
__%[1]s_debug "No space directive not supported in this version of bash"
|
||||
fi
|
||||
fi
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
if (((directive & shellCompDirectiveKeepOrder) != 0)); then
|
||||
if [[ $(type -t compopt) == builtin ]]; then
|
||||
# no sort isn't supported for bash less than < 4.4
|
||||
if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then
|
||||
__%[1]s_debug "No sort directive not supported in this version of bash"
|
||||
else
|
||||
__%[1]s_debug "Activating keep order"
|
||||
compopt -o nosort
|
||||
fi
|
||||
else
|
||||
__%[1]s_debug "No sort directive not supported in this version of bash"
|
||||
fi
|
||||
fi
|
||||
if (((directive & shellCompDirectiveNoFileComp) != 0)); then
|
||||
if [[ $(type -t compopt) == builtin ]]; then
|
||||
__%[1]s_debug "Activating no file completion"
|
||||
compopt +o default
|
||||
else
|
||||
|
@ -111,26 +139,30 @@ __%[1]s_process_completion_results() {
|
|||
fi
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local fullFilter filter filteringCmd
|
||||
# Separate activeHelp from normal completions
|
||||
local completions=()
|
||||
local activeHelp=()
|
||||
__%[1]s_extract_activeHelp
|
||||
|
||||
# Do not use quotes around the $out variable or else newline
|
||||
if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
|
||||
# File extension filtering
|
||||
local fullFilter="" filter filteringCmd
|
||||
|
||||
# Do not use quotes around the $completions variable or else newline
|
||||
# characters will be kept.
|
||||
for filter in ${out[*]}; do
|
||||
for filter in ${completions[*]}; do
|
||||
fullFilter+="$filter|"
|
||||
done
|
||||
|
||||
filteringCmd="_filedir $fullFilter"
|
||||
__%[1]s_debug "File filtering command: $filteringCmd"
|
||||
$filteringCmd
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
elif (((directive & shellCompDirectiveFilterDirs) != 0)); then
|
||||
# File completion for directories only
|
||||
|
||||
# Use printf to strip any trailing newline
|
||||
local subdir
|
||||
subdir=$(printf "%%s" "${out[0]}")
|
||||
if [ -n "$subdir" ]; then
|
||||
subdir=${completions[0]}
|
||||
if [[ -n $subdir ]]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
|
||||
else
|
||||
|
@ -143,6 +175,96 @@ __%[1]s_process_completion_results() {
|
|||
|
||||
__%[1]s_handle_special_char "$cur" :
|
||||
__%[1]s_handle_special_char "$cur" =
|
||||
|
||||
# Print the activeHelp statements before we finish
|
||||
__%[1]s_handle_activeHelp
|
||||
}
|
||||
|
||||
__%[1]s_handle_activeHelp() {
|
||||
# Print the activeHelp statements
|
||||
if ((${#activeHelp[*]} != 0)); then
|
||||
if [ -z $COMP_TYPE ]; then
|
||||
# Bash v3 does not set the COMP_TYPE variable.
|
||||
printf "\n";
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
printf "\n"
|
||||
__%[1]s_reprint_commandLine
|
||||
return
|
||||
fi
|
||||
|
||||
# Only print ActiveHelp on the second TAB press
|
||||
if [ $COMP_TYPE -eq 63 ]; then
|
||||
printf "\n"
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
|
||||
if ((${#COMPREPLY[*]} == 0)); then
|
||||
# When there are no completion choices from the program, file completion
|
||||
# may kick in if the program has not disabled it; in such a case, we want
|
||||
# to know if any files will match what the user typed, so that we know if
|
||||
# there will be completions presented, so that we know how to handle ActiveHelp.
|
||||
# To find out, we actually trigger the file completion ourselves;
|
||||
# the call to _filedir will fill COMPREPLY if files match.
|
||||
if (((directive & shellCompDirectiveNoFileComp) == 0)); then
|
||||
__%[1]s_debug "Listing files"
|
||||
_filedir
|
||||
fi
|
||||
fi
|
||||
|
||||
if ((${#COMPREPLY[*]} != 0)); then
|
||||
# If there are completion choices to be shown, print a delimiter.
|
||||
# Re-printing the command-line will automatically be done
|
||||
# by the shell when it prints the completion choices.
|
||||
printf -- "--"
|
||||
else
|
||||
# When there are no completion choices at all, we need
|
||||
# to re-print the command-line since the shell will
|
||||
# not be doing it itself.
|
||||
__%[1]s_reprint_commandLine
|
||||
fi
|
||||
elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then
|
||||
# For completion type: menu-complete/menu-complete-backward and insert-completions
|
||||
# the completions are immediately inserted into the command-line, so we first
|
||||
# print the activeHelp message and reprint the command-line since the shell won't.
|
||||
printf "\n"
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
|
||||
__%[1]s_reprint_commandLine
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_reprint_commandLine() {
|
||||
# The prompt format is only available from bash 4.4.
|
||||
# We test if it is available before using it.
|
||||
if (x=${PS1@P}) 2> /dev/null; then
|
||||
printf "%%s" "${PS1@P}${COMP_LINE[@]}"
|
||||
else
|
||||
# Can't print the prompt. Just print the
|
||||
# text the user had typed, it is workable enough.
|
||||
printf "%%s" "${COMP_LINE[@]}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Separate activeHelp lines from real completions.
|
||||
# Fills the $activeHelp and $completions arrays.
|
||||
__%[1]s_extract_activeHelp() {
|
||||
local activeHelpMarker="%[9]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
[[ -z $comp ]] && continue
|
||||
|
||||
if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
|
||||
comp=${comp:endIndex}
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
if [[ -n $comp ]]; then
|
||||
activeHelp+=("$comp")
|
||||
fi
|
||||
else
|
||||
# Not an activeHelp line but a normal completion
|
||||
completions+=("$comp")
|
||||
fi
|
||||
done <<<"${out}"
|
||||
}
|
||||
|
||||
__%[1]s_handle_completion_types() {
|
||||
|
@ -154,17 +276,21 @@ __%[1]s_handle_completion_types() {
|
|||
# If the user requested inserting one completion at a time, or all
|
||||
# completions at once on the command-line we must remove the descriptions.
|
||||
# https://github.com/spf13/cobra/issues/1508
|
||||
local tab comp
|
||||
tab=$(printf '\t')
|
||||
while IFS='' read -r comp; do
|
||||
# Strip any description
|
||||
comp=${comp%%%%$tab*}
|
||||
# Only consider the completions that match
|
||||
comp=$(compgen -W "$comp" -- "$cur")
|
||||
if [ -n "$comp" ]; then
|
||||
COMPREPLY+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
|
||||
# If there are no completions, we don't need to do anything
|
||||
(( ${#completions[@]} == 0 )) && return 0
|
||||
|
||||
local tab=$'\t'
|
||||
|
||||
# Strip any description and escape the completion to handled special characters
|
||||
IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}")
|
||||
|
||||
# Only consider the completions that match
|
||||
IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}")
|
||||
|
||||
# compgen looses the escaping so we need to escape all completions again since they will
|
||||
# all be inserted on the command-line.
|
||||
IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}")
|
||||
;;
|
||||
|
||||
*)
|
||||
|
@ -175,44 +301,67 @@ __%[1]s_handle_completion_types() {
|
|||
}
|
||||
|
||||
__%[1]s_handle_standard_completion_case() {
|
||||
local tab comp
|
||||
tab=$(printf '\t')
|
||||
local tab=$'\t'
|
||||
|
||||
# If there are no completions, we don't need to do anything
|
||||
(( ${#completions[@]} == 0 )) && return 0
|
||||
|
||||
# Short circuit to optimize if we don't have descriptions
|
||||
if [[ "${completions[*]}" != *$tab* ]]; then
|
||||
# First, escape the completions to handle special characters
|
||||
IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}")
|
||||
# Only consider the completions that match what the user typed
|
||||
IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}")
|
||||
|
||||
# compgen looses the escaping so, if there is only a single completion, we need to
|
||||
# escape it again because it will be inserted on the command-line. If there are multiple
|
||||
# completions, we don't want to escape them because they will be printed in a list
|
||||
# and we don't want to show escape characters in that list.
|
||||
if (( ${#COMPREPLY[@]} == 1 )); then
|
||||
COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}")
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
local longest=0
|
||||
local compline
|
||||
# Look for the longest completion so that we can format things nicely
|
||||
while IFS='' read -r comp; do
|
||||
# Strip any description before checking the length
|
||||
comp=${comp%%%%$tab*}
|
||||
while IFS='' read -r compline; do
|
||||
[[ -z $compline ]] && continue
|
||||
|
||||
# Before checking if the completion matches what the user typed,
|
||||
# we need to strip any description and escape the completion to handle special
|
||||
# characters because those escape characters are part of what the user typed.
|
||||
# Don't call "printf" in a sub-shell because it will be much slower
|
||||
# since we are in a loop.
|
||||
printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}")
|
||||
|
||||
# Only consider the completions that match
|
||||
comp=$(compgen -W "$comp" -- "$cur")
|
||||
[[ $comp == "$cur"* ]] || continue
|
||||
|
||||
# The completions matches. Add it to the list of full completions including
|
||||
# its description. We don't escape the completion because it may get printed
|
||||
# in a list if there are more than one and we don't want show escape characters
|
||||
# in that list.
|
||||
COMPREPLY+=("$compline")
|
||||
|
||||
# Strip any description before checking the length, and again, don't escape
|
||||
# the completion because this length is only used when printing the completions
|
||||
# in a list and we don't want show escape characters in that list.
|
||||
comp=${compline%%%%$tab*}
|
||||
if ((${#comp}>longest)); then
|
||||
longest=${#comp}
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
|
||||
local completions=()
|
||||
while IFS='' read -r comp; do
|
||||
if [ -z "$comp" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
__%[1]s_debug "Original comp: $comp"
|
||||
comp="$(__%[1]s_format_comp_descriptions "$comp" "$longest")"
|
||||
__%[1]s_debug "Final comp: $comp"
|
||||
completions+=("$comp")
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${completions[*]}" -- "$cur")
|
||||
|
||||
# If there is a single completion left, remove the description text
|
||||
if [ ${#COMPREPLY[*]} -eq 1 ]; then
|
||||
# If there is a single completion left, remove the description text and escape any special characters
|
||||
if ((${#COMPREPLY[*]} == 1)); then
|
||||
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
|
||||
comp="${COMPREPLY[0]%%%% *}"
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
|
||||
COMPREPLY=()
|
||||
COMPREPLY+=("$comp")
|
||||
COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}")
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}"
|
||||
else
|
||||
# Format the descriptions
|
||||
__%[1]s_format_comp_descriptions $longest
|
||||
fi
|
||||
}
|
||||
|
||||
|
@ -223,53 +372,56 @@ __%[1]s_handle_special_char()
|
|||
if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
|
||||
local word=${comp%%"${comp##*${char}}"}
|
||||
local idx=${#COMPREPLY[*]}
|
||||
while [[ $((--idx)) -ge 0 ]]; do
|
||||
COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"}
|
||||
while ((--idx >= 0)); do
|
||||
COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_format_comp_descriptions()
|
||||
{
|
||||
local tab
|
||||
tab=$(printf '\t')
|
||||
local comp="$1"
|
||||
local longest=$2
|
||||
local tab=$'\t'
|
||||
local comp desc maxdesclength
|
||||
local longest=$1
|
||||
|
||||
# Properly format the description string which follows a tab character if there is one
|
||||
if [[ "$comp" == *$tab* ]]; then
|
||||
desc=${comp#*$tab}
|
||||
comp=${comp%%%%$tab*}
|
||||
local i ci
|
||||
for ci in ${!COMPREPLY[*]}; do
|
||||
comp=${COMPREPLY[ci]}
|
||||
# Properly format the description string which follows a tab character if there is one
|
||||
if [[ "$comp" == *$tab* ]]; then
|
||||
__%[1]s_debug "Original comp: $comp"
|
||||
desc=${comp#*$tab}
|
||||
comp=${comp%%%%$tab*}
|
||||
|
||||
# $COLUMNS stores the current shell width.
|
||||
# Remove an extra 4 because we add 2 spaces and 2 parentheses.
|
||||
maxdesclength=$(( COLUMNS - longest - 4 ))
|
||||
# $COLUMNS stores the current shell width.
|
||||
# Remove an extra 4 because we add 2 spaces and 2 parentheses.
|
||||
maxdesclength=$(( COLUMNS - longest - 4 ))
|
||||
|
||||
# Make sure we can fit a description of at least 8 characters
|
||||
# if we are to align the descriptions.
|
||||
if [[ $maxdesclength -gt 8 ]]; then
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
for ((i = ${#comp} ; i < longest ; i++)); do
|
||||
comp+=" "
|
||||
done
|
||||
else
|
||||
# Don't pad the descriptions so we can fit more text after the completion
|
||||
maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
|
||||
fi
|
||||
|
||||
# If there is enough space for any description text,
|
||||
# truncate the descriptions that are too long for the shell width
|
||||
if [ $maxdesclength -gt 0 ]; then
|
||||
if [ ${#desc} -gt $maxdesclength ]; then
|
||||
desc=${desc:0:$(( maxdesclength - 1 ))}
|
||||
desc+="…"
|
||||
# Make sure we can fit a description of at least 8 characters
|
||||
# if we are to align the descriptions.
|
||||
if ((maxdesclength > 8)); then
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
for ((i = ${#comp} ; i < longest ; i++)); do
|
||||
comp+=" "
|
||||
done
|
||||
else
|
||||
# Don't pad the descriptions so we can fit more text after the completion
|
||||
maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
|
||||
fi
|
||||
comp+=" ($desc)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Must use printf to escape all special characters
|
||||
printf "%%q" "${comp}"
|
||||
# If there is enough space for any description text,
|
||||
# truncate the descriptions that are too long for the shell width
|
||||
if ((maxdesclength > 0)); then
|
||||
if ((${#desc} > maxdesclength)); then
|
||||
desc=${desc:0:$(( maxdesclength - 1 ))}
|
||||
desc+="…"
|
||||
fi
|
||||
comp+=" ($desc)"
|
||||
fi
|
||||
COMPREPLY[ci]=$comp
|
||||
__%[1]s_debug "Final comp: $comp"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
__start_%[1]s()
|
||||
|
@ -281,9 +433,9 @@ __start_%[1]s()
|
|||
# Call _init_completion from the bash-completion package
|
||||
# to prepare the arguments properly
|
||||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion -n "=:" || return
|
||||
_init_completion -n =: || return
|
||||
else
|
||||
__%[1]s_init_completion -n "=:" || return
|
||||
__%[1]s_init_completion -n =: || return
|
||||
fi
|
||||
|
||||
__%[1]s_debug
|
||||
|
@ -310,7 +462,8 @@ fi
|
|||
# ex: ts=4 sw=4 et filetype=sh
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
||||
// GenBashCompletionFileV2 generates Bash completion version 2.
|
||||
|
|
33
bash_completionsV2_test.go
Normal file
33
bash_completionsV2_test.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
// Copyright 2013-2023 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))
|
||||
}
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -261,3 +275,15 @@ func TestBashCompletionTraverseChildren(t *testing.T) {
|
|||
checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`)
|
||||
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))
|
||||
}
|
||||
|
|
54
cobra.go
54
cobra.go
|
@ -1,9 +1,10 @@
|
|||
// Copyright © 2013 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2013-2023 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
|
||||
//
|
||||
// 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,
|
||||
|
@ -39,15 +40,30 @@ var templateFuncs = template.FuncMap{
|
|||
}
|
||||
|
||||
var initializers []func()
|
||||
var finalizers []func()
|
||||
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
const (
|
||||
defaultPrefixMatching = false
|
||||
defaultCommandSorting = true
|
||||
defaultCaseInsensitive = false
|
||||
defaultTraverseRunHooks = false
|
||||
)
|
||||
|
||||
// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = false
|
||||
var EnablePrefixMatching = defaultPrefixMatching
|
||||
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// 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
|
||||
|
||||
// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.
|
||||
// By default this is disabled, which means only the first run hook to be found is executed.
|
||||
var EnableTraverseRunHooks = defaultTraverseRunHooks
|
||||
|
||||
// MousetrapHelpText enables an information splash screen on Windows
|
||||
// if the CLI is started from explorer.exe.
|
||||
|
@ -84,6 +100,12 @@ func OnInitialize(y ...func()) {
|
|||
initializers = append(initializers, y...)
|
||||
}
|
||||
|
||||
// OnFinalize sets the passed functions to be run when each command's
|
||||
// Execute method is terminated.
|
||||
func OnFinalize(y ...func()) {
|
||||
finalizers = append(finalizers, y...)
|
||||
}
|
||||
|
||||
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
|
@ -150,16 +172,20 @@ func appendIfNotPresent(s, stringToAppend string) string {
|
|||
|
||||
// rpad adds padding to the right of a string.
|
||||
func rpad(s string, padding int) string {
|
||||
template := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(template, s)
|
||||
formattedString := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(formattedString, s)
|
||||
}
|
||||
|
||||
// tmpl executes the given template text on data, writing the result to w.
|
||||
func tmpl(w io.Writer, text string, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(templateFuncs)
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
func tmpl(text string) *tmplFunc {
|
||||
return &tmplFunc{
|
||||
tmpl: text,
|
||||
fn: func(w io.Writer, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(templateFuncs)
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
|
@ -171,8 +197,6 @@ func ld(s, t string, ignoreCase bool) int {
|
|||
d := make([][]int, len(s)+1)
|
||||
for i := range d {
|
||||
d[i] = make([]int, len(t)+1)
|
||||
}
|
||||
for i := range d {
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := range d[0] {
|
||||
|
|
273
cobra_test.go
273
cobra_test.go
|
@ -1,6 +1,25 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"text/template"
|
||||
)
|
||||
|
@ -26,3 +45,257 @@ func TestAddTemplateFunctions(t *testing.T) {
|
|||
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLevenshteinDistance(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
s string
|
||||
t string
|
||||
ignoreCase bool
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "Equal strings (case-sensitive)",
|
||||
s: "hello",
|
||||
t: "hello",
|
||||
ignoreCase: false,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "Equal strings (case-insensitive)",
|
||||
s: "Hello",
|
||||
t: "hello",
|
||||
ignoreCase: true,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "Different strings (case-sensitive)",
|
||||
s: "kitten",
|
||||
t: "sitting",
|
||||
ignoreCase: false,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "Different strings (case-insensitive)",
|
||||
s: "Kitten",
|
||||
t: "Sitting",
|
||||
ignoreCase: true,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "Empty strings",
|
||||
s: "",
|
||||
t: "",
|
||||
ignoreCase: false,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "One empty string",
|
||||
s: "abc",
|
||||
t: "",
|
||||
ignoreCase: false,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "Both empty strings",
|
||||
s: "",
|
||||
t: "",
|
||||
ignoreCase: true,
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Act
|
||||
got := ld(tt.s, tt.t, tt.ignoreCase)
|
||||
|
||||
// Assert
|
||||
if got != tt.expected {
|
||||
t.Errorf("Expected ld: %v\nGot: %v", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringInSlice(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
a string
|
||||
list []string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "String in slice (case-sensitive)",
|
||||
a: "apple",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "String not in slice (case-sensitive)",
|
||||
a: "pear",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "String in slice (case-insensitive)",
|
||||
a: "APPLE",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Empty slice",
|
||||
a: "apple",
|
||||
list: []string{},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Empty string",
|
||||
a: "",
|
||||
list: []string{"orange", "banana", "apple", "grape"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Empty strings match",
|
||||
a: "",
|
||||
list: []string{"orange", ""},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Empty string in empty slice",
|
||||
a: "",
|
||||
list: []string{},
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Act
|
||||
got := stringInSlice(tt.a, tt.list)
|
||||
|
||||
// Assert
|
||||
if got != tt.expected {
|
||||
t.Errorf("Expected stringInSlice: %v\nGot: %v", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRpad(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inputString string
|
||||
padding int
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "Padding required",
|
||||
inputString: "Hello",
|
||||
padding: 10,
|
||||
expected: "Hello ",
|
||||
},
|
||||
{
|
||||
name: "No padding required",
|
||||
inputString: "World",
|
||||
padding: 5,
|
||||
expected: "World",
|
||||
},
|
||||
{
|
||||
name: "Empty string",
|
||||
inputString: "",
|
||||
padding: 8,
|
||||
expected: " ",
|
||||
},
|
||||
{
|
||||
name: "Zero padding",
|
||||
inputString: "cobra",
|
||||
padding: 0,
|
||||
expected: "cobra",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Act
|
||||
got := rpad(tt.inputString, tt.padding)
|
||||
|
||||
// Assert
|
||||
if got != tt.expected {
|
||||
t.Errorf("Expected rpad: %v\nGot: %v", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeadcodeElimination checks that a simple program using cobra in its
|
||||
// default configuration is linked taking full advantage of the linker's
|
||||
// deadcode elimination step.
|
||||
//
|
||||
// If reflect.Value.MethodByName/reflect.Value.Method are reachable the
|
||||
// linker will not always be able to prove that exported methods are
|
||||
// unreachable, making deadcode elimination less effective. Using
|
||||
// text/template and html/template makes reflect.Value.MethodByName
|
||||
// reachable.
|
||||
// Since cobra can use text/template templates this test checks that in its
|
||||
// default configuration that code path can be proven to be unreachable by
|
||||
// the linker.
|
||||
//
|
||||
// See also: https://github.com/spf13/cobra/pull/1956
|
||||
func TestDeadcodeElimination(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("go tool nm fails on windows")
|
||||
}
|
||||
|
||||
// check that a simple program using cobra in its default configuration is
|
||||
// linked with deadcode elimination enabled.
|
||||
const (
|
||||
dirname = "test_deadcode"
|
||||
progname = "test_deadcode_elimination"
|
||||
)
|
||||
_ = os.Mkdir(dirname, 0770)
|
||||
defer os.RemoveAll(dirname)
|
||||
filename := filepath.Join(dirname, progname+".go")
|
||||
err := os.WriteFile(filename, []byte(`package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Version: "1.0",
|
||||
Use: "example_program",
|
||||
Short: "example_program - test fixture to check that deadcode elimination is allowed",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("hello world")
|
||||
},
|
||||
Aliases: []string{"alias1", "alias2"},
|
||||
Example: "stringer --help",
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
`), 0600)
|
||||
if err != nil {
|
||||
t.Fatalf("could not write test program: %v", err)
|
||||
}
|
||||
buf, err := exec.Command("go", "build", filename).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("could not compile test program: %s", string(buf))
|
||||
}
|
||||
defer os.Remove(progname)
|
||||
buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("could not run go tool nm: %v", err)
|
||||
}
|
||||
if strings.Contains(string(buf), "MethodByName") {
|
||||
t.Error("compiled programs contains MethodByName symbol")
|
||||
}
|
||||
}
|
||||
|
|
602
command.go
602
command.go
File diff suppressed because it is too large
Load diff
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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
|
||||
// +build !windows
|
||||
|
||||
|
|
1042
command_test.go
1042
command_test.go
File diff suppressed because it is too large
Load diff
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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
|
||||
// +build windows
|
||||
|
||||
|
|
266
completions.go
266
completions.go
|
@ -1,8 +1,24 @@
|
|||
// Copyright 2013-2023 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"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
|
@ -19,7 +35,7 @@ const (
|
|||
)
|
||||
|
||||
// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.
|
||||
var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
|
||||
var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{}
|
||||
|
||||
// lock for reading and writing from flagCompletionFunctions
|
||||
var flagCompletionMutex = &sync.RWMutex{}
|
||||
|
@ -63,6 +79,10 @@ const (
|
|||
// obtain the same behavior but only for flags.
|
||||
ShellCompDirectiveFilterDirs
|
||||
|
||||
// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
|
||||
// in which the completions are provided
|
||||
ShellCompDirectiveKeepOrder
|
||||
|
||||
// ===========================================================================
|
||||
|
||||
// All directives using iota should be above this one.
|
||||
|
@ -97,14 +117,50 @@ type CompletionOptions struct {
|
|||
HiddenDefaultCmd bool
|
||||
}
|
||||
|
||||
// Completion is a string that can be used for completions
|
||||
//
|
||||
// two formats are supported:
|
||||
// - the completion choice
|
||||
// - the completion choice with a textual description (separated by a TAB).
|
||||
//
|
||||
// [CompletionWithDesc] can be used to create a completion string with a textual description.
|
||||
//
|
||||
// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used.
|
||||
type Completion = string
|
||||
|
||||
// CompletionFunc is a function that provides completion results.
|
||||
type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)
|
||||
|
||||
// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.
|
||||
func CompletionWithDesc(choice string, description string) Completion {
|
||||
return choice + "\t" + description
|
||||
}
|
||||
|
||||
// NoFileCompletions can be used to disable file completion for commands that should
|
||||
// not trigger file completions.
|
||||
func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
//
|
||||
// This method satisfies [CompletionFunc].
|
||||
// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].
|
||||
func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {
|
||||
return nil, ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
||||
// FixedCompletions can be used to create a completion function which always
|
||||
// returns the same results.
|
||||
//
|
||||
// This method returns a function that satisfies [CompletionFunc]
|
||||
// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].
|
||||
func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc {
|
||||
return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {
|
||||
return choices, directive
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
|
||||
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
|
||||
//
|
||||
// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions],
|
||||
// or you can define your own.
|
||||
func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error {
|
||||
flag := c.Flag(flagName)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
|
||||
|
@ -119,6 +175,20 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman
|
|||
return nil
|
||||
}
|
||||
|
||||
// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.
|
||||
func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) {
|
||||
flag := c.Flag(flagName)
|
||||
if flag == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
flagCompletionMutex.RLock()
|
||||
defer flagCompletionMutex.RUnlock()
|
||||
|
||||
completionFunc, exists := flagCompletionFunctions[flag]
|
||||
return completionFunc, exists
|
||||
}
|
||||
|
||||
// Returns a string listing the different directive enabled in the specified parameter
|
||||
func (d ShellCompDirective) string() string {
|
||||
var directives []string
|
||||
|
@ -137,6 +207,9 @@ func (d ShellCompDirective) string() string {
|
|||
if d&ShellCompDirectiveFilterDirs != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveFilterDirs")
|
||||
}
|
||||
if d&ShellCompDirectiveKeepOrder != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveKeepOrder")
|
||||
}
|
||||
if len(directives) == 0 {
|
||||
directives = append(directives, "ShellCompDirectiveDefault")
|
||||
}
|
||||
|
@ -147,7 +220,7 @@ func (d ShellCompDirective) string() string {
|
|||
return strings.Join(directives, ", ")
|
||||
}
|
||||
|
||||
// Adds a special hidden command that can be used to request custom completions.
|
||||
// initCompleteCmd adds a special hidden command that can be used to request custom completions.
|
||||
func (c *Command) initCompleteCmd(args []string) {
|
||||
completeCmd := &Command{
|
||||
Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
|
||||
|
@ -168,18 +241,29 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
// 2- Even without completions, we need to print the directive
|
||||
}
|
||||
|
||||
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
|
||||
noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd
|
||||
if !noDescriptions {
|
||||
if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {
|
||||
noDescriptions = !doDescriptions
|
||||
}
|
||||
}
|
||||
noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable
|
||||
out := finalCmd.OutOrStdout()
|
||||
for _, comp := range completions {
|
||||
if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {
|
||||
// Remove all activeHelp entries if it's disabled.
|
||||
continue
|
||||
}
|
||||
if noDescriptions {
|
||||
// Remove any description that may be included following a tab character.
|
||||
comp = strings.Split(comp, "\t")[0]
|
||||
comp = strings.SplitN(comp, "\t", 2)[0]
|
||||
}
|
||||
|
||||
// Make sure we only write the first line to the output.
|
||||
// This is needed if a description contains a linebreak.
|
||||
// Otherwise the shell scripts will interpret the other lines as new flags
|
||||
// and could therefore provide a wrong completion.
|
||||
comp = strings.Split(comp, "\n")[0]
|
||||
comp = strings.SplitN(comp, "\n", 2)[0]
|
||||
|
||||
// Finally trim the completion. This is especially important to get rid
|
||||
// of a trailing tab when there are no description following it.
|
||||
|
@ -188,14 +272,14 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
// although there is no description).
|
||||
comp = strings.TrimSpace(comp)
|
||||
|
||||
// Print each possible completion to stdout for the completion script to consume.
|
||||
fmt.Fprintln(finalCmd.OutOrStdout(), comp)
|
||||
// Print each possible completion to the output for the completion script to consume.
|
||||
fmt.Fprintln(out, comp)
|
||||
}
|
||||
|
||||
// As the last printout, print the completion directive for the completion script to parse.
|
||||
// The directive integer must be that last character following a single colon (:).
|
||||
// The completion script expects :<directive>
|
||||
fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
|
||||
fmt.Fprintf(out, ":%d\n", directive)
|
||||
|
||||
// Print some helpful info to stderr for the user to understand.
|
||||
// Output from stderr must be ignored by the completion script.
|
||||
|
@ -214,7 +298,15 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
}
|
||||
}
|
||||
|
||||
func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
|
||||
// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect
|
||||
// flags that accept multiple values and therefore can provide completion
|
||||
// multiple times.
|
||||
type SliceValue interface {
|
||||
// GetSlice returns the flag value list as an array of strings.
|
||||
GetSlice() []string
|
||||
}
|
||||
|
||||
func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) {
|
||||
// The last argument, which is not completely typed by the user,
|
||||
// should not be part of the list of arguments
|
||||
toComplete := args[len(args)-1]
|
||||
|
@ -242,10 +334,20 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
}
|
||||
if err != nil {
|
||||
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
|
||||
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
|
||||
return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)
|
||||
}
|
||||
finalCmd.ctx = c.ctx
|
||||
|
||||
// These flags are normally added when `execute()` is called on `finalCmd`,
|
||||
// however, when doing completion, we don't call `finalCmd.execute()`.
|
||||
// Let's add the --help and --version flag ourselves but only if the finalCmd
|
||||
// has not disabled flag parsing; if flag parsing is disabled, it is up to the
|
||||
// finalCmd itself to handle the completion of *all* flags.
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
finalCmd.InitDefaultHelpFlag()
|
||||
finalCmd.InitDefaultVersionFlag()
|
||||
}
|
||||
|
||||
// Check if we are doing flag value completion before parsing the flags.
|
||||
// This is important because if we are completing a flag value, we need to also
|
||||
// remove the flag name argument from the list of finalArgs or else the parsing
|
||||
|
@ -262,7 +364,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
|
||||
// Parse the flags early so we can check if required flags are set
|
||||
if err = finalCmd.ParseFlags(finalArgs); err != nil {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
}
|
||||
|
||||
realArgCount := finalCmd.Flags().NArg()
|
||||
|
@ -274,10 +376,16 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
if flagErr != nil {
|
||||
// If error type is flagCompError and we don't want flagCompletion we should ignore the error
|
||||
if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
// Look for the --help or --version flags. If they are present,
|
||||
// there should be no further completions.
|
||||
if helpOrVersionFlagPresent(finalCmd) {
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil
|
||||
}
|
||||
|
||||
// We only remove the flags from the arguments if DisableFlagParsing is not set.
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
|
@ -304,15 +412,18 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil
|
||||
}
|
||||
// Directory completion
|
||||
return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil
|
||||
return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil
|
||||
}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
var completions []Completion
|
||||
var directive ShellCompDirective
|
||||
|
||||
// Enforce flag groups before doing flag completions
|
||||
finalCmd.enforceFlagGroupsForCompletion()
|
||||
|
||||
// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;
|
||||
// doing this allows for completion of persistant 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.
|
||||
//
|
||||
// When doing completion of a flag name, as soon as an argument starts with
|
||||
// a '-' we know it is a flag. We cannot use isFlagArg() here as it requires
|
||||
|
@ -324,10 +435,14 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
// If we have not found any required flags, only then can we show regular flags
|
||||
if len(completions) == 0 {
|
||||
doCompleteFlags := func(flag *pflag.Flag) {
|
||||
if !flag.Changed ||
|
||||
_, acceptsMultiple := flag.Value.(SliceValue)
|
||||
acceptsMultiple = acceptsMultiple ||
|
||||
strings.Contains(flag.Value.Type(), "Slice") ||
|
||||
strings.Contains(flag.Value.Type(), "Array") {
|
||||
// If the flag is not already present, or if it can be specified multiple times (Array or Slice)
|
||||
strings.Contains(flag.Value.Type(), "Array") ||
|
||||
strings.HasPrefix(flag.Value.Type(), "stringTo")
|
||||
|
||||
if !flag.Changed || acceptsMultiple {
|
||||
// If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo)
|
||||
// we suggest it as a completion
|
||||
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
|
||||
}
|
||||
|
@ -339,6 +454,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
doCompleteFlags(flag)
|
||||
})
|
||||
// Try to complete non-inherited flags even if DisableFlagParsing==true.
|
||||
// This allows programs to tell Cobra about flags for completion even
|
||||
// if the actual parsing of flags is not done by Cobra.
|
||||
// For instance, Helm uses this to provide flag name completion for
|
||||
// some of its plugins.
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
doCompleteFlags(flag)
|
||||
})
|
||||
|
@ -382,7 +502,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
for _, subCmd := range finalCmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
|
||||
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
@ -427,7 +547,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
}
|
||||
|
||||
// Find the completion function for the flag or command
|
||||
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
var completionFn CompletionFunc
|
||||
if flag != nil && flagCompletion {
|
||||
flagCompletionMutex.RLock()
|
||||
completionFn = flagCompletionFunctions[flag]
|
||||
|
@ -438,7 +558,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
if completionFn != nil {
|
||||
// Go custom completion defined for this flag or command.
|
||||
// Call the registered completion function to get the completions.
|
||||
var comps []string
|
||||
var comps []Completion
|
||||
comps, directive = completionFn(finalCmd, finalArgs, toComplete)
|
||||
completions = append(completions, comps...)
|
||||
}
|
||||
|
@ -446,16 +566,28 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
||||
func helpOrVersionFlagPresent(cmd *Command) bool {
|
||||
if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&
|
||||
len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
|
||||
return true
|
||||
}
|
||||
if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil &&
|
||||
len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {
|
||||
if nonCompletableFlag(flag) {
|
||||
return []string{}
|
||||
return []Completion{}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
var completions []Completion
|
||||
flagName := "--" + flag.Name
|
||||
if strings.HasPrefix(flagName, toComplete) {
|
||||
// Flag without the =
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
completions = append(completions, CompletionWithDesc(flagName, flag.Usage))
|
||||
|
||||
// Why suggest both long forms: --flag and --flag= ?
|
||||
// This forces the user to *always* have to type either an = or a space after the flag name.
|
||||
|
@ -467,20 +599,20 @@ func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
|||
// if len(flag.NoOptDefVal) == 0 {
|
||||
// // Flag requires a value, so it can be suffixed with =
|
||||
// flagName += "="
|
||||
// completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
// completions = append(completions, CompletionWithDesc(flagName, flag.Usage))
|
||||
// }
|
||||
}
|
||||
|
||||
flagName = "-" + flag.Shorthand
|
||||
if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
completions = append(completions, CompletionWithDesc(flagName, flag.Usage))
|
||||
}
|
||||
|
||||
return completions
|
||||
}
|
||||
|
||||
func completeRequireFlags(finalCmd *Command, toComplete string) []string {
|
||||
var completions []string
|
||||
func completeRequireFlags(finalCmd *Command, toComplete string) []Completion {
|
||||
var completions []Completion
|
||||
|
||||
doCompleteRequiredFlags := func(flag *pflag.Flag) {
|
||||
if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {
|
||||
|
@ -590,13 +722,13 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
return flag, trimmedArgs, lastArg, nil
|
||||
}
|
||||
|
||||
// initDefaultCompletionCmd adds a default 'completion' command to c.
|
||||
// InitDefaultCompletionCmd adds a default 'completion' command to c.
|
||||
// This function will do nothing if any of the following is true:
|
||||
// 1- the feature has been explicitly disabled by the program,
|
||||
// 2- c has no subcommands (to avoid creating one),
|
||||
// 3- c already has a 'completion' command provided by the program.
|
||||
func (c *Command) initDefaultCompletionCmd() {
|
||||
if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
|
||||
func (c *Command) InitDefaultCompletionCmd(args ...string) {
|
||||
if c.CompletionOptions.DisableDefaultCmd {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -609,6 +741,16 @@ func (c *Command) initDefaultCompletionCmd() {
|
|||
|
||||
haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions
|
||||
|
||||
// Special case to know if there are sub-commands or not.
|
||||
hasSubCommands := false
|
||||
for _, cmd := range c.commands {
|
||||
if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName {
|
||||
// We found a real sub-command (not 'help' or '__complete')
|
||||
hasSubCommands = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
completionCmd := &Command{
|
||||
Use: compCmdName,
|
||||
Short: "Generate the autocompletion script for the specified shell",
|
||||
|
@ -618,9 +760,26 @@ See each sub-command's help for details on how to use the generated script.
|
|||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
Hidden: c.CompletionOptions.HiddenDefaultCmd,
|
||||
GroupID: c.completionCommandGroupID,
|
||||
}
|
||||
c.AddCommand(completionCmd)
|
||||
|
||||
if !hasSubCommands {
|
||||
// If the 'completion' command will be the only sub-command,
|
||||
// we only create it if it is actually being called.
|
||||
// This avoids breaking programs that would suddenly find themselves with
|
||||
// a subcommand, which would prevent them from accepting arguments.
|
||||
// We also create the 'completion' command if the user is triggering
|
||||
// shell completion for it (prog __complete completion '')
|
||||
subCmd, cmdArgs, err := c.Find(args)
|
||||
if err != nil || subCmd.Name() != compCmdName &&
|
||||
!(subCmd.Name() == ShellCompRequestCmd && len(cmdArgs) > 1 && cmdArgs[0] == compCmdName) {
|
||||
// The completion command is not being called or being completed so we remove it.
|
||||
c.RemoveCommand(completionCmd)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
out := c.OutOrStdout()
|
||||
noDesc := c.CompletionOptions.DisableDescriptions
|
||||
shortDesc := "Generate the autocompletion script for %s"
|
||||
|
@ -644,7 +803,7 @@ To load completions for every new session, execute once:
|
|||
|
||||
#### 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.
|
||||
`, c.Root().Name()),
|
||||
|
@ -669,6 +828,10 @@ to enable it. You can execute the following once:
|
|||
|
||||
echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
source <(%[1]s completion zsh)
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
#### Linux:
|
||||
|
@ -677,7 +840,7 @@ To load completions for every new session, execute once:
|
|||
|
||||
#### 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.
|
||||
`, c.Root().Name()),
|
||||
|
@ -809,3 +972,34 @@ func CompError(msg string) {
|
|||
func CompErrorln(msg string) {
|
||||
CompError(fmt.Sprintf("%s\n", msg))
|
||||
}
|
||||
|
||||
// These values should not be changed: users will be using them explicitly.
|
||||
const (
|
||||
configEnvVarGlobalPrefix = "COBRA"
|
||||
configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"
|
||||
)
|
||||
|
||||
var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
|
||||
|
||||
// configEnvVar returns the name of the program-specific configuration environment
|
||||
// variable. It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the
|
||||
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
func configEnvVar(name, suffix string) string {
|
||||
// This format should not be changed: users will be using it explicitly.
|
||||
v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))
|
||||
v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")
|
||||
return v
|
||||
}
|
||||
|
||||
// getEnvConfig returns the value of the configuration environment variable
|
||||
// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper
|
||||
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
// If the value is empty or not set, the value of the environment variable
|
||||
// COBRA_<SUFFIX> is returned instead.
|
||||
func getEnvConfig(cmd *Command, suffix string) string {
|
||||
v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))
|
||||
if v == "" {
|
||||
v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
|
1370
completions_test.go
1370
completions_test.go
File diff suppressed because it is too large
Load diff
|
@ -1,12 +0,0 @@
|
|||
# Documentation generation
|
||||
|
||||
- [Man page docs](./man_docs.md)
|
||||
- [Markdown docs](./md_docs.md)
|
||||
- [Rest docs](./rest_docs.md)
|
||||
- [Yaml docs](./yaml_docs.md)
|
||||
|
||||
## Options
|
||||
### `DisableAutoGenTag`
|
||||
You may set `cmd.DisableAutoGenTag = true`
|
||||
to _entirely_ remove the auto generated string "Auto generated by spf13/cobra..."
|
||||
from any documentation source.
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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
|
||||
|
||||
import (
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
// Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
// Copyright 2013-2023 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
|
||||
//
|
||||
// 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,
|
||||
|
@ -66,7 +67,7 @@ func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
|
|||
if opts.CommandSeparator != "" {
|
||||
separator = opts.CommandSeparator
|
||||
}
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
|
||||
basename := strings.ReplaceAll(cmd.CommandPath(), " ", separator)
|
||||
filename := filepath.Join(opts.Path, basename+"."+section)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
@ -116,7 +117,7 @@ func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
|
|||
|
||||
func fillHeader(header *GenManHeader, name string, disableAutoGen bool) error {
|
||||
if header.Title == "" {
|
||||
header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
|
||||
header.Title = strings.ToUpper(strings.ReplaceAll(name, " ", "\\-"))
|
||||
}
|
||||
if header.Section == "" {
|
||||
header.Section = "1"
|
||||
|
@ -132,7 +133,7 @@ func fillHeader(header *GenManHeader, name string, disableAutoGen bool) error {
|
|||
}
|
||||
header.Date = &now
|
||||
}
|
||||
header.date = (*header.Date).Format("Jan 2006")
|
||||
header.date = header.Date.Format("Jan 2006")
|
||||
if header.Source == "" && !disableAutoGen {
|
||||
header.Source = "Auto generated by spf13/cobra"
|
||||
}
|
||||
|
@ -203,7 +204,7 @@ func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
|
|||
cmd.InitDefaultHelpFlag()
|
||||
|
||||
// something like `rootcmd-subcmd1-subcmd2`
|
||||
dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
|
||||
dashCommandName := strings.ReplaceAll(cmd.CommandPath(), " ", "-")
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
|
@ -218,7 +219,7 @@ func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
|
|||
seealsos := make([]string, 0)
|
||||
if cmd.HasParent() {
|
||||
parentPath := cmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
dashParentPath := strings.ReplaceAll(parentPath, " ", "-")
|
||||
seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
|
||||
seealsos = append(seealsos, seealso)
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
|
|
|
@ -1,10 +1,23 @@
|
|||
// Copyright 2013-2023 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
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
@ -20,7 +33,7 @@ func assertNoErr(t *testing.T, e error) {
|
|||
}
|
||||
|
||||
func translate(in string) string {
|
||||
return strings.Replace(in, "-", "\\-", -1)
|
||||
return strings.ReplaceAll(in, "-", "\\-")
|
||||
}
|
||||
|
||||
func TestGenManDoc(t *testing.T) {
|
||||
|
@ -38,7 +51,7 @@ func TestGenManDoc(t *testing.T) {
|
|||
|
||||
// Make sure parent has - in CommandPath() in SEE ALSO:
|
||||
parentPath := echoCmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
dashParentPath := strings.ReplaceAll(parentPath, " ", "-")
|
||||
expected := translate(dashParentPath)
|
||||
expected = expected + "(" + header.Section + ")"
|
||||
checkStringContains(t, output, expected)
|
||||
|
@ -73,7 +86,7 @@ func TestGenManNoHiddenParents(t *testing.T) {
|
|||
|
||||
// Make sure parent has - in CommandPath() in SEE ALSO:
|
||||
parentPath := echoCmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
dashParentPath := strings.ReplaceAll(parentPath, " ", "-")
|
||||
expected := translate(dashParentPath)
|
||||
expected = expected + "(" + header.Section + ")"
|
||||
checkStringContains(t, output, expected)
|
||||
|
@ -128,15 +141,12 @@ func TestGenManSeeAlso(t *testing.T) {
|
|||
if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil {
|
||||
t.Fatalf("Couldn't find SEE ALSO section header: %v", err)
|
||||
}
|
||||
if err := assertNextLineEquals(scanner, ".PP"); err != nil {
|
||||
t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err)
|
||||
}
|
||||
if err := assertNextLineEquals(scanner, `\fBroot-bbb(1)\fP, \fBroot-ccc(1)\fP`); err != nil {
|
||||
t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
|
||||
func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
|
||||
c := &cobra.Command{}
|
||||
c.Flags().StringP("foo", "f", "default", "Foo flag")
|
||||
assertNoErr(t, c.Flags().MarkShorthandDeprecated("foo", "don't use it no more"))
|
||||
|
@ -154,7 +164,7 @@ func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
|
|||
func TestGenManTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
header := &GenManHeader{Section: "2"}
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-man-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
|
@ -205,7 +215,7 @@ func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
|
|||
}
|
||||
|
||||
func BenchmarkGenManToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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
|
||||
|
||||
import (
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
//Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
// Copyright 2013-2023 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
|
||||
//
|
||||
// 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,
|
||||
|
@ -26,6 +27,8 @@ import (
|
|||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const markdownExtension = ".md"
|
||||
|
||||
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(buf)
|
||||
|
@ -82,8 +85,8 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string)
|
|||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
link := pname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
link := pname + markdownExtension
|
||||
link = strings.ReplaceAll(link, " ", "_")
|
||||
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
|
@ -100,8 +103,8 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string)
|
|||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
link := cname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
link := cname + markdownExtension
|
||||
link = strings.ReplaceAll(link, " ", "_")
|
||||
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
|
||||
}
|
||||
buf.WriteString("\n")
|
||||
|
@ -125,7 +128,7 @@ func GenMarkdownTree(cmd *cobra.Command, dir string) error {
|
|||
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
|
||||
}
|
||||
|
||||
// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
|
||||
// GenMarkdownTreeCustom is the same as GenMarkdownTree, but
|
||||
// with custom filePrepender and linkHandler.
|
||||
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
|
@ -137,7 +140,7 @@ func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHa
|
|||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
|
||||
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + markdownExtension
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
|
|
@ -1,8 +1,21 @@
|
|||
// Copyright 2013-2023 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
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
@ -80,7 +93,7 @@ func TestGenMdNoTag(t *testing.T) {
|
|||
|
||||
func TestGenMdTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-md-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %v", err)
|
||||
}
|
||||
|
@ -96,7 +109,7 @@ func TestGenMdTree(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkGenMarkdownToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
//Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
// Copyright 2013-2023 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
|
||||
//
|
||||
// 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,
|
||||
|
@ -47,7 +48,7 @@ func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error
|
|||
return nil
|
||||
}
|
||||
|
||||
// linkHandler for default ReST hyperlink markup
|
||||
// defaultLinkHandler for default ReST hyperlink markup
|
||||
func defaultLinkHandler(name, ref string) string {
|
||||
return fmt.Sprintf("`%s <%s.rst>`_", name, ref)
|
||||
}
|
||||
|
@ -70,7 +71,7 @@ func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, str
|
|||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
ref := strings.Replace(name, " ", "_", -1)
|
||||
ref := strings.ReplaceAll(name, " ", "_")
|
||||
|
||||
buf.WriteString(".. _" + ref + ":\n\n")
|
||||
buf.WriteString(name + "\n")
|
||||
|
@ -99,7 +100,7 @@ func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, str
|
|||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
ref = strings.Replace(pname, " ", "_", -1)
|
||||
ref = strings.ReplaceAll(pname, " ", "_")
|
||||
buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short))
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
|
@ -116,7 +117,7 @@ func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, str
|
|||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
ref = strings.Replace(cname, " ", "_", -1)
|
||||
ref = strings.ReplaceAll(cname, " ", "_")
|
||||
buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short))
|
||||
}
|
||||
buf.WriteString("\n")
|
||||
|
@ -139,7 +140,7 @@ func GenReSTTree(cmd *cobra.Command, dir string) error {
|
|||
return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
|
||||
}
|
||||
|
||||
// GenReSTTreeCustom is the the same as GenReSTTree, but
|
||||
// GenReSTTreeCustom is the same as GenReSTTree, but
|
||||
// with custom filePrepender and linkHandler.
|
||||
func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
|
@ -151,7 +152,7 @@ func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string
|
|||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst"
|
||||
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".rst"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
@ -168,7 +169,7 @@ func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string
|
|||
return nil
|
||||
}
|
||||
|
||||
// adapted from: https://github.com/kr/text/blob/main/indent.go
|
||||
// indentString adapted from: https://github.com/kr/text/blob/main/indent.go
|
||||
func indentString(s, p string) string {
|
||||
var res []byte
|
||||
b := []byte(s)
|
||||
|
|
|
@ -1,8 +1,21 @@
|
|||
// Copyright 2013-2023 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
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
@ -67,7 +80,7 @@ func TestGenRSTNoTag(t *testing.T) {
|
|||
func TestGenRSTTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-rst-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
|
@ -83,7 +96,7 @@ func TestGenRSTTree(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkGenReSTToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
// Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
// Copyright 2013-2023 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
|
||||
//
|
||||
// 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,
|
||||
|
@ -39,7 +40,7 @@ func hasSeeAlso(cmd *cobra.Command) bool {
|
|||
// that do not contain \n.
|
||||
func forceMultiLine(s string) string {
|
||||
if len(s) > 60 && !strings.Contains(s, "\n") {
|
||||
s = s + "\n"
|
||||
s += "\n"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
// Copyright 2016 French Ben. All rights reserved.
|
||||
// Copyright 2013-2023 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
|
||||
//
|
||||
// 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,
|
||||
|
@ -23,7 +24,7 @@ import (
|
|||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
"gopkg.in/yaml.v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type cmdOption struct {
|
||||
|
@ -66,7 +67,7 @@ func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandle
|
|||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml"
|
||||
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".yaml"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
@ -128,7 +129,7 @@ func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) str
|
|||
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
result = append(result, child.Name()+" - "+child.Short)
|
||||
result = append(result, child.CommandPath()+" - "+child.Short)
|
||||
}
|
||||
yamlDoc.SeeAlso = result
|
||||
}
|
||||
|
|
|
@ -1,8 +1,22 @@
|
|||
// Copyright 2013-2023 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
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
@ -24,6 +38,7 @@ func TestGenYamlDoc(t *testing.T) {
|
|||
checkStringContains(t, output, "rootflag")
|
||||
checkStringContains(t, output, rootCmd.Short)
|
||||
checkStringContains(t, output, echoSubCmd.Short)
|
||||
checkStringContains(t, output, fmt.Sprintf("- %s - %s", echoSubCmd.CommandPath(), echoSubCmd.Short))
|
||||
}
|
||||
|
||||
func TestGenYamlNoTag(t *testing.T) {
|
||||
|
@ -42,7 +57,7 @@ func TestGenYamlNoTag(t *testing.T) {
|
|||
func TestGenYamlTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
|
||||
tmpdir, err := os.MkdirTemp("", "test-gen-yaml-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
|
@ -69,7 +84,7 @@ func TestGenYamlDocRunnable(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkGenYamlToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
file, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -11,8 +25,8 @@ import (
|
|||
func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
|
||||
nameForVar = strings.Replace(nameForVar, ":", "_", -1)
|
||||
nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
|
||||
nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
|
@ -38,7 +52,8 @@ function __%[1]s_perform_completion
|
|||
__%[1]s_debug "args: $args"
|
||||
__%[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 "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
|
||||
|
||||
__%[1]s_debug "Calling $requestComp"
|
||||
set -l results (eval $requestComp 2> /dev/null)
|
||||
|
@ -74,6 +89,60 @@ function __%[1]s_perform_completion
|
|||
printf "%%s\n" "$directiveLine"
|
||||
end
|
||||
|
||||
# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result
|
||||
function __%[1]s_perform_completion_once
|
||||
__%[1]s_debug "Starting __%[1]s_perform_completion_once"
|
||||
|
||||
if test -n "$__%[1]s_perform_completion_once_result"
|
||||
__%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion"
|
||||
return 0
|
||||
end
|
||||
|
||||
set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion)
|
||||
if test -z "$__%[1]s_perform_completion_once_result"
|
||||
__%[1]s_debug "No completions, probably due to a failure"
|
||||
return 1
|
||||
end
|
||||
|
||||
__%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result"
|
||||
return 0
|
||||
end
|
||||
|
||||
# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run
|
||||
function __%[1]s_clear_perform_completion_once_result
|
||||
__%[1]s_debug ""
|
||||
__%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable =========="
|
||||
set --erase __%[1]s_perform_completion_once_result
|
||||
__%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result"
|
||||
end
|
||||
|
||||
function __%[1]s_requires_order_preservation
|
||||
__%[1]s_debug ""
|
||||
__%[1]s_debug "========= checking if order preservation is required =========="
|
||||
|
||||
__%[1]s_perform_completion_once
|
||||
if test -z "$__%[1]s_perform_completion_once_result"
|
||||
__%[1]s_debug "Error determining if order preservation is required"
|
||||
return 1
|
||||
end
|
||||
|
||||
set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])
|
||||
__%[1]s_debug "Directive is: $directive"
|
||||
|
||||
set -l shellCompDirectiveKeepOrder %[9]d
|
||||
set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2)
|
||||
__%[1]s_debug "Keeporder is: $keeporder"
|
||||
|
||||
if test $keeporder -ne 0
|
||||
__%[1]s_debug "This does require order preservation"
|
||||
return 0
|
||||
end
|
||||
|
||||
__%[1]s_debug "This doesn't require order preservation"
|
||||
return 1
|
||||
end
|
||||
|
||||
|
||||
# This function does two things:
|
||||
# - Obtain the completions and store them in the global __%[1]s_comp_results
|
||||
# - Return false if file completion should be performed
|
||||
|
@ -84,17 +153,17 @@ function __%[1]s_prepare_completions
|
|||
# Start fresh
|
||||
set --erase __%[1]s_comp_results
|
||||
|
||||
set -l results (__%[1]s_perform_completion)
|
||||
__%[1]s_debug "Completion results: $results"
|
||||
__%[1]s_perform_completion_once
|
||||
__%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result"
|
||||
|
||||
if test -z "$results"
|
||||
if test -z "$__%[1]s_perform_completion_once_result"
|
||||
__%[1]s_debug "No completion, probably due to a failure"
|
||||
# Might as well do file completion, in case it helps
|
||||
return 1
|
||||
end
|
||||
|
||||
set -l directive (string sub --start 2 $results[-1])
|
||||
set --global __%[1]s_comp_results $results[1..-2]
|
||||
set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])
|
||||
set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2]
|
||||
|
||||
__%[1]s_debug "Completions are: $__%[1]s_comp_results"
|
||||
__%[1]s_debug "Directive is: $directive"
|
||||
|
@ -190,13 +259,17 @@ end
|
|||
# Remove any pre-existing completions for the program since we will be handling all of them.
|
||||
complete -c %[2]s -e
|
||||
|
||||
# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global
|
||||
complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result'
|
||||
# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results
|
||||
# which provides the program's completion choices.
|
||||
complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
|
||||
|
||||
# If this doesn't require order preservation, we don't use the -k flag
|
||||
complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
|
||||
# otherwise we use the -k flag
|
||||
complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
|
||||
`, nameForVar, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
// GenFishCompletion generates fish completion file and writes to the passed writer.
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
## Generating Fish Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
|
@ -1,7 +1,25 @@
|
|||
// Copyright 2013-2023 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"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
@ -67,3 +85,59 @@ func TestProgWithColon(t *testing.T) {
|
|||
check(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) {
|
||||
tmpFile, err := os.CreateTemp("", "cobra-test")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
|
||||
child := &Command{
|
||||
Use: "child",
|
||||
ValidArgsFunction: validArgsFunc,
|
||||
Run: emptyRun,
|
||||
}
|
||||
rootCmd.AddCommand(child)
|
||||
|
||||
assertNoErr(t, rootCmd.GenFishCompletionFile(tmpFile.Name(), false))
|
||||
}
|
||||
|
||||
func TestFailGenFishCompletionFile(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "cobra-test")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
f, _ := os.OpenFile(filepath.Join(tmpDir, "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(f.Name(), false)
|
||||
if !errors.Is(got, os.ErrPermission) {
|
||||
t.Errorf("got: %s, want: %s", got.Error(), os.ErrPermission.Error())
|
||||
}
|
||||
}
|
||||
|
|
290
flag_groups.go
Normal file
290
flag_groups.go
Normal file
|
@ -0,0 +1,290 @@
|
|||
// Copyright 2013-2023 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"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set"
|
||||
oneRequiredAnnotation = "cobra_annotation_one_required"
|
||||
mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive"
|
||||
)
|
||||
|
||||
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked with a subset (but not all) of the given flags.
|
||||
func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))
|
||||
}
|
||||
if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil {
|
||||
// Only errs if the flag isn't found.
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked without at least one flag from the given set of flags.
|
||||
func (c *Command) MarkFlagsOneRequired(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v))
|
||||
}
|
||||
if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil {
|
||||
// Only errs if the flag isn't found.
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked with more than one flag from the given set of flags.
|
||||
func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))
|
||||
}
|
||||
// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.
|
||||
if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the
|
||||
// first error encountered.
|
||||
func (c *Command) ValidateFlagGroups() error {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
|
||||
flags := c.Flags()
|
||||
|
||||
// groupStatus format is the list of flags as a unique ID,
|
||||
// then a map of each flag name and whether it is set or not.
|
||||
groupStatus := map[string]map[string]bool{}
|
||||
oneRequiredGroupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
flags.VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
if err := validateRequiredFlagGroups(groupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {
|
||||
for _, fname := range flagnames {
|
||||
f := fs.Lookup(fname)
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {
|
||||
groupInfo, found := pflag.Annotations[annotation]
|
||||
if found {
|
||||
for _, group := range groupInfo {
|
||||
if groupStatus[group] == nil {
|
||||
flagnames := strings.Split(group, " ")
|
||||
|
||||
// Only consider this flag group at all if all the flags are defined.
|
||||
if !hasAllFlags(flags, flagnames...) {
|
||||
continue
|
||||
}
|
||||
|
||||
groupStatus[group] = make(map[string]bool, len(flagnames))
|
||||
for _, name := range flagnames {
|
||||
groupStatus[group][name] = false
|
||||
}
|
||||
}
|
||||
|
||||
groupStatus[group][pflag.Name] = pflag.Changed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateRequiredFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
|
||||
unset := []string{}
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if !isSet {
|
||||
unset = append(unset, flagname)
|
||||
}
|
||||
}
|
||||
if len(unset) == len(flagnameAndStatus) || len(unset) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(unset)
|
||||
return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOneRequiredFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
var set []string
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
set = append(set, flagname)
|
||||
}
|
||||
}
|
||||
if len(set) >= 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(set)
|
||||
return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
var set []string
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
set = append(set, flagname)
|
||||
}
|
||||
}
|
||||
if len(set) == 0 || len(set) == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(set)
|
||||
return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]map[string]bool) []string {
|
||||
keys := make([]string, len(m))
|
||||
i := 0
|
||||
for k := range m {
|
||||
keys[i] = k
|
||||
i++
|
||||
}
|
||||
sort.Strings(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 none of the flags in a one-required group are present, all flags in the group will be marked required
|
||||
// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
|
||||
// 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{}
|
||||
oneRequiredGroupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
c.Flags().VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
// If a flag that is part of a group is present, we make all the other flags
|
||||
// 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 none of the flags of a one-required group are present, we make all the flags
|
||||
// of that group required so that the shell completion suggests them automatically
|
||||
for flagList, flagnameAndStatus := range oneRequiredGroupStatus {
|
||||
isSet := false
|
||||
|
||||
for _, isSet = range flagnameAndStatus {
|
||||
if isSet {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// None of the flags of the group are set, mark all flags in the group
|
||||
// as required
|
||||
if !isSet {
|
||||
for _, fName := range strings.Split(flagList, " ") {
|
||||
_ = c.MarkFlagRequired(fName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If a flag that is mutually exclusive to others is present, we hide the other
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
195
flag_groups_test.go
Normal file
195
flag_groups_test.go
Normal file
|
@ -0,0 +1,195 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateFlagGroups(t *testing.T) {
|
||||
getCmd := func() *Command {
|
||||
c := &Command{
|
||||
Use: "testcmd",
|
||||
Run: func(cmd *Command, args []string) {
|
||||
}}
|
||||
// Define lots of flags to utilize for testing.
|
||||
for _, v := range []string{"a", "b", "c", "d"} {
|
||||
c.Flags().String(v, "", "")
|
||||
}
|
||||
for _, v := range []string{"e", "f", "g"} {
|
||||
c.PersistentFlags().String(v, "", "")
|
||||
}
|
||||
subC := &Command{
|
||||
Use: "subcmd",
|
||||
Run: func(cmd *Command, args []string) {
|
||||
}}
|
||||
subC.Flags().String("subonly", "", "")
|
||||
c.AddCommand(subC)
|
||||
return c
|
||||
}
|
||||
|
||||
// Each test case uses a unique command from the function above.
|
||||
testcases := []struct {
|
||||
desc string
|
||||
flagGroupsRequired []string
|
||||
flagGroupsOneRequired []string
|
||||
flagGroupsExclusive []string
|
||||
subCmdFlagGroupsRequired []string
|
||||
subCmdFlagGroupsOneRequired []string
|
||||
subCmdFlagGroupsExclusive []string
|
||||
args []string
|
||||
expectErr string
|
||||
}{
|
||||
{
|
||||
desc: "No flags no problem",
|
||||
}, {
|
||||
desc: "No flags no problem even with conflicting groups",
|
||||
flagGroupsRequired: []string{"a b"},
|
||||
flagGroupsExclusive: []string{"a b"},
|
||||
}, {
|
||||
desc: "Required flag group not satisfied",
|
||||
flagGroupsRequired: []string{"a b c"},
|
||||
args: []string{"--a=foo"},
|
||||
expectErr: "if any flags in the group [a b c] are set they must all be set; missing [b c]",
|
||||
}, {
|
||||
desc: "One-required flag group not satisfied",
|
||||
flagGroupsOneRequired: []string{"a b"},
|
||||
args: []string{"--c=foo"},
|
||||
expectErr: "at least one of the flags in the group [a b] is required",
|
||||
}, {
|
||||
desc: "Exclusive flag group not satisfied",
|
||||
flagGroupsExclusive: []string{"a b c"},
|
||||
args: []string{"--a=foo", "--b=foo"},
|
||||
expectErr: "if any flags in the group [a b c] are set none of the others can be; [a b] were all set",
|
||||
}, {
|
||||
desc: "Multiple required flag group not satisfied returns first error",
|
||||
flagGroupsRequired: []string{"a b c", "a d"},
|
||||
args: []string{"--c=foo", "--d=foo"},
|
||||
expectErr: `if any flags in the group [a b c] are set they must all be set; missing [a b]`,
|
||||
}, {
|
||||
desc: "Multiple one-required flag group not satisfied returns first error",
|
||||
flagGroupsOneRequired: []string{"a b", "d e"},
|
||||
args: []string{"--c=foo", "--f=foo"},
|
||||
expectErr: `at least one of the flags in the group [a b] is required`,
|
||||
}, {
|
||||
desc: "Multiple exclusive flag group not satisfied returns first error",
|
||||
flagGroupsExclusive: []string{"a b c", "a d"},
|
||||
args: []string{"--a=foo", "--c=foo", "--d=foo"},
|
||||
expectErr: `if any flags in the group [a b c] are set none of the others can be; [a c] were all set`,
|
||||
}, {
|
||||
desc: "Validation of required groups occurs on groups in sorted order",
|
||||
flagGroupsRequired: []string{"a d", "a b", "a c"},
|
||||
args: []string{"--a=foo"},
|
||||
expectErr: `if any flags in the group [a b] are set they must all be set; missing [b]`,
|
||||
}, {
|
||||
desc: "Validation of one-required groups occurs on groups in sorted order",
|
||||
flagGroupsOneRequired: []string{"d e", "a b", "f g"},
|
||||
args: []string{"--c=foo"},
|
||||
expectErr: `at least one of the flags in the group [a b] is required`,
|
||||
}, {
|
||||
desc: "Validation of exclusive groups occurs on groups in sorted order",
|
||||
flagGroupsExclusive: []string{"a d", "a b", "a c"},
|
||||
args: []string{"--a=foo", "--b=foo", "--c=foo"},
|
||||
expectErr: `if any flags in the group [a b] are set none of the others can be; [a b] were all set`,
|
||||
}, {
|
||||
desc: "Persistent flags utilize required and exclusive groups and can fail required groups",
|
||||
flagGroupsRequired: []string{"a e", "e f"},
|
||||
flagGroupsExclusive: []string{"f g"},
|
||||
args: []string{"--a=foo", "--f=foo", "--g=foo"},
|
||||
expectErr: `if any flags in the group [a e] are set they must all be set; missing [e]`,
|
||||
}, {
|
||||
desc: "Persistent flags utilize one-required and exclusive groups and can fail one-required groups",
|
||||
flagGroupsOneRequired: []string{"a b", "e f"},
|
||||
flagGroupsExclusive: []string{"e f"},
|
||||
args: []string{"--e=foo"},
|
||||
expectErr: `at least one of the flags in the group [a b] is required`,
|
||||
}, {
|
||||
desc: "Persistent flags utilize required and exclusive groups and can fail mutually exclusive groups",
|
||||
flagGroupsRequired: []string{"a e", "e f"},
|
||||
flagGroupsExclusive: []string{"f g"},
|
||||
args: []string{"--a=foo", "--e=foo", "--f=foo", "--g=foo"},
|
||||
expectErr: `if any flags in the group [f g] are set none of the others can be; [f g] were all set`,
|
||||
}, {
|
||||
desc: "Persistent flags utilize required and exclusive groups and can pass",
|
||||
flagGroupsRequired: []string{"a e", "e f"},
|
||||
flagGroupsExclusive: []string{"f g"},
|
||||
args: []string{"--a=foo", "--e=foo", "--f=foo"},
|
||||
}, {
|
||||
desc: "Persistent flags utilize one-required and exclusive groups and can pass",
|
||||
flagGroupsOneRequired: []string{"a e", "e f"},
|
||||
flagGroupsExclusive: []string{"f g"},
|
||||
args: []string{"--a=foo", "--e=foo", "--f=foo"},
|
||||
}, {
|
||||
desc: "Subcmds can use required groups using inherited flags",
|
||||
subCmdFlagGroupsRequired: []string{"e subonly"},
|
||||
args: []string{"subcmd", "--e=foo", "--subonly=foo"},
|
||||
}, {
|
||||
desc: "Subcmds can use one-required groups using inherited flags",
|
||||
subCmdFlagGroupsOneRequired: []string{"e subonly"},
|
||||
args: []string{"subcmd", "--e=foo", "--subonly=foo"},
|
||||
}, {
|
||||
desc: "Subcmds can use one-required groups using inherited flags and fail one-required groups",
|
||||
subCmdFlagGroupsOneRequired: []string{"e subonly"},
|
||||
args: []string{"subcmd"},
|
||||
expectErr: "at least one of the flags in the group [e subonly] is required",
|
||||
}, {
|
||||
desc: "Subcmds can use exclusive groups using inherited flags",
|
||||
subCmdFlagGroupsExclusive: []string{"e subonly"},
|
||||
args: []string{"subcmd", "--e=foo", "--subonly=foo"},
|
||||
expectErr: "if any flags in the group [e subonly] are set none of the others can be; [e subonly] were all set",
|
||||
}, {
|
||||
desc: "Subcmds can use exclusive groups using inherited flags and pass",
|
||||
subCmdFlagGroupsExclusive: []string{"e subonly"},
|
||||
args: []string{"subcmd", "--e=foo"},
|
||||
}, {
|
||||
desc: "Flag groups not applied if not found on invoked command",
|
||||
subCmdFlagGroupsRequired: []string{"e subonly"},
|
||||
args: []string{"--e=foo"},
|
||||
},
|
||||
}
|
||||
for _, tc := range testcases {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
c := getCmd()
|
||||
sub := c.Commands()[0]
|
||||
for _, flagGroup := range tc.flagGroupsRequired {
|
||||
c.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)
|
||||
}
|
||||
for _, flagGroup := range tc.flagGroupsOneRequired {
|
||||
c.MarkFlagsOneRequired(strings.Split(flagGroup, " ")...)
|
||||
}
|
||||
for _, flagGroup := range tc.flagGroupsExclusive {
|
||||
c.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)
|
||||
}
|
||||
for _, flagGroup := range tc.subCmdFlagGroupsRequired {
|
||||
sub.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)
|
||||
}
|
||||
for _, flagGroup := range tc.subCmdFlagGroupsOneRequired {
|
||||
sub.MarkFlagsOneRequired(strings.Split(flagGroup, " ")...)
|
||||
}
|
||||
for _, flagGroup := range tc.subCmdFlagGroupsExclusive {
|
||||
sub.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)
|
||||
}
|
||||
c.SetArgs(tc.args)
|
||||
err := c.Execute()
|
||||
switch {
|
||||
case err == nil && len(tc.expectErr) > 0:
|
||||
t.Errorf("Expected error %q but got nil", tc.expectErr)
|
||||
case err != nil && err.Error() != tc.expectErr:
|
||||
t.Errorf("Expected error %q but got %q", tc.expectErr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
8
go.mod
8
go.mod
|
@ -3,8 +3,8 @@ module github.com/spf13/cobra
|
|||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.1
|
||||
github.com/inconshreveable/mousetrap v1.0.0
|
||||
github.com/spf13/pflag v1.0.5
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6
|
||||
github.com/inconshreveable/mousetrap v1.1.0
|
||||
github.com/spf13/pflag v1.0.6
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
|
24
go.sum
24
go.sum
|
@ -1,18 +1,12 @@
|
|||
github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs=
|
||||
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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
|
||||
// can be downloaded separately for windows 7 or 8.1).
|
||||
|
||||
|
@ -8,9 +22,15 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
|
||||
nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
|
@ -27,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
||||
[scriptblock]${__%[2]sCompleterBlock} = {
|
||||
param(
|
||||
$WordToComplete,
|
||||
$CommandAst,
|
||||
|
@ -52,16 +72,18 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
}
|
||||
__%[1]s_debug "Truncated command: $Command"
|
||||
|
||||
$ShellCompDirectiveError=%[3]d
|
||||
$ShellCompDirectiveNoSpace=%[4]d
|
||||
$ShellCompDirectiveNoFileComp=%[5]d
|
||||
$ShellCompDirectiveFilterFileExt=%[6]d
|
||||
$ShellCompDirectiveFilterDirs=%[7]d
|
||||
$ShellCompDirectiveError=%[4]d
|
||||
$ShellCompDirectiveNoSpace=%[5]d
|
||||
$ShellCompDirectiveNoFileComp=%[6]d
|
||||
$ShellCompDirectiveFilterFileExt=%[7]d
|
||||
$ShellCompDirectiveFilterDirs=%[8]d
|
||||
$ShellCompDirectiveKeepOrder=%[9]d
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Split the command at the first space to separate the program and arguments.
|
||||
$Program,$Arguments = $Command.Split(" ",2)
|
||||
$RequestComp="$Program %[2]s $Arguments"
|
||||
|
||||
$RequestComp="$Program %[3]s $Arguments"
|
||||
__%[1]s_debug "RequestComp: $RequestComp"
|
||||
|
||||
# we cannot use $WordToComplete because it
|
||||
|
@ -85,16 +107,27 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go method.
|
||||
__%[1]s_debug "Adding extra empty parameter"
|
||||
`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+`
|
||||
`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
|
||||
# PowerShell 7.2+ changed the way how the arguments are passed to executables,
|
||||
# so for pre-7.2 or when Legacy argument passing is enabled we need to use
|
||||
`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+`
|
||||
if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
|
||||
($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
|
||||
(($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
|
||||
$PSNativeCommandArgumentPassing -eq 'Legacy')) {
|
||||
`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
|
||||
} else {
|
||||
$RequestComp="$RequestComp" + ' ""'
|
||||
}
|
||||
}
|
||||
|
||||
__%[1]s_debug "Calling $RequestComp"
|
||||
# First disable ActiveHelp which is not supported for Powershell
|
||||
${env:%[10]s}=0
|
||||
|
||||
#call the command store the output in $out and redirect stderr and stdout to null
|
||||
# $Out is an array contains each line per element
|
||||
Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
|
||||
|
||||
|
||||
# get directive from last line
|
||||
[int]$Directive = $Out[-1].TrimStart(':')
|
||||
if ($Directive -eq "") {
|
||||
|
@ -114,7 +147,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
}
|
||||
|
||||
$Longest = 0
|
||||
$Values = $Out | ForEach-Object {
|
||||
[Array]$Values = $Out | ForEach-Object {
|
||||
#Split the output in name and description
|
||||
`+" $Name, $Description = $_.Split(\"`t\",2)"+`
|
||||
__%[1]s_debug "Name: $Name Description: $Description"
|
||||
|
@ -129,7 +162,10 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
if (-Not $Description) {
|
||||
$Description = " "
|
||||
}
|
||||
@{Name="$Name";Description="$Description"}
|
||||
New-Object -TypeName PSCustomObject -Property @{
|
||||
Name = "$Name"
|
||||
Description = "$Description"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -159,6 +195,11 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
}
|
||||
}
|
||||
|
||||
# we sort the values in ascending order by name if keep order isn't passed
|
||||
if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
|
||||
$Values = $Values | Sort-Object -Property Name
|
||||
}
|
||||
|
||||
if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
|
||||
__%[1]s_debug "ShellCompDirectiveNoFileComp is called"
|
||||
|
||||
|
@ -202,7 +243,12 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
__%[1]s_debug "Only one completion left"
|
||||
|
||||
# insert space after value
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space
|
||||
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
|
||||
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
} else {
|
||||
$CompletionText
|
||||
}
|
||||
|
||||
} else {
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
|
@ -217,7 +263,12 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
$Description = " ($($comp.Description))"
|
||||
}
|
||||
|
||||
[System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
|
||||
$CompletionText = "$($comp.Name)$Description"
|
||||
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
|
||||
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
|
||||
} else {
|
||||
$CompletionText
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -226,7 +277,13 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
# insert space after value
|
||||
# MenuComplete will automatically show the ToolTip of
|
||||
# the highlighted value at the bottom of the suggestions.
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
|
||||
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space
|
||||
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
|
||||
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
} else {
|
||||
$CompletionText
|
||||
}
|
||||
}
|
||||
|
||||
# TabCompleteNext and in case we get something unknown
|
||||
|
@ -234,15 +291,23 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
# Like MenuComplete but we don't want to add a space here because
|
||||
# the user need to press space anyway to get the completion.
|
||||
# Description will not be shown because that's not possible with TabCompleteNext
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
|
||||
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars)
|
||||
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
|
||||
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
} else {
|
||||
$CompletionText
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
`, name, compCmd,
|
||||
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock}
|
||||
`, name, nameForVar, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
# Generating PowerShell Completions For Your Own cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.
|
33
powershell_completions_test.go
Normal file
33
powershell_completions_test.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
// Copyright 2013-2023 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("${env:%s}=0", activeHelpVar))
|
||||
}
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
|
168
site/content/active_help.md
Normal file
168
site/content/active_help.md
Normal file
|
@ -0,0 +1,168 @@
|
|||
# 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,
|
||||
|
||||
```console
|
||||
$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding.
|
||||
|
||||
$ bin/helm package [tab]
|
||||
Please specify the path to the chart to package
|
||||
|
||||
$ 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](completions/_index.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.
|
||||
- Zsh
|
||||
|
||||
## Adding Active Help messages
|
||||
|
||||
As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](completions/_index.md).
|
||||
|
||||
Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.
|
||||
|
||||
### 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) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
var comps []cobra.Completion
|
||||
if len(args) == 0 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
} else if len(args) == 1 {
|
||||
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:
|
||||
|
||||
```console
|
||||
$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding
|
||||
|
||||
$ helm repo add grafana [tab]
|
||||
You must specify the URL for the repo you are adding
|
||||
|
||||
$ 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) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
if len(args) != 2 {
|
||||
return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
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.
|
||||
|
||||
```console
|
||||
$ bin/helm install myrelease --version 2.0.[tab]
|
||||
You must first specify the chart to install before the --version flag can be completed
|
||||
|
||||
$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
|
||||
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 non-ASCII-alphanumeric characters 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) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
|
||||
|
||||
var comps []cobra.Completion
|
||||
if len(args) == 0 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
}
|
||||
} 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](completions/_index.md#debugging) for details.
|
||||
|
||||
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any non-ASCII-alphanumeric characters are replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
|
||||
|
||||
```console
|
||||
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
_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
|
||||
```
|
|
@ -8,7 +8,8 @@ The currently supported shells are:
|
|||
- PowerShell
|
||||
|
||||
Cobra will automatically provide your program with a fully functional `completion` command,
|
||||
similarly to how it provides the `help` command.
|
||||
similarly to how it provides the `help` command. If there are no other subcommands, the
|
||||
default `completion` command will be hidden, but still functional.
|
||||
|
||||
## Creating your own completion command
|
||||
|
||||
|
@ -40,7 +41,7 @@ Bash:
|
|||
# Linux:
|
||||
$ %[1]s completion bash > /etc/bash_completion.d/%[1]s
|
||||
# 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:
|
||||
|
||||
|
@ -71,7 +72,7 @@ PowerShell:
|
|||
`,cmd.Root().Name()),
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
|
||||
Args: cobra.ExactValidArgs(1),
|
||||
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
switch args[0] {
|
||||
case "bash":
|
||||
|
@ -99,6 +100,11 @@ To tell Cobra *not* to provide the default `completion` command:
|
|||
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:
|
||||
```
|
||||
rootCmd.CompletionOptions.DisableNoDescFlag = true
|
||||
|
@ -122,7 +128,7 @@ For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns
|
|||
Some simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pod", "node", "service", "replicationcontroller" }
|
||||
validArgs = []string{ "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
|
@ -148,7 +154,7 @@ node pod replicationcontroller service
|
|||
If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go
|
||||
argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
|
@ -157,16 +163,7 @@ cmd := &cobra.Command{
|
|||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
$ kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of
|
||||
replication controllers following `rc`.
|
||||
The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.
|
||||
|
||||
### Dynamic completion of nouns
|
||||
|
||||
|
@ -181,7 +178,7 @@ cmd := &cobra.Command{
|
|||
RunE: func(cmd *cobra.Command, args []string) {
|
||||
RunGet(args[0])
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
if len(args) != 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
@ -215,7 +212,7 @@ ShellCompDirectiveNoFileComp
|
|||
|
||||
// Indicates that the returned completions should be used as file extension filters.
|
||||
// For example, to complete only files of the form *.json or *.yaml:
|
||||
// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt
|
||||
// return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt
|
||||
// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
|
||||
// is a shortcut to using this directive explicitly.
|
||||
//
|
||||
|
@ -223,15 +220,19 @@ ShellCompDirectiveFilterFileExt
|
|||
|
||||
// Indicates that only directory names should be provided in file completion.
|
||||
// For example:
|
||||
// return nil, ShellCompDirectiveFilterDirs
|
||||
// return nil, cobra.ShellCompDirectiveFilterDirs
|
||||
// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
|
||||
//
|
||||
// To request directory names within another directory, the returned completions
|
||||
// should specify a single directory name within which to search. For example,
|
||||
// to complete directories within "themes/":
|
||||
// return []string{"themes"}, ShellCompDirectiveFilterDirs
|
||||
// return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
//
|
||||
ShellCompDirectiveFilterDirs
|
||||
|
||||
// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
|
||||
// in which the completions are provided
|
||||
ShellCompDirectiveKeepOrder
|
||||
```
|
||||
|
||||
***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
|
||||
|
@ -259,7 +260,7 @@ Calling the `__complete` command directly allows you to run the Go debugger to t
|
|||
```go
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and optionally prints to stderr.
|
||||
cobra.CompDebug(msg string, printToStdErr bool) {
|
||||
cobra.CompDebug(msg string, printToStdErr bool)
|
||||
cobra.CompDebugln(msg string, printToStdErr bool)
|
||||
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
|
@ -293,8 +294,8 @@ As for nouns, Cobra provides a way of defining dynamic completion of flags. To
|
|||
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
})
|
||||
```
|
||||
Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
|
||||
|
@ -327,8 +328,8 @@ cmd.MarkFlagFilename(flagName, "yaml", "json")
|
|||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt})
|
||||
```
|
||||
|
||||
### Limit flag completions to directory names
|
||||
|
@ -341,15 +342,15 @@ cmd.MarkFlagDirname(flagName)
|
|||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return nil, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
### Descriptions for completions
|
||||
|
@ -370,16 +371,38 @@ $ helm s[tab]
|
|||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
```
|
||||
|
||||
Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
|
||||
Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. Cobra provides the helper function `CompletionWithDesc(string, string)` to create a completion with a description. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
return []cobra.Completion{
|
||||
cobra.CompletionWithDesc("harbor", "An image registry"),
|
||||
cobra.CompletionWithDesc("thanos", "Long-term metrics")
|
||||
}, cobra.ShellCompDirectiveNoFileComp
|
||||
}}
|
||||
```
|
||||
or
|
||||
```go
|
||||
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
|
||||
ValidArgs: []cobra.Completion{
|
||||
cobra.CompletionWithDesc("bash", "Completions for bash"),
|
||||
cobra.CompletionWithDesc("zsh", "Completions for zsh")
|
||||
}
|
||||
```
|
||||
|
||||
If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:
|
||||
|
||||
```bash
|
||||
$ source <(helm completion bash)
|
||||
$ helm completion [tab][tab]
|
||||
bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell)
|
||||
fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh)
|
||||
|
||||
$ source <(helm completion bash --no-descriptions)
|
||||
$ helm completion [tab][tab]
|
||||
bash fish powershell zsh
|
||||
```
|
||||
|
||||
Setting the `<PROGRAM>_COMPLETION_DESCRIPTIONS` environment variable (falling back to `COBRA_COMPLETION_DESCRIPTIONS` if empty or not set) to a [falsey value](https://pkg.go.dev/strconv#ParseBool) achieves the same. `<PROGRAM>` is the name of your program with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
|
||||
## Bash completions
|
||||
|
||||
### Dependencies
|
||||
|
@ -403,7 +426,7 @@ completion firstcommand secondcommand
|
|||
### Bash legacy dynamic completions
|
||||
|
||||
For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
|
||||
Please refer to [Bash Completions](bash_completions.md) for details.
|
||||
Please refer to [Bash Completions](bash.md) for details.
|
||||
|
||||
### Bash completion V2
|
||||
|
||||
|
@ -412,13 +435,13 @@ Cobra provides two versions for bash completion. The original bash completion (
|
|||
|
||||
A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or
|
||||
`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion
|
||||
(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion
|
||||
(see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion
|
||||
solution described in this document.
|
||||
Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash
|
||||
completion V2 solution which provides the following extra features:
|
||||
- Supports completion descriptions (like the other shells)
|
||||
- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)
|
||||
- Streamlined user experience thanks to a completion behavior aligned with the other shells
|
||||
- Streamlined user experience thanks to a completion behavior aligned with the other shells
|
||||
|
||||
`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`
|
||||
you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra
|
||||
|
@ -435,7 +458,7 @@ show (show information of a chart)
|
|||
$ helm s[tab][tab]
|
||||
search show status
|
||||
```
|
||||
**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
|
||||
**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
|
||||
## Zsh completions
|
||||
|
||||
Cobra supports native zsh completion generated from the root `cobra.Command`.
|
||||
|
@ -469,7 +492,7 @@ search show status
|
|||
### Zsh completions standardization
|
||||
|
||||
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
|
||||
Please refer to [Zsh Completions](zsh_completions.md) for details.
|
||||
Please refer to [Zsh Completions](zsh.md) for details.
|
||||
|
||||
## fish completions
|
||||
|
||||
|
@ -522,7 +545,7 @@ search (search for a keyword in charts) show (show information of a chart) s
|
|||
|
||||
# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
search show status
|
||||
|
||||
search for a keyword in charts
|
||||
|
||||
|
@ -530,6 +553,21 @@ search for a keyword in charts
|
|||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
### Aliases
|
||||
|
||||
You can also configure `powershell` aliases for your program and they will also support completions.
|
||||
|
||||
```
|
||||
$ sal aliasname origcommand
|
||||
$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$ aliasname <tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
||||
The name of the completer block variable is of the form `$__<programName>CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax.
|
||||
|
||||
### Limitations
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Generating Bash Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
Please refer to [Shell Completions](_index.md) for details.
|
||||
|
||||
## Bash legacy dynamic completions
|
||||
|
4
site/content/completions/fish.md
Normal file
4
site/content/completions/fish.md
Normal file
|
@ -0,0 +1,4 @@
|
|||
## Generating Fish Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](_index.md) for details.
|
||||
|
3
site/content/completions/powershell.md
Normal file
3
site/content/completions/powershell.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
# Generating PowerShell Completions For Your Own cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](_index.md#powershell-completions) for details.
|
|
@ -1,6 +1,6 @@
|
|||
## Generating Zsh Completion For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
Please refer to [Shell Completions](_index.md) for details.
|
||||
|
||||
## Zsh completions standardization
|
||||
|
17
site/content/docgen/_index.md
Normal file
17
site/content/docgen/_index.md
Normal file
|
@ -0,0 +1,17 @@
|
|||
# Documentation generation
|
||||
|
||||
- [Man page docs](man.md)
|
||||
- [Markdown docs](md.md)
|
||||
- [Rest docs](rest.md)
|
||||
- [Yaml docs](yaml.md)
|
||||
|
||||
## Options
|
||||
### `DisableAutoGenTag`
|
||||
|
||||
You may set `cmd.DisableAutoGenTag = true`
|
||||
to _entirely_ remove the auto generated string "Auto generated by spf13/cobra..."
|
||||
from any documentation source.
|
||||
|
||||
### `InitDefaultCompletionCmd`
|
||||
|
||||
You may call `cmd.InitDefaultCompletionCmd()` to document the default autocompletion command.
|
|
@ -35,7 +35,7 @@ package main
|
|||
|
||||
import (
|
||||
"log"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
|
@ -45,7 +45,7 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)
|
||||
err := doc.GenMarkdownTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
@ -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
|
||||
const fmTemplate = `---
|
|
@ -35,7 +35,7 @@ package main
|
|||
|
||||
import (
|
||||
"log"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
|
@ -45,7 +45,7 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)
|
||||
err := doc.GenReSTTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
@ -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
|
||||
const fmTemplate = `---
|
|
@ -34,7 +34,7 @@ This program can actually generate docs for the kubectl command in the kubernete
|
|||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
|
@ -45,7 +45,7 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)
|
||||
err := doc.GenYamlTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
@ -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
|
||||
const fmTemplate = `---
|
|
@ -1,28 +1,40 @@
|
|||
## Projects using Cobra
|
||||
|
||||
- [Allero](https://github.com/allero-io/allero)
|
||||
- [Arewefastyet](https://benchmark.vitess.io)
|
||||
- [Arduino CLI](https://github.com/arduino/arduino-cli)
|
||||
- [Bleve](http://www.blevesearch.com/)
|
||||
- [CockroachDB](http://www.cockroachlabs.com/)
|
||||
- [Azion](https://github.com/aziontech/azion)
|
||||
- [Bleve](https://blevesearch.com/)
|
||||
- [Cilium](https://cilium.io/)
|
||||
- [CloudQuery](https://github.com/cloudquery/cloudquery)
|
||||
- [CockroachDB](https://www.cockroachlabs.com/)
|
||||
- [Conduit](https://github.com/conduitio/conduit)
|
||||
- [Constellation](https://github.com/edgelesssys/constellation)
|
||||
- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)
|
||||
- [Datree](https://github.com/datreeio/datree)
|
||||
- [Delve](https://github.com/derekparker/delve)
|
||||
- [Docker (distribution)](https://github.com/docker/distribution)
|
||||
- [Encore](https://encore.dev)
|
||||
- [Etcd](https://etcd.io/)
|
||||
- [Gardener](https://github.com/gardener/gardenctl)
|
||||
- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)
|
||||
- [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)
|
||||
- [Golangci-lint](https://golangci-lint.run)
|
||||
- [GopherJS](http://www.gopherjs.org/)
|
||||
- [GopherJS](https://github.com/gopherjs/gopherjs)
|
||||
- [GoReleaser](https://goreleaser.com)
|
||||
- [Helm](https://helm.sh)
|
||||
- [Hugo](https://gohugo.io)
|
||||
- [Incus](https://linuxcontainers.org/incus/)
|
||||
- [Infracost](https://github.com/infracost/infracost)
|
||||
- [Istio](https://istio.io)
|
||||
- [Kool](https://github.com/kool-dev/kool)
|
||||
- [Kubernetes](http://kubernetes.io/)
|
||||
- [Kubernetes](https://kubernetes.io/)
|
||||
- [Kubescape](https://github.com/kubescape/kubescape)
|
||||
- [KubeVirt](https://github.com/kubevirt/kubevirt)
|
||||
- [Linkerd](https://linkerd.io/)
|
||||
- [LXC](https://github.com/canonical/lxd)
|
||||
- [Mattermost-server](https://github.com/mattermost/mattermost-server)
|
||||
- [Mercure](https://mercure.rocks/)
|
||||
- [Meroxa CLI](https://github.com/meroxa/cli)
|
||||
|
@ -32,20 +44,28 @@
|
|||
- [Multi-gitter](https://github.com/lindell/multi-gitter)
|
||||
- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
|
||||
- [nFPM](https://nfpm.goreleaser.com)
|
||||
- [Okteto](https://github.com/okteto/okteto)
|
||||
- [OpenShift](https://www.openshift.com/)
|
||||
- [Ory Hydra](https://github.com/ory/hydra)
|
||||
- [Ory Kratos](https://github.com/ory/kratos)
|
||||
- [Pixie](https://github.com/pixie-io/pixie)
|
||||
- [Polygon Edge](https://github.com/0xPolygon/polygon-edge)
|
||||
- [Pouch](https://github.com/alibaba/pouch)
|
||||
- [ProjectAtomic (enterprise)](http://www.projectatomic.io/)
|
||||
- [ProjectAtomic (enterprise)](https://www.projectatomic.io/)
|
||||
- [Prototool](https://github.com/uber/prototool)
|
||||
- [Pulumi](https://www.pulumi.com)
|
||||
- [QRcp](https://github.com/claudiodangelis/qrcp)
|
||||
- [Random](https://github.com/erdaltsksn/random)
|
||||
- [Rclone](https://rclone.org/)
|
||||
- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)
|
||||
- [Sia](https://github.com/SiaFoundation/siad)
|
||||
- [Skaffold](https://skaffold.dev/)
|
||||
- [Taikun](https://taikun.cloud/)
|
||||
- [Tendermint](https://github.com/tendermint/tendermint)
|
||||
- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
|
||||
- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)
|
||||
- [Vitess](https://vitess.io)
|
||||
- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)
|
||||
- [Werf](https://werf.io/)
|
||||
- [Zarf](https://github.com/defenseunicorns/zarf)
|
||||
- [ZITADEL](https://github.com/zitadel/zitadel)
|
|
@ -3,14 +3,14 @@
|
|||
While you are welcome to provide your own organization, typically a Cobra-based
|
||||
application will follow the following organizational structure:
|
||||
|
||||
```
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
```console
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
```
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
|
||||
|
@ -18,9 +18,7 @@ In a Cobra app, typically the main.go file is very bare. It serves one purpose:
|
|||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
import "{pathToYourApp}/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
|
@ -29,10 +27,10 @@ func main() {
|
|||
|
||||
## Using the Cobra Generator
|
||||
|
||||
Cobra-CLI is its own program that will create your application and add any
|
||||
commands you want. It's the easiest way to incorporate Cobra into your application.
|
||||
Cobra-CLI is its own program that will create your application and add any commands you want.
|
||||
It's the easiest way to incorporate Cobra into your application.
|
||||
|
||||
For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/master/README.md)
|
||||
For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
|
||||
|
||||
## Using the Cobra Library
|
||||
|
||||
|
@ -51,7 +49,7 @@ var rootCmd = &cobra.Command{
|
|||
Short: "Hugo is a very fast static site generator",
|
||||
Long: `A Fast and Flexible Static Site Generator built with
|
||||
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) {
|
||||
// Do Stuff Here
|
||||
},
|
||||
|
@ -148,9 +146,7 @@ In a Cobra app, typically the main.go file is very bare. It serves one purpose:
|
|||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
import "{pathToYourApp}/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
|
@ -188,6 +184,37 @@ var versionCmd = &cobra.Command{
|
|||
}
|
||||
```
|
||||
|
||||
### Organizing subcommands
|
||||
|
||||
A command may have subcommands which in turn may have other subcommands. This is achieved by using
|
||||
`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in
|
||||
its own go package.
|
||||
|
||||
The suggested approach is for the parent command to use `AddCommand` to add its most immediate
|
||||
subcommands. For example, consider the following directory structure:
|
||||
|
||||
```console
|
||||
├── cmd
|
||||
│ ├── root.go
|
||||
│ └── sub1
|
||||
│ ├── sub1.go
|
||||
│ └── sub2
|
||||
│ ├── leafA.go
|
||||
│ ├── leafB.go
|
||||
│ └── sub2.go
|
||||
└── main.go
|
||||
```
|
||||
|
||||
In this case:
|
||||
|
||||
* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.
|
||||
* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.
|
||||
* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the
|
||||
sub2 command.
|
||||
|
||||
This approach ensures the subcommands are always included at compile time while avoiding cyclic
|
||||
references.
|
||||
|
||||
### Returning and handling errors
|
||||
|
||||
If you wish to return an error to the caller of a command, `RunE` can be used.
|
||||
|
@ -270,6 +297,7 @@ command := cobra.Command{
|
|||
### Bind Flags with Config
|
||||
|
||||
You can also bind your flags with [viper](https://github.com/spf13/viper):
|
||||
|
||||
```go
|
||||
var author string
|
||||
|
||||
|
@ -289,43 +317,99 @@ More in [viper documentation](https://github.com/spf13/viper#working-with-flags)
|
|||
|
||||
Flags are optional by default. If instead you wish your command to report an error
|
||||
when a flag has not been set, mark it as required:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkFlagRequired("region")
|
||||
```
|
||||
|
||||
Or, for persistent flags:
|
||||
|
||||
```go
|
||||
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkPersistentFlagRequired("region")
|
||||
```
|
||||
|
||||
### 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
|
||||
Cobra can enforce that requirement:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
|
||||
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
|
||||
rootCmd.MarkFlagsRequiredTogether("username", "password")
|
||||
```
|
||||
|
||||
You can also prevent different flags from being provided together if they represent mutually
|
||||
exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
|
||||
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
|
||||
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
|
||||
```
|
||||
|
||||
If you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`.
|
||||
This can be combined with `MarkFlagsMutuallyExclusive` to enforce exactly one flag from a given group:
|
||||
|
||||
```go
|
||||
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
|
||||
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
|
||||
rootCmd.MarkFlagsOneRequired("json", "yaml")
|
||||
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
|
||||
```
|
||||
|
||||
In these cases:
|
||||
- both local and persistent flags can be used
|
||||
- **NOTE:** the group is only enforced on commands where every flag is defined
|
||||
- a flag may appear in multiple groups
|
||||
- a group may contain any number of flags
|
||||
|
||||
## Positional and Custom Arguments
|
||||
|
||||
Validation of positional arguments can be specified using the `Args` field
|
||||
of `Command`.
|
||||
|
||||
Validation of positional arguments can be specified using the `Args` field of `Command`.
|
||||
The following validators are built in:
|
||||
|
||||
- `NoArgs` - the command will report an error if there are any positional args.
|
||||
- `ArbitraryArgs` - the command will accept any args.
|
||||
- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.
|
||||
- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
|
||||
- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
|
||||
- `ExactArgs(int)` - the command will 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)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
|
||||
- `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities).
|
||||
- Number of arguments:
|
||||
- `NoArgs` - report an error if there are any positional args.
|
||||
- `ArbitraryArgs` - accept any number of args.
|
||||
- `MinimumNArgs(int)` - report an error if less than N positional args are provided.
|
||||
- `MaximumNArgs(int)` - report an error if more than N positional args are provided.
|
||||
- `ExactArgs(int)` - report an error if there are not exactly N positional args.
|
||||
- `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.
|
||||
- Content of the arguments:
|
||||
- `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: cobra.MatchAll(cobra.ExactArgs(2), cobra.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
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return errors.New("requires a color argument")
|
||||
// Optionally run one of the validators provided by cobra
|
||||
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
// Run the custom validation logic
|
||||
if myapp.IsValidColor(args[0]) {
|
||||
return nil
|
||||
}
|
||||
|
@ -346,7 +430,7 @@ by not providing a 'Run' for the 'rootCmd'.
|
|||
|
||||
We have only defined one flag for a single command.
|
||||
|
||||
More documentation about flags is available at https://github.com/spf13/pflag
|
||||
More documentation about flags is available at https://github.com/spf13/pflag.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
@ -405,7 +489,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
|
||||
|
||||
|
@ -420,37 +504,47 @@ create' is called. Every command will automatically have the '--help' flag adde
|
|||
The following output is automatically generated by Cobra. Nothing beyond the
|
||||
command and flag definitions are needed.
|
||||
|
||||
$ cobra help
|
||||
```console
|
||||
$ cobra-cli help
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.
|
||||
|
||||
Usage:
|
||||
cobra [command]
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration (default true)
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
Use "cobra-cli [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
Help is just a command like any other. There is no special logic or behavior
|
||||
around it. In fact, you can provide your own if you want.
|
||||
|
||||
### Grouping commands in help
|
||||
|
||||
Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly
|
||||
defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element
|
||||
of that subcommand. The groups will appear in the help output in the same order as they are defined using different
|
||||
calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using
|
||||
`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.
|
||||
|
||||
### Defining your own help
|
||||
|
||||
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
|
||||
cmd.SetHelpCommand(cmd *Command)
|
||||
|
@ -460,6 +554,9 @@ cmd.SetHelpTemplate(s string)
|
|||
|
||||
The latter two will also apply to any children commands.
|
||||
|
||||
Note that templates specified with `SetHelpTemplate` are evaluated using
|
||||
`text/template` which can increase the size of the compiled executable.
|
||||
|
||||
## Usage Message
|
||||
|
||||
When the user provides an invalid flag or invalid command, Cobra responds by
|
||||
|
@ -469,26 +566,30 @@ showing the user the 'usage'.
|
|||
You may recognize this from the help above. That's because the default help
|
||||
embeds the usage as part of its output.
|
||||
|
||||
$ cobra --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra [command]
|
||||
```console
|
||||
$ cobra-cli --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration (default true)
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
### Defining your own usage
|
||||
|
||||
You can provide your own usage function or template for Cobra to use.
|
||||
Like help, the function and template are overridable through public methods:
|
||||
|
||||
|
@ -497,6 +598,9 @@ cmd.SetUsageFunc(f func(*Command) error)
|
|||
cmd.SetUsageTemplate(s string)
|
||||
```
|
||||
|
||||
Note that templates specified with `SetUsageTemplate` are evaluated using
|
||||
`text/template` which can increase the size of the compiled executable.
|
||||
|
||||
## Version Flag
|
||||
|
||||
Cobra adds a top-level '--version' flag if the Version field is set on the root command.
|
||||
|
@ -504,9 +608,18 @@ Running an application with the '--version' flag will print the version to stdou
|
|||
the version template. The template can be customized using the
|
||||
`cmd.SetVersionTemplate(s string)` function.
|
||||
|
||||
Note that templates specified with `SetVersionTemplate` are evaluated using
|
||||
`text/template` which can increase the size of the compiled executable.
|
||||
|
||||
## Error Message Prefix
|
||||
|
||||
Cobra prints an error message when receiving a non-nil error value.
|
||||
The default error message is `Error: <error contents>`.
|
||||
The Prefix, `Error:` can be customized using the `cmd.SetErrPrefix(s string)` function.
|
||||
|
||||
## PreRun and PostRun Hooks
|
||||
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. The `*PreRun` and `*PostRun` functions will only be executed if the `Run` function of the current command has been declared. These functions are run in the following order:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
|
@ -589,11 +702,15 @@ Inside subCmd PostRun with args: [arg1 arg2]
|
|||
Inside subCmd PersistentPostRun with args: [arg1 arg2]
|
||||
```
|
||||
|
||||
By default, only the first persistent hook found in the command chain is executed.
|
||||
That is why in the above output, the `rootCmd PersistentPostRun` was not called for a child command.
|
||||
Set `EnableTraverseRunHooks` global variable to `true` if you want to execute all parents' persistent hooks.
|
||||
|
||||
## Suggestions when "unknown command" happens
|
||||
|
||||
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
|
||||
|
||||
```
|
||||
```console
|
||||
$ hugo srever
|
||||
Error: unknown command "srever" for "hugo"
|
||||
|
||||
|
@ -603,7 +720,7 @@ Did you mean this?
|
|||
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:
|
||||
|
||||
|
@ -617,9 +734,10 @@ or
|
|||
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:
|
||||
|
||||
```
|
||||
```console
|
||||
$ kubectl remove
|
||||
Error: unknown command "remove" for "kubectl"
|
||||
|
||||
|
@ -631,8 +749,71 @@ Run 'kubectl help' for usage.
|
|||
|
||||
## Generating documentation for your command
|
||||
|
||||
Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
|
||||
Cobra can generate documentation based on subcommands, flags, etc.
|
||||
Read more about it in the [docs generation documentation](docgen/_index.md).
|
||||
|
||||
## 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](completions/_index.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).
|
||||
|
||||
## Creating a plugin
|
||||
|
||||
When creating a plugin for tools like *kubectl*, the executable is named
|
||||
`kubectl-myplugin`, but it is used as `kubectl myplugin`. To fix help
|
||||
messages and completions, annotate the root command with the
|
||||
`cobra.CommandDisplayNameAnnotation` annotation.
|
||||
|
||||
### Example kubectl plugin
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
rootCmd := &cobra.Command{
|
||||
Use: "kubectl-myplugin",
|
||||
Annotations: map[string]string{
|
||||
cobra.CommandDisplayNameAnnotation: "kubectl myplugin",
|
||||
},
|
||||
}
|
||||
subCmd := &cobra.Command{
|
||||
Use: "subcmd",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("kubectl myplugin subcmd")
|
||||
},
|
||||
}
|
||||
rootCmd.AddCommand(subCmd)
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
Example run as a kubectl plugin:
|
||||
|
||||
```console
|
||||
$ kubectl myplugin
|
||||
Usage:
|
||||
kubectl myplugin [command]
|
||||
|
||||
Available Commands:
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
subcmd
|
||||
|
||||
Flags:
|
||||
-h, --help help for kubectl myplugin
|
||||
|
||||
Use "kubectl myplugin [command] --help" for more information about a command.
|
||||
```
|
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2023 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 (
|
||||
|
@ -75,7 +89,8 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
|
|||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
|
||||
compdef _%[1]s %[1]s
|
||||
|
||||
# zsh completion for %-36[1]s -*- shell-script -*-
|
||||
|
||||
|
@ -94,8 +109,9 @@ _%[1]s()
|
|||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
local shellCompDirectiveKeepOrder=%[8]d
|
||||
|
||||
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
|
||||
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
|
||||
local -a completions
|
||||
|
||||
__%[1]s_debug "\n========= starting completion logic =========="
|
||||
|
@ -163,7 +179,24 @@ _%[1]s()
|
|||
return
|
||||
fi
|
||||
|
||||
local activeHelpMarker="%[9]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
local startIndex=$((${#activeHelpMarker}+1))
|
||||
local hasActiveHelp=0
|
||||
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 requested, completions are returned with a description.
|
||||
# The description is preceded by a TAB character.
|
||||
|
@ -171,7 +204,7 @@ _%[1]s()
|
|||
# We first need to escape any : as part of the completion itself.
|
||||
comp=${comp//:/\\:}
|
||||
|
||||
local tab=$(printf '\t')
|
||||
local tab="$(printf '\t')"
|
||||
comp=${comp//$tab/:}
|
||||
|
||||
__%[1]s_debug "Adding completion: ${comp}"
|
||||
|
@ -180,11 +213,27 @@ _%[1]s()
|
|||
fi
|
||||
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
|
||||
__%[1]s_debug "Activating nospace."
|
||||
noSpace="-S ''"
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
|
||||
__%[1]s_debug "Activating keep order."
|
||||
keepOrder="-V"
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local filteringCmd
|
||||
|
@ -220,7 +269,7 @@ _%[1]s()
|
|||
return $result
|
||||
else
|
||||
__%[1]s_debug "Calling _describe"
|
||||
if eval _describe "completions" completions $flagPrefix $noSpace; then
|
||||
if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then
|
||||
__%[1]s_debug "_describe found some completions"
|
||||
|
||||
# Return the success of having called _describe
|
||||
|
@ -254,5 +303,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then
|
|||
fi
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
|
33
zsh_completions_test.go
Normal file
33
zsh_completions_test.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
// Copyright 2013-2023 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))
|
||||
}
|
Loading…
Add table
Reference in a new issue