vendor: github.com/spf13/cobra v1.8.0 (#4182)
This commit is contained in:
commit
60e7e87889
31 changed files with 422 additions and 1878 deletions
4
go.mod
4
go.mod
|
@ -26,7 +26,7 @@ require (
|
|||
github.com/redis/go-redis/extra/redisotel/v9 v9.0.5
|
||||
github.com/redis/go-redis/v9 v9.1.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/spf13/cobra v1.8.0
|
||||
golang.org/x/crypto v0.14.0
|
||||
golang.org/x/oauth2 v0.7.0
|
||||
google.golang.org/api v0.114.0
|
||||
|
@ -55,7 +55,7 @@ require (
|
|||
github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.7.1 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.5 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/kr/pretty v0.2.1 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
|
|
10
go.sum
10
go.sum
|
@ -85,7 +85,7 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
|
|||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4=
|
||||
github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg=
|
||||
|
@ -206,8 +206,8 @@ github.com/hashicorp/golang-lru/arc/v2 v2.0.5/go.mod h1:ny6zBSQZi2JxIeYcv7kt2sH2
|
|||
github.com/hashicorp/golang-lru/v2 v2.0.5 h1:wW7h1TG88eUIJ2i69gaE3uNVtEPIagzhGvHgwfx2Vm4=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.5/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
|
||||
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
|
||||
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
|
||||
|
@ -299,8 +299,8 @@ github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrf
|
|||
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
|
||||
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
||||
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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
|
|
1
vendor/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
1
vendor/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
|
@ -1,3 +1,4 @@
|
|||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package mousetrap
|
||||
|
|
96
vendor/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
96
vendor/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
|
@ -1,79 +1,30 @@
|
|||
// +build windows
|
||||
// +build !go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// defined by the Win32 API
|
||||
th32cs_snapprocess uintptr = 0x2
|
||||
)
|
||||
|
||||
var (
|
||||
kernel = syscall.MustLoadDLL("kernel32.dll")
|
||||
CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
|
||||
Process32First = kernel.MustFindProc("Process32FirstW")
|
||||
Process32Next = kernel.MustFindProc("Process32NextW")
|
||||
)
|
||||
|
||||
// ProcessEntry32 structure defined by the Win32 API
|
||||
type processEntry32 struct {
|
||||
dwSize uint32
|
||||
cntUsage uint32
|
||||
th32ProcessID uint32
|
||||
th32DefaultHeapID int
|
||||
th32ModuleID uint32
|
||||
cntThreads uint32
|
||||
th32ParentProcessID uint32
|
||||
pcPriClassBase int32
|
||||
dwFlags uint32
|
||||
szExeFile [syscall.MAX_PATH]uint16
|
||||
}
|
||||
|
||||
func getProcessEntry(pid int) (pe *processEntry32, err error) {
|
||||
snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
|
||||
if snapshot == uintptr(syscall.InvalidHandle) {
|
||||
err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
|
||||
return
|
||||
}
|
||||
defer syscall.CloseHandle(syscall.Handle(snapshot))
|
||||
|
||||
var processEntry processEntry32
|
||||
processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
|
||||
ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32First: %v", e1)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
if processEntry.th32ProcessID == uint32(pid) {
|
||||
pe = &processEntry
|
||||
return
|
||||
}
|
||||
|
||||
ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32Next: %v", e1)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getppid() (pid int, err error) {
|
||||
pe, err := getProcessEntry(os.Getpid())
|
||||
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
||||
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(snapshot)
|
||||
var procEntry syscall.ProcessEntry32
|
||||
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
||||
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for {
|
||||
if procEntry.ProcessID == uint32(pid) {
|
||||
return &procEntry, nil
|
||||
}
|
||||
err = syscall.Process32Next(snapshot, &procEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
pid = int(pe.th32ParentProcessID)
|
||||
return
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
|
@ -83,16 +34,9 @@ func getppid() (pid int, err error) {
|
|||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
ppid, err := getppid()
|
||||
pe, err := getProcessEntry(syscall.Getppid())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pe, err := getProcessEntry(ppid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
name := syscall.UTF16ToString(pe.szExeFile[:])
|
||||
return name == "explorer.exe"
|
||||
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
||||
}
|
||||
|
|
46
vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
46
vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
|
@ -1,46 +0,0 @@
|
|||
// +build windows
|
||||
// +build go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
||||
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(snapshot)
|
||||
var procEntry syscall.ProcessEntry32
|
||||
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
||||
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for {
|
||||
if procEntry.ProcessID == uint32(pid) {
|
||||
return &procEntry, nil
|
||||
}
|
||||
err = syscall.Process32Next(snapshot, &procEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
pe, err := getProcessEntry(os.Getppid())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
||||
}
|
10
vendor/github.com/spf13/cobra/.golangci.yml
generated
vendored
10
vendor/github.com/spf13/cobra/.golangci.yml
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
# Copyright 2013-2022 The Cobra Authors
|
||||
# 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.
|
||||
|
@ -19,7 +19,7 @@ linters:
|
|||
disable-all: true
|
||||
enable:
|
||||
#- bodyclose
|
||||
- deadcode
|
||||
# - deadcode ! deprecated since v1.49.0; replaced by 'unused'
|
||||
#- depguard
|
||||
#- dogsled
|
||||
#- dupl
|
||||
|
@ -51,12 +51,12 @@ linters:
|
|||
#- rowserrcheck
|
||||
#- scopelint
|
||||
#- staticcheck
|
||||
- structcheck
|
||||
#- structcheck ! deprecated since v1.49.0; replaced by 'unused'
|
||||
#- stylecheck
|
||||
#- typecheck
|
||||
- unconvert
|
||||
#- unparam
|
||||
#- unused
|
||||
- varcheck
|
||||
- unused
|
||||
# - varcheck ! deprecated since v1.49.0; replaced by 'unused'
|
||||
#- whitespace
|
||||
fast: false
|
||||
|
|
8
vendor/github.com/spf13/cobra/Makefile
generated
vendored
8
vendor/github.com/spf13/cobra/Makefile
generated
vendored
|
@ -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 install github.com/kyoh86/richgo@latest")
|
||||
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:
|
||||
|
|
12
vendor/github.com/spf13/cobra/README.md
generated
vendored
12
vendor/github.com/spf13/cobra/README.md
generated
vendored
|
@ -1,12 +1,12 @@
|
|||
![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
|
||||
![cobra logo](assets/CobraMain.png)
|
||||
|
||||
Cobra is a library for creating powerful modern CLI applications.
|
||||
|
||||
Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
|
||||
[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
|
||||
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
|
||||
name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.
|
||||
|
||||
[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
|
||||
[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
|
||||
[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)
|
||||
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
|
||||
[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
|
||||
|
@ -80,7 +80,7 @@ which maintains the same interface while adding POSIX compliance.
|
|||
|
||||
# Installing
|
||||
Using Cobra is easy. First, use `go get` to install the latest version
|
||||
of the library.
|
||||
of the library.
|
||||
|
||||
```
|
||||
go get -u github.com/spf13/cobra@latest
|
||||
|
@ -105,8 +105,8 @@ go install github.com/spf13/cobra-cli@latest
|
|||
|
||||
For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
|
||||
|
||||
For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).
|
||||
For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md).
|
||||
|
||||
# License
|
||||
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)
|
||||
|
|
12
vendor/github.com/spf13/cobra/active_help.go
generated
vendored
12
vendor/github.com/spf13/cobra/active_help.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -17,6 +17,7 @@ package cobra
|
|||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
@ -29,6 +30,8 @@ const (
|
|||
activeHelpGlobalDisable = "0"
|
||||
)
|
||||
|
||||
var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
|
||||
|
||||
// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
|
||||
// Such strings will be processed by the completion script and will be shown as ActiveHelp
|
||||
// to the user.
|
||||
|
@ -42,7 +45,7 @@ func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
|
|||
|
||||
// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
|
||||
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
|
||||
// case, with all - replaced by _.
|
||||
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
|
||||
// is set to "0".
|
||||
func GetActiveHelpConfig(cmd *Command) string {
|
||||
|
@ -55,9 +58,10 @@ func GetActiveHelpConfig(cmd *Command) string {
|
|||
|
||||
// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
|
||||
// variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
|
||||
// root command in upper case, with all - replaced by _.
|
||||
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
|
||||
func activeHelpEnvVar(name string) string {
|
||||
// This format should not be changed: users will be using it explicitly.
|
||||
activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
|
||||
return strings.ReplaceAll(activeHelpEnvVar, "-", "_")
|
||||
activeHelpEnvVar = activeHelpEnvVarPrefixSubstRegexp.ReplaceAllString(activeHelpEnvVar, "_")
|
||||
return activeHelpEnvVar
|
||||
}
|
||||
|
|
157
vendor/github.com/spf13/cobra/active_help.md
generated
vendored
157
vendor/github.com/spf13/cobra/active_help.md
generated
vendored
|
@ -1,157 +0,0 @@
|
|||
# Active Help
|
||||
|
||||
Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion.
|
||||
|
||||
For example,
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding.
|
||||
|
||||
bash-5.1$ bin/helm package [tab]
|
||||
Please specify the path to the chart to package
|
||||
|
||||
bash-5.1$ bin/helm package [tab][tab]
|
||||
bin/ internal/ scripts/ pkg/ testdata/
|
||||
```
|
||||
|
||||
**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.
|
||||
## Supported shells
|
||||
|
||||
Active Help is currently only supported for the following shells:
|
||||
- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.
|
||||
- Zsh
|
||||
|
||||
## Adding Active Help messages
|
||||
|
||||
As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md).
|
||||
|
||||
Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.
|
||||
|
||||
### Active Help for nouns
|
||||
|
||||
Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "add [NAME] [URL]",
|
||||
Short: "add a chart repository",
|
||||
Args: require.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return addRepo(args)
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
var comps []string
|
||||
if len(args) == 0 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
} else if len(args) == 1 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
|
||||
} else {
|
||||
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
|
||||
}
|
||||
return comps, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior:
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana [tab]
|
||||
You must specify the URL for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
|
||||
This command does not take any more arguments
|
||||
```
|
||||
**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.
|
||||
|
||||
### Active Help for flags
|
||||
|
||||
Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:
|
||||
```go
|
||||
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 2 {
|
||||
return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return compVersionFlag(args[1], toComplete)
|
||||
})
|
||||
```
|
||||
The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.
|
||||
```
|
||||
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
|
||||
You must first specify the chart to install before the --version flag can be completed
|
||||
|
||||
bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
|
||||
2.0.1 2.0.2 2.0.3
|
||||
```
|
||||
|
||||
## User control of Active Help
|
||||
|
||||
You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.
|
||||
Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.
|
||||
|
||||
The way to configure Active Help is to use the program's Active Help environment
|
||||
variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your
|
||||
program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever
|
||||
Active Help configuration values are supported by the program.
|
||||
|
||||
For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user
|
||||
would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.
|
||||
|
||||
For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the
|
||||
Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages
|
||||
should or should not be added (instead of reading the environment variable directly).
|
||||
|
||||
For example:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
|
||||
|
||||
var comps []string
|
||||
if len(args) == 0 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
}
|
||||
} else if len(args) == 1 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
|
||||
}
|
||||
} else {
|
||||
if activeHelpLevel == "local" {
|
||||
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
|
||||
}
|
||||
}
|
||||
return comps, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
```
|
||||
**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.
|
||||
|
||||
**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.
|
||||
|
||||
**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string.
|
||||
## Active Help with Cobra's default completion command
|
||||
|
||||
Cobra provides a default `completion` command for programs that wish to use it.
|
||||
When using the default `completion` command, Active Help is configurable in the same
|
||||
fashion as described above using environment variables. You may wish to document this in more
|
||||
details for your users.
|
||||
|
||||
## Debugging Active Help
|
||||
|
||||
Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details.
|
||||
|
||||
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
|
||||
```
|
||||
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
_activeHelp_ WARNING: cannot re-use a name that is still in use
|
||||
:0
|
||||
Completion ended with directive: ShellCompDirectiveDefault
|
||||
|
||||
$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
:0
|
||||
Completion ended with directive: ShellCompDirectiveDefault
|
||||
```
|
4
vendor/github.com/spf13/cobra/args.go
generated
vendored
4
vendor/github.com/spf13/cobra/args.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -21,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
|
||||
|
|
6
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
6
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -85,7 +85,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
local out requestComp lastParam lastChar comp directive args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
|
||||
args=("${words[@]:1}")
|
||||
# Disable ActiveHelp which is not supported for bash completion v1
|
||||
requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"
|
||||
|
@ -532,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()
|
||||
|
|
93
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
93
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
|
@ -1,93 +0,0 @@
|
|||
# Generating Bash Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
||||
## Bash legacy dynamic completions
|
||||
|
||||
For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution.
|
||||
|
||||
**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own.
|
||||
|
||||
The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions.
|
||||
|
||||
Some code that works in kubernetes:
|
||||
|
||||
```bash
|
||||
const (
|
||||
bash_completion_func = `__kubectl_parse_get()
|
||||
{
|
||||
local kubectl_output out
|
||||
if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
|
||||
out=($(echo "${kubectl_output}" | awk '{print $1}'))
|
||||
COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_get_resource()
|
||||
{
|
||||
if [[ ${#nouns[@]} -eq 0 ]]; then
|
||||
return 1
|
||||
fi
|
||||
__kubectl_parse_get ${nouns[${#nouns[@]} -1]}
|
||||
if [[ $? -eq 0 ]]; then
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_custom_func() {
|
||||
case ${last_command} in
|
||||
kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
|
||||
__kubectl_get_resource
|
||||
return
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
`)
|
||||
```
|
||||
|
||||
And then I set that in my command definition:
|
||||
|
||||
```go
|
||||
cmds := &cobra.Command{
|
||||
Use: "kubectl",
|
||||
Short: "kubectl controls the Kubernetes cluster manager",
|
||||
Long: `kubectl controls the Kubernetes cluster manager.
|
||||
|
||||
Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
|
||||
Run: runHelp,
|
||||
BashCompletionFunction: bash_completion_func,
|
||||
}
|
||||
```
|
||||
|
||||
The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`__<command-use>_custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
|
||||
|
||||
Similarly, for flags:
|
||||
|
||||
```go
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "namespace",
|
||||
Usage: usage,
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`
|
||||
value, e.g.:
|
||||
|
||||
```bash
|
||||
__kubectl_get_namespaces()
|
||||
{
|
||||
local template
|
||||
template="{{ range .items }}{{ .metadata.name }} {{ end }}"
|
||||
local kubectl_out
|
||||
if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
|
||||
COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
```
|
73
vendor/github.com/spf13/cobra/bash_completionsV2.go
generated
vendored
73
vendor/github.com/spf13/cobra/bash_completionsV2.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -38,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
|
||||
}
|
||||
|
@ -57,7 +57,7 @@ __%[1]s_get_completion_results() {
|
|||
local requestComp lastParam lastChar args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
|
||||
args=("${words[@]:1}")
|
||||
requestComp="${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
|
@ -65,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"
|
||||
|
@ -75,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
|
||||
|
||||
|
@ -87,7 +87,7 @@ __%[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
|
||||
|
@ -101,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
|
||||
|
@ -130,7 +144,7 @@ __%[1]s_process_completion_results() {
|
|||
local activeHelp=()
|
||||
__%[1]s_extract_activeHelp
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
|
||||
# File extension filtering
|
||||
local fullFilter filter filteringCmd
|
||||
|
||||
|
@ -143,13 +157,12 @@ __%[1]s_process_completion_results() {
|
|||
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" "${completions[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
|
||||
|
@ -164,7 +177,7 @@ __%[1]s_process_completion_results() {
|
|||
__%[1]s_handle_special_char "$cur" =
|
||||
|
||||
# Print the activeHelp statements before we finish
|
||||
if [ ${#activeHelp[*]} -ne 0 ]; then
|
||||
if ((${#activeHelp[*]} != 0)); then
|
||||
printf "\n";
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
printf "\n"
|
||||
|
@ -184,21 +197,21 @@ __%[1]s_process_completion_results() {
|
|||
# Separate activeHelp lines from real completions.
|
||||
# Fills the $activeHelp and $completions arrays.
|
||||
__%[1]s_extract_activeHelp() {
|
||||
local activeHelpMarker="%[8]s"
|
||||
local activeHelpMarker="%[9]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then
|
||||
if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
|
||||
comp=${comp:endIndex}
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
if [ -n "$comp" ]; then
|
||||
if [[ -n $comp ]]; then
|
||||
activeHelp+=("$comp")
|
||||
fi
|
||||
else
|
||||
# Not an activeHelp line but a normal completion
|
||||
completions+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out}")
|
||||
done <<<"${out}"
|
||||
}
|
||||
|
||||
__%[1]s_handle_completion_types() {
|
||||
|
@ -254,7 +267,7 @@ __%[1]s_handle_standard_completion_case() {
|
|||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
|
||||
# If there is a single completion left, remove the description text
|
||||
if [ ${#COMPREPLY[*]} -eq 1 ]; then
|
||||
if ((${#COMPREPLY[*]} == 1)); then
|
||||
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
|
||||
comp="${COMPREPLY[0]%%%%$tab*}"
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
|
||||
|
@ -271,8 +284,8 @@ __%[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
|
||||
}
|
||||
|
@ -298,7 +311,7 @@ __%[1]s_format_comp_descriptions()
|
|||
|
||||
# Make sure we can fit a description of at least 8 characters
|
||||
# if we are to align the descriptions.
|
||||
if [[ $maxdesclength -gt 8 ]]; then
|
||||
if ((maxdesclength > 8)); then
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
for ((i = ${#comp} ; i < longest ; i++)); do
|
||||
comp+=" "
|
||||
|
@ -310,8 +323,8 @@ __%[1]s_format_comp_descriptions()
|
|||
|
||||
# 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
|
||||
if ((maxdesclength > 0)); then
|
||||
if ((${#desc} > maxdesclength)); then
|
||||
desc=${desc:0:$(( maxdesclength - 1 ))}
|
||||
desc+="…"
|
||||
fi
|
||||
|
@ -332,9 +345,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
|
||||
|
@ -361,7 +374,7 @@ fi
|
|||
# ex: ts=4 sw=4 et filetype=sh
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
||||
|
|
19
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
19
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -43,12 +43,13 @@ var initializers []func()
|
|||
var finalizers []func()
|
||||
|
||||
const (
|
||||
defaultPrefixMatching = false
|
||||
defaultCommandSorting = true
|
||||
defaultCaseInsensitive = false
|
||||
defaultPrefixMatching = false
|
||||
defaultCommandSorting = true
|
||||
defaultCaseInsensitive = false
|
||||
defaultTraverseRunHooks = false
|
||||
)
|
||||
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = defaultPrefixMatching
|
||||
|
@ -60,6 +61,10 @@ var EnableCommandSorting = defaultCommandSorting
|
|||
// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
|
||||
var EnableCaseInsensitive = defaultCaseInsensitive
|
||||
|
||||
// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.
|
||||
// By default this is disabled, which means only the first run hook to be found is executed.
|
||||
var EnableTraverseRunHooks = defaultTraverseRunHooks
|
||||
|
||||
// MousetrapHelpText enables an information splash screen on Windows
|
||||
// if the CLI is started from explorer.exe.
|
||||
// To disable the mousetrap, just set this variable to blank string ("").
|
||||
|
@ -167,8 +172,8 @@ 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.
|
||||
|
|
123
vendor/github.com/spf13/cobra/command.go
generated
vendored
123
vendor/github.com/spf13/cobra/command.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -30,12 +30,15 @@ import (
|
|||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
|
||||
const (
|
||||
FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
|
||||
CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
|
||||
)
|
||||
|
||||
// FParseErrWhitelist configures Flag parse errors to be ignored
|
||||
type FParseErrWhitelist flag.ParseErrorsWhitelist
|
||||
|
||||
// Structure to manage groups for commands
|
||||
// Group Structure to manage groups for commands
|
||||
type Group struct {
|
||||
ID string
|
||||
Title string
|
||||
|
@ -47,7 +50,7 @@ type Group struct {
|
|||
// definition to ensure usability.
|
||||
type Command struct {
|
||||
// Use is the one-line usage message.
|
||||
// Recommended syntax is as follow:
|
||||
// Recommended syntax is as follows:
|
||||
// [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
|
||||
// ... indicates that you can specify multiple values for the previous argument.
|
||||
// | indicates mutually exclusive information. You can use the argument to the left of the separator or the
|
||||
|
@ -99,7 +102,7 @@ type Command struct {
|
|||
Deprecated string
|
||||
|
||||
// Annotations are key/value pairs that can be used by applications to identify or
|
||||
// group commands.
|
||||
// group commands or set special options.
|
||||
Annotations map[string]string
|
||||
|
||||
// Version defines the version for this command. If this value is non-empty and the command does not
|
||||
|
@ -115,6 +118,8 @@ type Command struct {
|
|||
// * PostRun()
|
||||
// * PersistentPostRun()
|
||||
// All functions get the same args, the arguments after the command name.
|
||||
// The *PreRun and *PostRun functions will only be executed if the Run function of the current
|
||||
// command has been declared.
|
||||
//
|
||||
// PersistentPreRun: children of this command will inherit and execute.
|
||||
PersistentPreRun func(cmd *Command, args []string)
|
||||
|
@ -181,6 +186,9 @@ type Command struct {
|
|||
// versionTemplate is the version template defined by user.
|
||||
versionTemplate string
|
||||
|
||||
// errPrefix is the error message prefix defined by user.
|
||||
errPrefix string
|
||||
|
||||
// inReader is a reader defined by the user that replaces stdin
|
||||
inReader io.Reader
|
||||
// outWriter is a writer defined by the user that replaces stdout
|
||||
|
@ -321,7 +329,7 @@ func (c *Command) SetHelpCommand(cmd *Command) {
|
|||
c.helpCommand = cmd
|
||||
}
|
||||
|
||||
// SetHelpCommandGroup sets the group id of the help command.
|
||||
// SetHelpCommandGroupID sets the group id of the help command.
|
||||
func (c *Command) SetHelpCommandGroupID(groupID string) {
|
||||
if c.helpCommand != nil {
|
||||
c.helpCommand.GroupID = groupID
|
||||
|
@ -330,7 +338,7 @@ func (c *Command) SetHelpCommandGroupID(groupID string) {
|
|||
c.helpCommandGroupID = groupID
|
||||
}
|
||||
|
||||
// SetCompletionCommandGroup sets the group id of the completion command.
|
||||
// SetCompletionCommandGroupID sets the group id of the completion command.
|
||||
func (c *Command) SetCompletionCommandGroupID(groupID string) {
|
||||
// completionCommandGroupID is used if no completion command is defined by the user
|
||||
c.Root().completionCommandGroupID = groupID
|
||||
|
@ -346,6 +354,11 @@ func (c *Command) SetVersionTemplate(s string) {
|
|||
c.versionTemplate = s
|
||||
}
|
||||
|
||||
// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.
|
||||
func (c *Command) SetErrPrefix(s string) {
|
||||
c.errPrefix = s
|
||||
}
|
||||
|
||||
// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
|
||||
// The user should not have a cyclic dependency on commands.
|
||||
func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
|
||||
|
@ -595,6 +608,18 @@ func (c *Command) VersionTemplate() string {
|
|||
`
|
||||
}
|
||||
|
||||
// ErrPrefix return error message prefix for the command
|
||||
func (c *Command) ErrPrefix() string {
|
||||
if c.errPrefix != "" {
|
||||
return c.errPrefix
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.ErrPrefix()
|
||||
}
|
||||
return "Error:"
|
||||
}
|
||||
|
||||
func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
||||
flag := fs.Lookup(name)
|
||||
if flag == nil {
|
||||
|
@ -655,20 +680,44 @@ Loop:
|
|||
|
||||
// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
|
||||
// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
|
||||
func argsMinusFirstX(args []string, x string) []string {
|
||||
for i, y := range args {
|
||||
if x == y {
|
||||
ret := []string{}
|
||||
ret = append(ret, args[:i]...)
|
||||
ret = append(ret, args[i+1:]...)
|
||||
return ret
|
||||
// Special care needs to be taken not to remove a flag value.
|
||||
func (c *Command) argsMinusFirstX(args []string, x string) []string {
|
||||
if len(args) == 0 {
|
||||
return args
|
||||
}
|
||||
c.mergePersistentFlags()
|
||||
flags := c.Flags()
|
||||
|
||||
Loop:
|
||||
for pos := 0; pos < len(args); pos++ {
|
||||
s := args[pos]
|
||||
switch {
|
||||
case s == "--":
|
||||
// -- means we have reached the end of the parseable args. Break out of the loop now.
|
||||
break Loop
|
||||
case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
|
||||
fallthrough
|
||||
case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
|
||||
// This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip
|
||||
// over the next arg, because that is the value of this flag.
|
||||
pos++
|
||||
continue
|
||||
case !strings.HasPrefix(s, "-"):
|
||||
// This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,
|
||||
// return the args, excluding the one at this position.
|
||||
if s == x {
|
||||
ret := []string{}
|
||||
ret = append(ret, args[:pos]...)
|
||||
ret = append(ret, args[pos+1:]...)
|
||||
return ret
|
||||
}
|
||||
}
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func isFlagArg(arg string) bool {
|
||||
return ((len(arg) >= 3 && arg[1] == '-') ||
|
||||
return ((len(arg) >= 3 && arg[0:2] == "--") ||
|
||||
(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
|
||||
}
|
||||
|
||||
|
@ -686,7 +735,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) {
|
|||
|
||||
cmd := c.findNext(nextSubCmd)
|
||||
if cmd != nil {
|
||||
return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
|
||||
return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))
|
||||
}
|
||||
return c, innerArgs
|
||||
}
|
||||
|
@ -728,7 +777,9 @@ func (c *Command) findNext(next string) *Command {
|
|||
}
|
||||
|
||||
if len(matches) == 1 {
|
||||
return matches[0]
|
||||
// Temporarily disable gosec G602, which produces a false positive.
|
||||
// See https://github.com/securego/gosec/issues/1005.
|
||||
return matches[0] // #nosec G602
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@ -886,15 +937,31 @@ func (c *Command) execute(a []string) (err error) {
|
|||
return err
|
||||
}
|
||||
|
||||
parents := make([]*Command, 0, 5)
|
||||
for p := c; p != nil; p = p.Parent() {
|
||||
if EnableTraverseRunHooks {
|
||||
// When EnableTraverseRunHooks is set:
|
||||
// - Execute all persistent pre-runs from the root parent till this command.
|
||||
// - Execute all persistent post-runs from this command till the root parent.
|
||||
parents = append([]*Command{p}, parents...)
|
||||
} else {
|
||||
// Otherwise, execute only the first found persistent hook.
|
||||
parents = append(parents, p)
|
||||
}
|
||||
}
|
||||
for _, p := range parents {
|
||||
if p.PersistentPreRunE != nil {
|
||||
if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
break
|
||||
if !EnableTraverseRunHooks {
|
||||
break
|
||||
}
|
||||
} else if p.PersistentPreRun != nil {
|
||||
p.PersistentPreRun(c, argWoFlags)
|
||||
break
|
||||
if !EnableTraverseRunHooks {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.PreRunE != nil {
|
||||
|
@ -931,10 +998,14 @@ func (c *Command) execute(a []string) (err error) {
|
|||
if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
break
|
||||
if !EnableTraverseRunHooks {
|
||||
break
|
||||
}
|
||||
} else if p.PersistentPostRun != nil {
|
||||
p.PersistentPostRun(c, argWoFlags)
|
||||
break
|
||||
if !EnableTraverseRunHooks {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1024,7 +1095,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
c = cmd
|
||||
}
|
||||
if !c.SilenceErrors {
|
||||
c.PrintErrln("Error:", err.Error())
|
||||
c.PrintErrln(c.ErrPrefix(), err.Error())
|
||||
c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
|
||||
}
|
||||
return c, err
|
||||
|
@ -1053,7 +1124,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
// If root command has SilenceErrors flagged,
|
||||
// all subcommands should respect it
|
||||
if !cmd.SilenceErrors && !c.SilenceErrors {
|
||||
c.PrintErrln("Error:", err.Error())
|
||||
c.PrintErrln(cmd.ErrPrefix(), err.Error())
|
||||
}
|
||||
|
||||
// If root command has SilenceUsage flagged,
|
||||
|
@ -1272,7 +1343,7 @@ func (c *Command) AllChildCommandsHaveGroup() bool {
|
|||
return true
|
||||
}
|
||||
|
||||
// ContainGroups return if groupID exists in the list of command groups.
|
||||
// ContainsGroup return if groupID exists in the list of command groups.
|
||||
func (c *Command) ContainsGroup(groupID string) bool {
|
||||
for _, x := range c.commandgroups {
|
||||
if x.ID == groupID {
|
||||
|
@ -1356,6 +1427,9 @@ func (c *Command) CommandPath() string {
|
|||
if c.HasParent() {
|
||||
return c.Parent().CommandPath() + " " + c.Name()
|
||||
}
|
||||
if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
|
||||
return displayName
|
||||
}
|
||||
return c.Name()
|
||||
}
|
||||
|
||||
|
@ -1378,6 +1452,7 @@ func (c *Command) UseLine() string {
|
|||
|
||||
// DebugFlags used to determine which flags have been assigned to which commands
|
||||
// and which persist.
|
||||
// nolint:goconst
|
||||
func (c *Command) DebugFlags() {
|
||||
c.Println("DebugFlags called on", c.Name())
|
||||
var debugflags func(*Command)
|
||||
|
|
2
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
2
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
|
2
vendor/github.com/spf13/cobra/command_win.go
generated
vendored
2
vendor/github.com/spf13/cobra/command_win.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
|
42
vendor/github.com/spf13/cobra/completions.go
generated
vendored
42
vendor/github.com/spf13/cobra/completions.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -77,6 +77,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.
|
||||
|
@ -141,6 +145,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) (func(*Command, []string, string) ([]string, ShellCompDirective), 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
|
||||
|
@ -159,6 +177,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")
|
||||
}
|
||||
|
@ -169,7 +190,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),
|
||||
|
@ -276,9 +297,13 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
|
||||
// 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.
|
||||
finalCmd.InitDefaultHelpFlag()
|
||||
finalCmd.InitDefaultVersionFlag()
|
||||
// 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
|
||||
|
@ -382,6 +407,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)
|
||||
})
|
||||
|
@ -727,7 +757,7 @@ to enable it. You can execute the following once:
|
|||
|
||||
To load completions in your current shell session:
|
||||
|
||||
source <(%[1]s completion zsh); compdef _%[1]s %[1]s
|
||||
source <(%[1]s completion zsh)
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
|
|
78
vendor/github.com/spf13/cobra/fish_completions.go
generated
vendored
78
vendor/github.com/spf13/cobra/fish_completions.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -53,7 +53,7 @@ function __%[1]s_perform_completion
|
|||
__%[1]s_debug "last arg: $lastArg"
|
||||
|
||||
# Disable ActiveHelp which is not supported for fish shell
|
||||
set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
|
||||
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)
|
||||
|
@ -89,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
|
||||
|
@ -99,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"
|
||||
|
@ -205,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, activeHelpEnvVar(name)))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
// GenFishCompletion generates fish completion file and writes to the passed writer.
|
||||
|
|
4
vendor/github.com/spf13/cobra/fish_completions.md
generated
vendored
4
vendor/github.com/spf13/cobra/fish_completions.md
generated
vendored
|
@ -1,4 +0,0 @@
|
|||
## Generating Fish Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
70
vendor/github.com/spf13/cobra/flag_groups.go
generated
vendored
70
vendor/github.com/spf13/cobra/flag_groups.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -24,6 +24,7 @@ import (
|
|||
|
||||
const (
|
||||
requiredAsGroup = "cobra_annotation_required_if_others_set"
|
||||
oneRequired = "cobra_annotation_one_required"
|
||||
mutuallyExclusive = "cobra_annotation_mutually_exclusive"
|
||||
)
|
||||
|
||||
|
@ -43,6 +44,22 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
|
|||
}
|
||||
}
|
||||
|
||||
// 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, oneRequired, append(f.Annotations[oneRequired], 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) {
|
||||
|
@ -59,7 +76,7 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
|
|||
}
|
||||
}
|
||||
|
||||
// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the
|
||||
// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the
|
||||
// first error encountered.
|
||||
func (c *Command) ValidateFlagGroups() error {
|
||||
if c.DisableFlagParsing {
|
||||
|
@ -71,15 +88,20 @@ func (c *Command) ValidateFlagGroups() error {
|
|||
// 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, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, 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
|
||||
}
|
||||
|
@ -142,6 +164,27 @@ func validateRequiredFlagGroups(data map[string]map[string]bool) error {
|
|||
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 {
|
||||
|
@ -176,6 +219,7 @@ func sortedKeys(m map[string]map[string]bool) []string {
|
|||
|
||||
// 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() {
|
||||
|
@ -185,9 +229,11 @@ func (c *Command) enforceFlagGroupsForCompletion() {
|
|||
|
||||
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, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
|
@ -204,6 +250,26 @@ func (c *Command) enforceFlagGroupsForCompletion() {
|
|||
}
|
||||
}
|
||||
|
||||
// If none of the flags of a one-required group are present, we make all the flags
|
||||
// of that group required so that the shell completion suggests them automatically
|
||||
for flagList, flagnameAndStatus := range oneRequiredGroupStatus {
|
||||
set := 0
|
||||
|
||||
for _, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
set++
|
||||
}
|
||||
}
|
||||
|
||||
// None of the flags of the group are set, mark all flags in the group
|
||||
// as required
|
||||
if set == 0 {
|
||||
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 {
|
||||
|
|
31
vendor/github.com/spf13/cobra/powershell_completions.go
generated
vendored
31
vendor/github.com/spf13/cobra/powershell_completions.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -47,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
|
||||
}
|
||||
|
||||
[scriptblock]$__%[2]sCompleterBlock = {
|
||||
[scriptblock]${__%[2]sCompleterBlock} = {
|
||||
param(
|
||||
$WordToComplete,
|
||||
$CommandAst,
|
||||
|
@ -77,6 +77,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
$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.
|
||||
|
@ -106,13 +107,22 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
# 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:%[9]s=0
|
||||
${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
|
||||
|
@ -137,7 +147,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
}
|
||||
|
||||
$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"
|
||||
|
@ -182,6 +192,11 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
}
|
||||
}
|
||||
|
||||
# we sort the values in ascending order by name if keep order isn't passed
|
||||
if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
|
||||
$Values = $Values | Sort-Object -Property Name
|
||||
}
|
||||
|
||||
if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
|
||||
__%[1]s_debug "ShellCompDirectiveNoFileComp is called"
|
||||
|
||||
|
@ -264,10 +279,10 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
}
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock}
|
||||
`, name, nameForVar, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {
|
||||
|
|
3
vendor/github.com/spf13/cobra/powershell_completions.md
generated
vendored
3
vendor/github.com/spf13/cobra/powershell_completions.md
generated
vendored
|
@ -1,3 +0,0 @@
|
|||
# Generating PowerShell Completions For Your Own cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.
|
60
vendor/github.com/spf13/cobra/projects_using_cobra.md
generated
vendored
60
vendor/github.com/spf13/cobra/projects_using_cobra.md
generated
vendored
|
@ -1,60 +0,0 @@
|
|||
## Projects using Cobra
|
||||
|
||||
- [Allero](https://github.com/allero-io/allero)
|
||||
- [Arduino CLI](https://github.com/arduino/arduino-cli)
|
||||
- [Bleve](https://blevesearch.com/)
|
||||
- [Cilium](https://cilium.io/)
|
||||
- [CloudQuery](https://github.com/cloudquery/cloudquery)
|
||||
- [CockroachDB](https://www.cockroachlabs.com/)
|
||||
- [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)
|
||||
- [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 Labeler](https://github.com/erdaltsksn/gh-label)
|
||||
- [Golangci-lint](https://golangci-lint.run)
|
||||
- [GopherJS](https://github.com/gopherjs/gopherjs)
|
||||
- [GoReleaser](https://goreleaser.com)
|
||||
- [Helm](https://helm.sh)
|
||||
- [Hugo](https://gohugo.io)
|
||||
- [Infracost](https://github.com/infracost/infracost)
|
||||
- [Istio](https://istio.io)
|
||||
- [Kool](https://github.com/kool-dev/kool)
|
||||
- [Kubernetes](https://kubernetes.io/)
|
||||
- [Kubescape](https://github.com/armosec/kubescape)
|
||||
- [KubeVirt](https://github.com/kubevirt/kubevirt)
|
||||
- [Linkerd](https://linkerd.io/)
|
||||
- [Mattermost-server](https://github.com/mattermost/mattermost-server)
|
||||
- [Mercure](https://mercure.rocks/)
|
||||
- [Meroxa CLI](https://github.com/meroxa/cli)
|
||||
- [Metal Stack CLI](https://github.com/metal-stack/metalctl)
|
||||
- [Moby (former Docker)](https://github.com/moby/moby)
|
||||
- [Moldy](https://github.com/Moldy-Community/moldy)
|
||||
- [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)](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)
|
||||
- [Skaffold](https://skaffold.dev/)
|
||||
- [Tendermint](https://github.com/tendermint/tendermint)
|
||||
- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
|
||||
- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)
|
||||
- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)
|
||||
- [Werf](https://werf.io/)
|
||||
- [ZITADEL](https://github.com/zitadel/zitadel)
|
2
vendor/github.com/spf13/cobra/shell_completions.go
generated
vendored
2
vendor/github.com/spf13/cobra/shell_completions.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
|
568
vendor/github.com/spf13/cobra/shell_completions.md
generated
vendored
568
vendor/github.com/spf13/cobra/shell_completions.md
generated
vendored
|
@ -1,568 +0,0 @@
|
|||
# Generating shell completions
|
||||
|
||||
Cobra can generate shell completions for multiple shells.
|
||||
The currently supported shells are:
|
||||
- Bash
|
||||
- Zsh
|
||||
- fish
|
||||
- PowerShell
|
||||
|
||||
Cobra will automatically provide your program with a fully functional `completion` command,
|
||||
similarly to how it provides the `help` command.
|
||||
|
||||
## Creating your own completion command
|
||||
|
||||
If you do not wish to use the default `completion` command, you can choose to
|
||||
provide your own, which will take precedence over the default one. (This also provides
|
||||
backwards-compatibility with programs that already have their own `completion` command.)
|
||||
|
||||
If you are using the `cobra-cli` generator,
|
||||
which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli),
|
||||
you can create a completion command by running
|
||||
|
||||
```bash
|
||||
cobra-cli add completion
|
||||
```
|
||||
and then modifying the generated `cmd/completion.go` file to look something like this
|
||||
(writing the shell script to stdout allows the most flexible use):
|
||||
|
||||
```go
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion [bash|zsh|fish|powershell]",
|
||||
Short: "Generate completion script",
|
||||
Long: fmt.Sprintf(`To load completions:
|
||||
|
||||
Bash:
|
||||
|
||||
$ source <(%[1]s completion bash)
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
# Linux:
|
||||
$ %[1]s completion bash > /etc/bash_completion.d/%[1]s
|
||||
# macOS:
|
||||
$ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
|
||||
|
||||
Zsh:
|
||||
|
||||
# If shell completion is not already enabled in your environment,
|
||||
# you will need to enable it. You can execute the following once:
|
||||
|
||||
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
|
||||
|
||||
# You will need to start a new shell for this setup to take effect.
|
||||
|
||||
fish:
|
||||
|
||||
$ %[1]s completion fish | source
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
|
||||
|
||||
PowerShell:
|
||||
|
||||
PS> %[1]s completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
# To load completions for every new session, run:
|
||||
PS> %[1]s completion powershell > %[1]s.ps1
|
||||
# and source this file from your PowerShell profile.
|
||||
`,cmd.Root().Name()),
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
|
||||
Args: cobra.ExactValidArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
switch args[0] {
|
||||
case "bash":
|
||||
cmd.Root().GenBashCompletion(os.Stdout)
|
||||
case "zsh":
|
||||
cmd.Root().GenZshCompletion(os.Stdout)
|
||||
case "fish":
|
||||
cmd.Root().GenFishCompletion(os.Stdout, true)
|
||||
case "powershell":
|
||||
cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
|
||||
}
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.
|
||||
|
||||
## Adapting the default completion command
|
||||
|
||||
Cobra provides a few options for the default `completion` command. To configure such options you must set
|
||||
the `CompletionOptions` field on the *root* command.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
To tell Cobra to completely disable descriptions for completions:
|
||||
```
|
||||
rootCmd.CompletionOptions.DisableDescriptions = true
|
||||
```
|
||||
|
||||
# Customizing completions
|
||||
|
||||
The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.
|
||||
|
||||
## Completion of nouns
|
||||
|
||||
### Static completion of nouns
|
||||
|
||||
Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.
|
||||
For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them.
|
||||
Some simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs = []string{ "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
Short: "Display one or many resources",
|
||||
Long: get_long,
|
||||
Example: get_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
cobra.CheckErr(RunGet(f, out, cmd, args))
|
||||
},
|
||||
ValidArgs: validArgs,
|
||||
}
|
||||
```
|
||||
|
||||
Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:
|
||||
|
||||
```bash
|
||||
$ kubectl get [tab][tab]
|
||||
node pod replicationcontroller service
|
||||
```
|
||||
|
||||
#### Aliases for nouns
|
||||
|
||||
If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go
|
||||
argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
ValidArgs: validArgs,
|
||||
ArgAliases: argAliases
|
||||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
$ kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of
|
||||
replication controllers following `rc`.
|
||||
|
||||
### Dynamic completion of nouns
|
||||
|
||||
In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.
|
||||
Simplified code from `helm status` looks like:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "status RELEASE_NAME",
|
||||
Short: "Display the status of the named release",
|
||||
Long: status_long,
|
||||
RunE: func(cmd *cobra.Command, args []string) {
|
||||
RunGet(args[0])
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
|
||||
Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like:
|
||||
|
||||
```bash
|
||||
$ helm status [tab][tab]
|
||||
harbor notary rook thanos
|
||||
```
|
||||
You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`
|
||||
```go
|
||||
// Indicates that the shell will perform its default behavior after completions
|
||||
// have been provided (this implies none of the other directives).
|
||||
ShellCompDirectiveDefault
|
||||
|
||||
// Indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError
|
||||
|
||||
// Indicates that the shell should not add a space after the completion,
|
||||
// even if there is a single completion provided.
|
||||
ShellCompDirectiveNoSpace
|
||||
|
||||
// Indicates that the shell should not provide file completion even when
|
||||
// no completion is provided.
|
||||
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
|
||||
// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
|
||||
// is a shortcut to using this directive explicitly.
|
||||
//
|
||||
ShellCompDirectiveFilterFileExt
|
||||
|
||||
// Indicates that only directory names should be provided in file completion.
|
||||
// For example:
|
||||
// return nil, 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
|
||||
//
|
||||
ShellCompDirectiveFilterDirs
|
||||
```
|
||||
|
||||
***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.
|
||||
|
||||
#### Debugging
|
||||
|
||||
Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:
|
||||
```bash
|
||||
$ helm __complete status har<ENTER>
|
||||
harbor
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command:
|
||||
```bash
|
||||
$ helm __complete status ""<ENTER>
|
||||
harbor
|
||||
notary
|
||||
rook
|
||||
thanos
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:
|
||||
```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.CompDebugln(msg string, printToStdErr bool)
|
||||
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and to stderr.
|
||||
cobra.CompError(msg string)
|
||||
cobra.CompErrorln(msg string)
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.
|
||||
|
||||
## Completions for flags
|
||||
|
||||
### Mark flags as required
|
||||
|
||||
Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so:
|
||||
|
||||
```go
|
||||
cmd.MarkFlagRequired("pod")
|
||||
cmd.MarkFlagRequired("container")
|
||||
```
|
||||
|
||||
and you'll get something like
|
||||
|
||||
```bash
|
||||
$ kubectl exec [tab][tab]
|
||||
-c --container= -p --pod=
|
||||
```
|
||||
|
||||
### Specify dynamic flag completion
|
||||
|
||||
As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.
|
||||
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
})
|
||||
```
|
||||
Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
|
||||
|
||||
```bash
|
||||
$ helm status --output [tab][tab]
|
||||
json table yaml
|
||||
```
|
||||
|
||||
#### Debugging
|
||||
|
||||
You can also easily debug your Go completion code for flags:
|
||||
```bash
|
||||
$ helm __complete status --output ""
|
||||
json
|
||||
table
|
||||
yaml
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above.
|
||||
|
||||
### Specify valid filename extensions for flags that take a filename
|
||||
|
||||
To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
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})
|
||||
```
|
||||
|
||||
### Limit flag completions to directory names
|
||||
|
||||
To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.MarkFlagDirname(flagName)
|
||||
```
|
||||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, 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
|
||||
})
|
||||
```
|
||||
### Descriptions for completions
|
||||
|
||||
Cobra provides support for completion descriptions. Such descriptions are supported for each shell
|
||||
(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)).
|
||||
For commands and flags, Cobra will provide the descriptions automatically, based on usage information.
|
||||
For example, using zsh:
|
||||
```
|
||||
$ helm s[tab]
|
||||
search -- search for a keyword in charts
|
||||
show -- show information of a chart
|
||||
status -- displays the status of the named release
|
||||
```
|
||||
while using fish:
|
||||
```
|
||||
$ 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:
|
||||
```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
|
||||
}}
|
||||
```
|
||||
or
|
||||
```go
|
||||
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
|
||||
```
|
||||
## Bash completions
|
||||
|
||||
### Dependencies
|
||||
|
||||
The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion))
|
||||
|
||||
### Aliases
|
||||
|
||||
You can also configure `bash` aliases for your program and they will also support completions.
|
||||
|
||||
```bash
|
||||
alias aliasname=origcommand
|
||||
complete -o default -F __start_origcommand aliasname
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$ aliasname <tab><tab>
|
||||
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.
|
||||
|
||||
### Bash completion V2
|
||||
|
||||
Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling
|
||||
`GenBashCompletion()` or `GenBashCompletionFile()`.
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
`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
|
||||
will provide the description automatically based on usage information. You can choose to make this option configurable by
|
||||
your users.
|
||||
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab][tab]
|
||||
search (search for a keyword in charts) status (display the status of the named release)
|
||||
show (show information of a chart)
|
||||
|
||||
# Without descriptions
|
||||
$ 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.
|
||||
## Zsh completions
|
||||
|
||||
Cobra supports native zsh completion generated from the root `cobra.Command`.
|
||||
The generated completion script should be put somewhere in your `$fpath` and be named
|
||||
`_<yourProgram>`. You will need to start a new shell for the completions to become available.
|
||||
|
||||
Zsh supports descriptions for completions. Cobra will provide the description automatically,
|
||||
based on usage information. Cobra provides a way to completely disable such descriptions by
|
||||
using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make
|
||||
this a configurable option to your users.
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab]
|
||||
search -- search for a keyword in charts
|
||||
show -- show information of a chart
|
||||
status -- displays the status of the named release
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
|
||||
### 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.
|
||||
|
||||
## fish completions
|
||||
|
||||
Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
* The following flag completion annotations are not supported and will be ignored for `fish`:
|
||||
* `BashCompFilenameExt` (filtering by file extension)
|
||||
* `BashCompSubdirsInDir` (filtering by directory)
|
||||
* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:
|
||||
* `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
|
||||
* `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
|
||||
* Similarly, the following completion directives are not supported and will be ignored for `fish`:
|
||||
* `ShellCompDirectiveFilterFileExt` (filtering by file extension)
|
||||
* `ShellCompDirectiveFilterDirs` (filtering by directory)
|
||||
|
||||
## PowerShell completions
|
||||
|
||||
Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
|
||||
The script is designed to support all three PowerShell completion modes:
|
||||
|
||||
* TabCompleteNext (default windows style - on each key press the next option is displayed)
|
||||
* Complete (works like bash)
|
||||
* MenuComplete (works like zsh)
|
||||
|
||||
You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.
|
||||
|
||||
Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
|
||||
|
||||
```
|
||||
# With descriptions and Mode 'Complete'
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
|
||||
# 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 for a keyword in charts
|
||||
|
||||
# Without descriptions
|
||||
$ 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
|
||||
|
||||
* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
* The following flag completion annotations are not supported and will be ignored for `powershell`:
|
||||
* `BashCompFilenameExt` (filtering by file extension)
|
||||
* `BashCompSubdirsInDir` (filtering by directory)
|
||||
* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:
|
||||
* `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
|
||||
* `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
|
||||
* Similarly, the following completion directives are not supported and will be ignored for `powershell`:
|
||||
* `ShellCompDirectiveFilterFileExt` (filtering by file extension)
|
||||
* `ShellCompDirectiveFilterDirs` (filtering by directory)
|
695
vendor/github.com/spf13/cobra/user_guide.md
generated
vendored
695
vendor/github.com/spf13/cobra/user_guide.md
generated
vendored
|
@ -1,695 +0,0 @@
|
|||
# User Guide
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
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
|
||||
|
||||
To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
|
||||
You will optionally provide additional commands as you see fit.
|
||||
|
||||
### Create rootCmd
|
||||
|
||||
Cobra doesn't require any special constructors. Simply create your commands.
|
||||
|
||||
Ideally you place this in app/cmd/root.go:
|
||||
|
||||
```go
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "hugo",
|
||||
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 https://gohugo.io/documentation/`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// Do Stuff Here
|
||||
},
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You will additionally define flags and handle configuration in your init() function.
|
||||
|
||||
For example cmd/root.go:
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
// Used for flags.
|
||||
cfgFile string
|
||||
userLicense string
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "cobra-cli",
|
||||
Short: "A generator for Cobra based Applications",
|
||||
Long: `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.`,
|
||||
}
|
||||
)
|
||||
|
||||
// Execute executes the root command.
|
||||
func Execute() error {
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
|
||||
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
|
||||
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
|
||||
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
|
||||
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.SetDefault("license", "apache")
|
||||
|
||||
rootCmd.AddCommand(addCmd)
|
||||
rootCmd.AddCommand(initCmd)
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := os.UserHomeDir()
|
||||
cobra.CheckErr(err)
|
||||
|
||||
// Search config in home directory with name ".cobra" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigType("yaml")
|
||||
viper.SetConfigName(".cobra")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv()
|
||||
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Create your main.go
|
||||
|
||||
With the root command you need to have your main function execute it.
|
||||
Execute should be run on the root for clarity, though it can be called on any command.
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
### Create additional commands
|
||||
|
||||
Additional commands can be defined and typically are each given their own file
|
||||
inside of the cmd/ directory.
|
||||
|
||||
If you wanted to create a version command you would create cmd/version.go and
|
||||
populate it with the following:
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number of Hugo",
|
||||
Long: `All software has versions. This is Hugo's`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Returning and handling errors
|
||||
|
||||
If you wish to return an error to the caller of a command, `RunE` can be used.
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(tryCmd)
|
||||
}
|
||||
|
||||
var tryCmd = &cobra.Command{
|
||||
Use: "try",
|
||||
Short: "Try and possibly fail at something",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if err := someFunc(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The error can then be caught at the execute function call.
|
||||
|
||||
## Working with Flags
|
||||
|
||||
Flags provide modifiers to control how the action command operates.
|
||||
|
||||
### Assign flags to a command
|
||||
|
||||
Since the flags are defined and used in different locations, we need to
|
||||
define a variable outside with the correct scope to assign the flag to
|
||||
work with.
|
||||
|
||||
```go
|
||||
var Verbose bool
|
||||
var Source string
|
||||
```
|
||||
|
||||
There are two different approaches to assign a flag.
|
||||
|
||||
### Persistent Flags
|
||||
|
||||
A flag can be 'persistent', meaning that this flag will be available to the
|
||||
command it's assigned to as well as every command under that command. For
|
||||
global flags, assign a flag as a persistent flag on the root.
|
||||
|
||||
```go
|
||||
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
|
||||
```
|
||||
|
||||
### Local Flags
|
||||
|
||||
A flag can also be assigned locally, which will only apply to that specific command.
|
||||
|
||||
```go
|
||||
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
||||
```
|
||||
|
||||
### Local Flag on Parent Commands
|
||||
|
||||
By default, Cobra only parses local flags on the target command, and any local flags on
|
||||
parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will
|
||||
parse local flags on each command before executing the target command.
|
||||
|
||||
```go
|
||||
command := cobra.Command{
|
||||
Use: "print [OPTIONS] [COMMANDS]",
|
||||
TraverseChildren: true,
|
||||
}
|
||||
```
|
||||
|
||||
### Bind Flags with Config
|
||||
|
||||
You can also bind your flags with [viper](https://github.com/spf13/viper):
|
||||
```go
|
||||
var author string
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the persistent flag `author` is bound with `viper`.
|
||||
**Note**: the variable `author` will not be set to the value from config,
|
||||
when the `--author` flag is provided by user.
|
||||
|
||||
More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
|
||||
|
||||
### Required 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(&u, "json", false, "Output in JSON")
|
||||
rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")
|
||||
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
|
||||
```
|
||||
|
||||
In both of 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`.
|
||||
The following validators are built in:
|
||||
|
||||
- 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.
|
||||
|
||||
If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.
|
||||
|
||||
Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.
|
||||
For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional
|
||||
args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as
|
||||
shown below:
|
||||
|
||||
```go
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: MatchAll(ExactArgs(2), OnlyValidArgs),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hello, World!")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.
|
||||
For example:
|
||||
|
||||
```go
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
// 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
|
||||
}
|
||||
return fmt.Errorf("invalid color specified: %s", args[0])
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hello, World!")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
In the example below, we have defined three commands. Two are at the top level
|
||||
and one (cmdTimes) is a child of one of the top commands. In this case the root
|
||||
is not executable, meaning that a subcommand is required. This is accomplished
|
||||
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
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var echoTimes int
|
||||
|
||||
var cmdPrint = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `print is for printing anything back to the screen.
|
||||
For many years people have printed back to the screen.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Print: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdEcho = &cobra.Command{
|
||||
Use: "echo [string to echo]",
|
||||
Short: "Echo anything to the screen",
|
||||
Long: `echo is for echoing anything back.
|
||||
Echo works a lot like print, except it has a child command.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdTimes = &cobra.Command{
|
||||
Use: "times [string to echo]",
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `echo things multiple times back to the user by providing
|
||||
a count and a string.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
for i := 0; i < echoTimes; i++ {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
|
||||
|
||||
var rootCmd = &cobra.Command{Use: "app"}
|
||||
rootCmd.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).
|
||||
|
||||
## Help Command
|
||||
|
||||
Cobra automatically adds a help command to your application when you have subcommands.
|
||||
This will be called when a user runs 'app help'. Additionally, help will also
|
||||
support all other commands as input. Say, for instance, you have a command called
|
||||
'create' without any additional configuration; Cobra will work when 'app help
|
||||
create' is called. Every command will automatically have the '--help' flag added.
|
||||
|
||||
### Example
|
||||
|
||||
The following output is automatically generated by Cobra. Nothing beyond the
|
||||
command and flag definitions are needed.
|
||||
|
||||
$ 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.
|
||||
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
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 the following functions:
|
||||
|
||||
```go
|
||||
cmd.SetHelpCommand(cmd *Command)
|
||||
cmd.SetHelpFunc(f func(*Command, []string))
|
||||
cmd.SetHelpTemplate(s string)
|
||||
```
|
||||
|
||||
The latter two will also apply to any children commands.
|
||||
|
||||
## Usage Message
|
||||
|
||||
When the user provides an invalid flag or invalid command, Cobra responds by
|
||||
showing the user the 'usage'.
|
||||
|
||||
### Example
|
||||
You may recognize this from the help above. That's because the default help
|
||||
embeds the usage as part of its output.
|
||||
|
||||
$ cobra-cli --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
Use "cobra [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:
|
||||
|
||||
```go
|
||||
cmd.SetUsageFunc(f func(*Command) error)
|
||||
cmd.SetUsageTemplate(s string)
|
||||
```
|
||||
|
||||
## Version Flag
|
||||
|
||||
Cobra adds a top-level '--version' flag if the Version field is set on the root command.
|
||||
Running an application with the '--version' flag will print the version to stdout using
|
||||
the version template. The template can be customized using the
|
||||
`cmd.SetVersionTemplate(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:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
- `Run`
|
||||
- `PostRun`
|
||||
- `PersistentPostRun`
|
||||
|
||||
An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "root [sub]",
|
||||
Short: "My root command",
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
|
||||
},
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
var subCmd = &cobra.Command{
|
||||
Use: "sub [no options!]",
|
||||
Short: "My subcommand",
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
rootCmd.AddCommand(subCmd)
|
||||
|
||||
rootCmd.SetArgs([]string{""})
|
||||
rootCmd.Execute()
|
||||
fmt.Println()
|
||||
rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
Inside rootCmd PersistentPreRun with args: []
|
||||
Inside rootCmd PreRun with args: []
|
||||
Inside rootCmd Run with args: []
|
||||
Inside rootCmd PostRun with args: []
|
||||
Inside rootCmd PersistentPostRun with args: []
|
||||
|
||||
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
|
||||
Inside subCmd PreRun with args: [arg1 arg2]
|
||||
Inside subCmd Run with args: [arg1 arg2]
|
||||
Inside subCmd PostRun with args: [arg1 arg2]
|
||||
Inside subCmd PersistentPostRun with args: [arg1 arg2]
|
||||
```
|
||||
|
||||
## 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:
|
||||
|
||||
```
|
||||
$ hugo srever
|
||||
Error: unknown command "srever" for "hugo"
|
||||
|
||||
Did you mean this?
|
||||
server
|
||||
|
||||
Run 'hugo --help' for usage.
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```go
|
||||
command.DisableSuggestions = true
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```go
|
||||
command.SuggestionsMinimumDistance = 1
|
||||
```
|
||||
|
||||
You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which
|
||||
you don't want aliases. Example:
|
||||
|
||||
```
|
||||
$ kubectl remove
|
||||
Error: unknown command "remove" for "kubectl"
|
||||
|
||||
Did you mean this?
|
||||
delete
|
||||
|
||||
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).
|
||||
|
||||
## 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).
|
||||
|
||||
## 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).
|
17
vendor/github.com/spf13/cobra/zsh_completions.go
generated
vendored
17
vendor/github.com/spf13/cobra/zsh_completions.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
// 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.
|
||||
|
@ -90,6 +90,7 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
|
|||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
|
||||
compdef _%[1]s %[1]s
|
||||
|
||||
# zsh completion for %-36[1]s -*- shell-script -*-
|
||||
|
||||
|
@ -108,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 =========="
|
||||
|
@ -177,7 +179,7 @@ _%[1]s()
|
|||
return
|
||||
fi
|
||||
|
||||
local activeHelpMarker="%[8]s"
|
||||
local activeHelpMarker="%[9]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
local startIndex=$((${#activeHelpMarker}+1))
|
||||
local hasActiveHelp=0
|
||||
|
@ -227,6 +229,11 @@ _%[1]s()
|
|||
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
|
||||
|
@ -262,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
|
||||
|
@ -296,6 +303,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then
|
|||
fi
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
|
48
vendor/github.com/spf13/cobra/zsh_completions.md
generated
vendored
48
vendor/github.com/spf13/cobra/zsh_completions.md
generated
vendored
|
@ -1,48 +0,0 @@
|
|||
## Generating Zsh Completion For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
||||
## Zsh completions standardization
|
||||
|
||||
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced.
|
||||
|
||||
### Deprecation summary
|
||||
|
||||
See further below for more details on these deprecations.
|
||||
|
||||
* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored.
|
||||
* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored.
|
||||
* Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`.
|
||||
* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored.
|
||||
* Instead use `ValidArgsFunction`.
|
||||
|
||||
### Behavioral changes
|
||||
|
||||
**Noun completion**
|
||||
|Old behavior|New behavior|
|
||||
|---|---|
|
||||
|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis|
|
||||
|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`|
|
||||
`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored|
|
||||
|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)|
|
||||
|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior|
|
||||
|
||||
**Flag-value completion**
|
||||
|
||||
|Old behavior|New behavior|
|
||||
|---|---|
|
||||
|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion|
|
||||
|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored|
|
||||
|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)|
|
||||
|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells|
|
||||
|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`|
|
||||
|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`|
|
||||
|
||||
**Improvements**
|
||||
|
||||
* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`)
|
||||
* File completion by default if no other completions found
|
||||
* Handling of required flags
|
||||
* File extension filtering no longer mutually exclusive with bash usage
|
||||
* Completion of directory names *within* another directory
|
||||
* Support for `=` form of flags
|
4
vendor/modules.txt
vendored
4
vendor/modules.txt
vendored
|
@ -235,7 +235,7 @@ github.com/hashicorp/golang-lru/arc/v2
|
|||
## explicit; go 1.18
|
||||
github.com/hashicorp/golang-lru/v2/internal
|
||||
github.com/hashicorp/golang-lru/v2/simplelru
|
||||
# github.com/inconshreveable/mousetrap v1.0.1
|
||||
# github.com/inconshreveable/mousetrap v1.1.0
|
||||
## explicit; go 1.18
|
||||
github.com/inconshreveable/mousetrap
|
||||
# github.com/jmespath/go-jmespath v0.4.0
|
||||
|
@ -314,7 +314,7 @@ github.com/redis/go-redis/v9/internal/util
|
|||
# github.com/sirupsen/logrus v1.9.3
|
||||
## explicit; go 1.13
|
||||
github.com/sirupsen/logrus
|
||||
# github.com/spf13/cobra v1.6.1
|
||||
# github.com/spf13/cobra v1.8.0
|
||||
## explicit; go 1.15
|
||||
github.com/spf13/cobra
|
||||
# github.com/spf13/pflag v1.0.5
|
||||
|
|
Loading…
Reference in a new issue