vendor: github.com/spf13/cobra v1.6.1
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 26c4429f7e
)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
parent
f528e2ab96
commit
526203dd7f
29 changed files with 2896 additions and 1092 deletions
|
@ -72,7 +72,7 @@ require (
|
|||
github.com/prometheus/client_golang v1.12.1
|
||||
github.com/rootless-containers/rootlesskit v1.1.0
|
||||
github.com/sirupsen/logrus v1.9.0
|
||||
github.com/spf13/cobra v1.1.3
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/spf13/pflag v1.0.5
|
||||
github.com/tchap/go-patricia v2.3.0+incompatible
|
||||
github.com/tonistiigi/fsutil v0.0.0-20220315205639-9ed612626da3
|
||||
|
@ -127,7 +127,7 @@ require (
|
|||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-sockaddr v1.0.2 // indirect
|
||||
github.com/hashicorp/golang-lru v0.5.4 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/jmespath/go-jmespath v0.3.0 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
|
||||
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
|
||||
|
|
|
@ -341,6 +341,7 @@ github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfc
|
|||
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
|
||||
|
@ -666,8 +667,9 @@ github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH
|
|||
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
|
||||
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/intel/goresctrl v0.2.0/go.mod h1:+CZdzouYFn5EsxgqAQTEzMfwKwuc0fVdMrT9FCCAVRQ=
|
||||
github.com/ishidawataru/sctp v0.0.0-20210707070123-9a39160e9062 h1:G1+wBT0dwjIrBdLy0MIG0i+E4CQxEnedHXdauJEIH6g=
|
||||
github.com/ishidawataru/sctp v0.0.0-20210707070123-9a39160e9062/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg=
|
||||
|
@ -942,6 +944,7 @@ github.com/rootless-containers/rootlesskit v1.1.0/go.mod h1:H+o9ndNe7tS91WqU0/+v
|
|||
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4=
|
||||
|
@ -977,8 +980,9 @@ github.com/spf13/cobra v0.0.1/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3
|
|||
github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
|
||||
github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M=
|
||||
github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/pflag v1.0.0/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
|
@ -1690,6 +1694,7 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
|
|||
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
|
||||
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
|
||||
gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8=
|
||||
|
|
208
vendor/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
208
vendor/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
|
@ -1,13 +1,201 @@
|
|||
Copyright 2014 Alan Shreve
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
1. Definitions.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2022 Alan Shreve (@inconshreveable)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
14
vendor/github.com/spf13/cobra/.golangci.yml
generated
vendored
14
vendor/github.com/spf13/cobra/.golangci.yml
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
# Copyright 2013-2022 The Cobra Authors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
run:
|
||||
deadline: 5m
|
||||
|
||||
|
|
28
vendor/github.com/spf13/cobra/.travis.yml
generated
vendored
28
vendor/github.com/spf13/cobra/.travis.yml
generated
vendored
|
@ -1,28 +0,0 @@
|
|||
language: go
|
||||
|
||||
stages:
|
||||
- test
|
||||
- build
|
||||
|
||||
go:
|
||||
- 1.12.x
|
||||
- 1.13.x
|
||||
- tip
|
||||
|
||||
env: GO111MODULE=on
|
||||
|
||||
before_install:
|
||||
- go get -u github.com/kyoh86/richgo
|
||||
- go get -u github.com/mitchellh/gox
|
||||
- curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin latest
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
include:
|
||||
- stage: build
|
||||
go: 1.13.x
|
||||
script: make cobra_generator
|
||||
|
||||
script:
|
||||
- make test
|
51
vendor/github.com/spf13/cobra/CHANGELOG.md
generated
vendored
51
vendor/github.com/spf13/cobra/CHANGELOG.md
generated
vendored
|
@ -1,51 +0,0 @@
|
|||
# Cobra Changelog
|
||||
|
||||
## v1.1.3
|
||||
|
||||
* **Fix:** release-branch.cobra1.1 only: Revert "Deprecate Go < 1.14" to maintain backward compatibility
|
||||
|
||||
## v1.1.2
|
||||
|
||||
### Notable Changes
|
||||
|
||||
* Bump license year to 2021 in golden files (#1309) @Bowbaq
|
||||
* Enhance PowerShell completion with custom comp (#1208) @Luap99
|
||||
* Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670
|
||||
* Documentation readability improvements (#1228 etc.) @zaataylor etc.
|
||||
* Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor
|
||||
|
||||
## v1.1.1
|
||||
|
||||
* **Fix:** yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context.
|
||||
* **Fix:** correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context.
|
||||
|
||||
## v1.1.0
|
||||
|
||||
### Notable Changes
|
||||
|
||||
* Extend Go completions and revamp zsh comp (#1070)
|
||||
* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` (#1104) @jpmcb
|
||||
* Add completion for help command (#1136)
|
||||
* Complete subcommands when TraverseChildren is set (#1171)
|
||||
* Fix stderr printing functions (#894)
|
||||
* fix: fish output redirection (#1247)
|
||||
|
||||
## v1.0.0
|
||||
|
||||
Announcing v1.0.0 of Cobra. 🎉
|
||||
|
||||
### Notable Changes
|
||||
* Fish completion (including support for Go custom completion) @marckhouzam
|
||||
* API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam
|
||||
* Remove/replace SetOutput on Command - deprecated @jpmcb
|
||||
* add support for autolabel stale PR @xchapter7x
|
||||
* Add Labeler Actions @xchapter7x
|
||||
* Custom completions coded in Go (instead of Bash) @marckhouzam
|
||||
* Partial Revert of #922 @jharshman
|
||||
* Add Makefile to project @jharshman
|
||||
* Correct documentation for InOrStdin @desponda
|
||||
* Apply formatting to templates @jharshman
|
||||
* Revert change so help is printed on stdout again @marckhouzam
|
||||
* Update md2man to v2.0.0 @pdf
|
||||
* update viper to v1.4.0 @umarcor
|
||||
* Update cmd/root.go example in README.md @jharshman
|
13
vendor/github.com/spf13/cobra/MAINTAINERS
generated
vendored
Normal file
13
vendor/github.com/spf13/cobra/MAINTAINERS
generated
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
maintainers:
|
||||
- spf13
|
||||
- johnSchnake
|
||||
- jpmcb
|
||||
- marckhouzam
|
||||
inactive:
|
||||
- anthonyfok
|
||||
- bep
|
||||
- bogem
|
||||
- broady
|
||||
- eparis
|
||||
- jharshman
|
||||
- wfernandes
|
13
vendor/github.com/spf13/cobra/Makefile
generated
vendored
13
vendor/github.com/spf13/cobra/Makefile
generated
vendored
|
@ -6,14 +6,14 @@ $(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://insta
|
|||
endif
|
||||
|
||||
ifeq (, $(shell which richgo))
|
||||
$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")
|
||||
$(warning "could not find richgo in $(PATH), run: go install github.com/kyoh86/richgo@latest")
|
||||
endif
|
||||
|
||||
.PHONY: fmt lint test cobra_generator install_deps clean
|
||||
.PHONY: fmt lint test install_deps clean
|
||||
|
||||
default: all
|
||||
|
||||
all: fmt test cobra_generator
|
||||
all: fmt test
|
||||
|
||||
fmt:
|
||||
$(info ******************** checking formatting ********************)
|
||||
|
@ -23,15 +23,10 @@ lint:
|
|||
$(info ******************** running lint tools ********************)
|
||||
golangci-lint run -v
|
||||
|
||||
test: install_deps lint
|
||||
test: install_deps
|
||||
$(info ******************** running tests ********************)
|
||||
richgo test -v ./...
|
||||
|
||||
cobra_generator: install_deps
|
||||
$(info ******************** building generator ********************)
|
||||
mkdir -p $(BIN)
|
||||
make -C cobra all
|
||||
|
||||
install_deps:
|
||||
$(info ******************** downloading dependencies ********************)
|
||||
go get -v ./...
|
||||
|
|
690
vendor/github.com/spf13/cobra/README.md
generated
vendored
690
vendor/github.com/spf13/cobra/README.md
generated
vendored
|
@ -1,61 +1,35 @@
|
|||
![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
|
||||
|
||||
Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
|
||||
Cobra is a library for creating powerful modern CLI applications.
|
||||
|
||||
Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/),
|
||||
[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to
|
||||
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.
|
||||
|
||||
[![](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)
|
||||
[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
|
||||
[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
|
||||
[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)
|
||||
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
|
||||
[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
|
||||
|
||||
# Table of Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Concepts](#concepts)
|
||||
* [Commands](#commands)
|
||||
* [Flags](#flags)
|
||||
- [Installing](#installing)
|
||||
- [Getting Started](#getting-started)
|
||||
* [Using the Cobra Generator](#using-the-cobra-generator)
|
||||
* [Using the Cobra Library](#using-the-cobra-library)
|
||||
* [Working with Flags](#working-with-flags)
|
||||
* [Positional and Custom Arguments](#positional-and-custom-arguments)
|
||||
* [Example](#example)
|
||||
* [Help Command](#help-command)
|
||||
* [Usage Message](#usage-message)
|
||||
* [PreRun and PostRun Hooks](#prerun-and-postrun-hooks)
|
||||
* [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens)
|
||||
* [Generating documentation for your command](#generating-documentation-for-your-command)
|
||||
* [Generating shell completions](#generating-shell-completions)
|
||||
- [Contributing](CONTRIBUTING.md)
|
||||
- [License](#license)
|
||||
|
||||
# Overview
|
||||
|
||||
Cobra is a library providing a simple interface to create powerful modern CLI
|
||||
interfaces similar to git & go tools.
|
||||
|
||||
Cobra is also an application that will generate your application scaffolding to rapidly
|
||||
develop a Cobra-based application.
|
||||
|
||||
Cobra provides:
|
||||
* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
|
||||
* Fully POSIX-compliant flags (including short & long versions)
|
||||
* Nested subcommands
|
||||
* Global, local and cascading flags
|
||||
* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`
|
||||
* Intelligent suggestions (`app srver`... did you mean `app server`?)
|
||||
* Automatic help generation for commands and flags
|
||||
* Grouping help for subcommands
|
||||
* Automatic help flag recognition of `-h`, `--help`, etc.
|
||||
* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
|
||||
* Automatically generated man pages for your application
|
||||
* Command aliases so you can change things without breaking them
|
||||
* The flexibility to define your own help, usage, etc.
|
||||
* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
|
||||
* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps
|
||||
|
||||
# Concepts
|
||||
|
||||
|
@ -67,9 +41,9 @@ The best applications read like sentences when used, and as a result, users
|
|||
intuitively know how to interact with them.
|
||||
|
||||
The pattern to follow is
|
||||
`APPNAME VERB NOUN --ADJECTIVE.`
|
||||
`APPNAME VERB NOUN --ADJECTIVE`
|
||||
or
|
||||
`APPNAME COMMAND ARG --FLAG`
|
||||
`APPNAME COMMAND ARG --FLAG`.
|
||||
|
||||
A few good real world examples may better illustrate this point.
|
||||
|
||||
|
@ -89,7 +63,7 @@ have children commands and optionally run an action.
|
|||
|
||||
In the example above, 'server' is the command.
|
||||
|
||||
[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command)
|
||||
[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command)
|
||||
|
||||
## Flags
|
||||
|
||||
|
@ -106,10 +80,11 @@ 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. This command will install the `cobra` generator executable
|
||||
along with the library and its dependencies:
|
||||
of the library.
|
||||
|
||||
go get -u github.com/spf13/cobra
|
||||
```
|
||||
go get -u github.com/spf13/cobra@latest
|
||||
```
|
||||
|
||||
Next, include Cobra in your application:
|
||||
|
||||
|
@ -117,643 +92,20 @@ Next, include Cobra in your application:
|
|||
import "github.com/spf13/cobra"
|
||||
```
|
||||
|
||||
# Getting Started
|
||||
# Usage
|
||||
`cobra-cli` is a command line program to generate cobra applications and command files.
|
||||
It will bootstrap your application scaffolding to rapidly
|
||||
develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.
|
||||
|
||||
While you are welcome to provide your own organization, typically a Cobra-based
|
||||
application will follow the following organizational structure:
|
||||
It can be installed by running:
|
||||
|
||||
```
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
go install github.com/spf13/cobra-cli@latest
|
||||
```
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
|
||||
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)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
## Using the Cobra Generator
|
||||
|
||||
Cobra provides 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.
|
||||
|
||||
[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it.
|
||||
|
||||
## 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 http://hugo.spf13.com`,
|
||||
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"
|
||||
|
||||
homedir "github.com/mitchellh/go-homedir"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
// Used for flags.
|
||||
cfgFile string
|
||||
userLicense string
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "cobra",
|
||||
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 := homedir.Dir()
|
||||
cobra.CheckErr(err)
|
||||
|
||||
// Search config in home directory with name ".cobra" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
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 not 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")
|
||||
```
|
||||
|
||||
## Positional and Custom Arguments
|
||||
|
||||
Validation of positional arguments can be specified using the `Args` field
|
||||
of `Command`.
|
||||
|
||||
The following validators are built in:
|
||||
|
||||
- `NoArgs` - the command will report an error if there are any positional args.
|
||||
- `ArbitraryArgs` - the command will accept any args.
|
||||
- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.
|
||||
- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
|
||||
- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
|
||||
- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.
|
||||
- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`
|
||||
- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
|
||||
|
||||
An example of setting the custom validator:
|
||||
|
||||
```go
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return errors.New("requires a color argument")
|
||||
}
|
||||
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](http://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 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 [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration (default true)
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
### Defining your own help
|
||||
|
||||
You can provide your own Help command or your own template for the default command to use
|
||||
with 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 --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration (default true)
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
|
||||
### 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 automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
|
||||
|
||||
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 makes sense in your set of commands and for some 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).
|
||||
For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).
|
||||
|
||||
# License
|
||||
|
||||
|
|
63
vendor/github.com/spf13/cobra/active_help.go
generated
vendored
Normal file
63
vendor/github.com/spf13/cobra/active_help.go
generated
vendored
Normal file
|
@ -0,0 +1,63 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
activeHelpMarker = "_activeHelp_ "
|
||||
// The below values should not be changed: programs will be using them explicitly
|
||||
// in their user documentation, and users will be using them explicitly.
|
||||
activeHelpEnvVarSuffix = "_ACTIVE_HELP"
|
||||
activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
|
||||
activeHelpGlobalDisable = "0"
|
||||
)
|
||||
|
||||
// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
|
||||
// Such strings will be processed by the completion script and will be shown as ActiveHelp
|
||||
// to the user.
|
||||
// The array parameter should be the array that will contain the completions.
|
||||
// This function can be called multiple times before and/or after completions are added to
|
||||
// the array. Each time this function is called with the same array, the new
|
||||
// ActiveHelp line will be shown below the previous ones when completion is triggered.
|
||||
func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
|
||||
return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
|
||||
}
|
||||
|
||||
// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
|
||||
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
|
||||
// case, with all - replaced by _.
|
||||
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
|
||||
// is set to "0".
|
||||
func GetActiveHelpConfig(cmd *Command) string {
|
||||
activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar)
|
||||
if activeHelpCfg != activeHelpGlobalDisable {
|
||||
activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))
|
||||
}
|
||||
return activeHelpCfg
|
||||
}
|
||||
|
||||
// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
|
||||
// variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
|
||||
// root command in upper case, with all - replaced by _.
|
||||
func activeHelpEnvVar(name string) string {
|
||||
// This format should not be changed: users will be using it explicitly.
|
||||
activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
|
||||
return strings.ReplaceAll(activeHelpEnvVar, "-", "_")
|
||||
}
|
157
vendor/github.com/spf13/cobra/active_help.md
generated
vendored
Normal file
157
vendor/github.com/spf13/cobra/active_help.md
generated
vendored
Normal file
|
@ -0,0 +1,157 @@
|
|||
# Active Help
|
||||
|
||||
Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion.
|
||||
|
||||
For example,
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding.
|
||||
|
||||
bash-5.1$ bin/helm package [tab]
|
||||
Please specify the path to the chart to package
|
||||
|
||||
bash-5.1$ bin/helm package [tab][tab]
|
||||
bin/ internal/ scripts/ pkg/ testdata/
|
||||
```
|
||||
|
||||
**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.
|
||||
## Supported shells
|
||||
|
||||
Active Help is currently only supported for the following shells:
|
||||
- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.
|
||||
- Zsh
|
||||
|
||||
## Adding Active Help messages
|
||||
|
||||
As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md).
|
||||
|
||||
Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.
|
||||
|
||||
### Active Help for nouns
|
||||
|
||||
Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "add [NAME] [URL]",
|
||||
Short: "add a chart repository",
|
||||
Args: require.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return addRepo(args)
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
var comps []string
|
||||
if len(args) == 0 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
} else if len(args) == 1 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
|
||||
} else {
|
||||
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
|
||||
}
|
||||
return comps, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior:
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana [tab]
|
||||
You must specify the URL for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
|
||||
This command does not take any more arguments
|
||||
```
|
||||
**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.
|
||||
|
||||
### Active Help for flags
|
||||
|
||||
Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:
|
||||
```go
|
||||
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 2 {
|
||||
return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return compVersionFlag(args[1], toComplete)
|
||||
})
|
||||
```
|
||||
The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.
|
||||
```
|
||||
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
|
||||
You must first specify the chart to install before the --version flag can be completed
|
||||
|
||||
bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
|
||||
2.0.1 2.0.2 2.0.3
|
||||
```
|
||||
|
||||
## User control of Active Help
|
||||
|
||||
You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.
|
||||
Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.
|
||||
|
||||
The way to configure Active Help is to use the program's Active Help environment
|
||||
variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your
|
||||
program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever
|
||||
Active Help configuration values are supported by the program.
|
||||
|
||||
For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user
|
||||
would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.
|
||||
|
||||
For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the
|
||||
Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages
|
||||
should or should not be added (instead of reading the environment variable directly).
|
||||
|
||||
For example:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
|
||||
|
||||
var comps []string
|
||||
if len(args) == 0 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
}
|
||||
} else if len(args) == 1 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
|
||||
}
|
||||
} else {
|
||||
if activeHelpLevel == "local" {
|
||||
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
|
||||
}
|
||||
}
|
||||
return comps, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
```
|
||||
**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.
|
||||
|
||||
**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.
|
||||
|
||||
**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string.
|
||||
## Active Help with Cobra's default completion command
|
||||
|
||||
Cobra provides a default `completion` command for programs that wish to use it.
|
||||
When using the default `completion` command, Active Help is configurable in the same
|
||||
fashion as described above using environment variables. You may wish to document this in more
|
||||
details for your users.
|
||||
|
||||
## Debugging Active Help
|
||||
|
||||
Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details.
|
||||
|
||||
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
|
||||
```
|
||||
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
_activeHelp_ WARNING: cannot re-use a name that is still in use
|
||||
:0
|
||||
Completion ended with directive: ShellCompDirectiveDefault
|
||||
|
||||
$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
:0
|
||||
Completion ended with directive: ShellCompDirectiveDefault
|
||||
```
|
50
vendor/github.com/spf13/cobra/args.go
generated
vendored
50
vendor/github.com/spf13/cobra/args.go
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
|
@ -32,7 +46,8 @@ func NoArgs(cmd *Command, args []string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.
|
||||
// OnlyValidArgs returns an error if there are any positional args that are not in
|
||||
// the `ValidArgs` field of `Command`
|
||||
func OnlyValidArgs(cmd *Command, args []string) error {
|
||||
if len(cmd.ValidArgs) > 0 {
|
||||
// Remove any description that may be included in ValidArgs.
|
||||
|
@ -41,7 +56,6 @@ func OnlyValidArgs(cmd *Command, args []string) error {
|
|||
for _, v := range cmd.ValidArgs {
|
||||
validArgs = append(validArgs, strings.Split(v, "\t")[0])
|
||||
}
|
||||
|
||||
for _, v := range args {
|
||||
if !stringInSlice(v, validArgs) {
|
||||
return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
|
||||
|
@ -86,18 +100,6 @@ func ExactArgs(n int) PositionalArgs {
|
|||
}
|
||||
}
|
||||
|
||||
// ExactValidArgs returns an error if
|
||||
// there are not exactly N positional args OR
|
||||
// there are any positional args that are not in the `ValidArgs` field of `Command`
|
||||
func ExactValidArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if err := ExactArgs(n)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
return OnlyValidArgs(cmd, args)
|
||||
}
|
||||
}
|
||||
|
||||
// RangeArgs returns an error if the number of args is not within the expected range.
|
||||
func RangeArgs(min int, max int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
|
@ -107,3 +109,23 @@ func RangeArgs(min int, max int) PositionalArgs {
|
|||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MatchAll allows combining several PositionalArgs to work in concert.
|
||||
func MatchAll(pargs ...PositionalArgs) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
for _, parg := range pargs {
|
||||
if err := parg(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExactValidArgs returns an error if there are not exactly N positional args OR
|
||||
// there are any positional args that are not in the `ValidArgs` field of `Command`
|
||||
//
|
||||
// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead
|
||||
func ExactValidArgs(n int) PositionalArgs {
|
||||
return MatchAll(ExactArgs(n), OnlyValidArgs)
|
||||
}
|
||||
|
|
87
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
87
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
|
@ -24,7 +38,7 @@ func writePreamble(buf io.StringWriter, name string) {
|
|||
WriteStringAndCheck(buf, fmt.Sprintf(`
|
||||
__%[1]s_debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
@ -73,7 +87,8 @@ __%[1]s_handle_go_custom_completion()
|
|||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
args=("${words[@]:1}")
|
||||
requestComp="${words[0]} %[2]s ${args[*]}"
|
||||
# Disable ActiveHelp which is not supported for bash completion v1
|
||||
requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
lastParam=${words[$((${#words[@]}-1))]}
|
||||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
|
@ -99,7 +114,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}"
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
# Error code. No completion.
|
||||
|
@ -125,7 +140,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
local fullFilter filter filteringCmd
|
||||
# Do not use quotes around the $out variable or else newline
|
||||
# characters will be kept.
|
||||
for filter in ${out[*]}; do
|
||||
for filter in ${out}; do
|
||||
fullFilter+="$filter|"
|
||||
done
|
||||
|
||||
|
@ -134,9 +149,9 @@ __%[1]s_handle_go_custom_completion()
|
|||
$filteringCmd
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
# File completion for directories only
|
||||
local subDir
|
||||
local subdir
|
||||
# Use printf to strip any trailing newline
|
||||
subdir=$(printf "%%s" "${out[0]}")
|
||||
subdir=$(printf "%%s" "${out}")
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
__%[1]s_handle_subdirs_in_dir_flag "$subdir"
|
||||
|
@ -147,7 +162,7 @@ __%[1]s_handle_go_custom_completion()
|
|||
else
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${out[*]}" -- "$cur")
|
||||
done < <(compgen -W "${out}" -- "$cur")
|
||||
fi
|
||||
}
|
||||
|
||||
|
@ -187,13 +202,19 @@ __%[1]s_handle_reply()
|
|||
PREFIX=""
|
||||
cur="${cur#*=}"
|
||||
${flags_completion[${index}]}
|
||||
if [ -n "${ZSH_VERSION}" ]; then
|
||||
if [ -n "${ZSH_VERSION:-}" ]; then
|
||||
# zsh completion needs --flag= prefix
|
||||
eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
return 0;
|
||||
|
||||
if [[ -z "${flag_parsing_disabled}" ]]; then
|
||||
# If flag parsing is enabled, we have completed the flags and can return.
|
||||
# If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough
|
||||
# to possibly call handle_go_custom_completion.
|
||||
return 0;
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
|
@ -232,13 +253,13 @@ __%[1]s_handle_reply()
|
|||
fi
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
if declare -F __%[1]s_custom_func >/dev/null; then
|
||||
# try command name qualified custom func
|
||||
__%[1]s_custom_func
|
||||
else
|
||||
# otherwise fall back to unqualified for compatibility
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
if declare -F __%[1]s_custom_func >/dev/null; then
|
||||
# try command name qualified custom func
|
||||
__%[1]s_custom_func
|
||||
else
|
||||
# otherwise fall back to unqualified for compatibility
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
fi
|
||||
|
||||
# available in bash-completion >= 2, not always present on macOS
|
||||
|
@ -272,7 +293,7 @@ __%[1]s_handle_flag()
|
|||
|
||||
# if a command required a flag, and we found it, unset must_have_one_flag()
|
||||
local flagname=${words[c]}
|
||||
local flagvalue
|
||||
local flagvalue=""
|
||||
# if the word contained an =
|
||||
if [[ ${words[c]} == *"="* ]]; then
|
||||
flagvalue=${flagname#*=} # take in as flagvalue after the =
|
||||
|
@ -291,7 +312,7 @@ __%[1]s_handle_flag()
|
|||
|
||||
# keep flag value with flagname as flaghash
|
||||
# flaghash variable is an associative array which is only supported in bash > 3.
|
||||
if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then
|
||||
if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then
|
||||
if [ -n "${flagvalue}" ] ; then
|
||||
flaghash[${flagname}]=${flagvalue}
|
||||
elif [ -n "${words[ $((c+1)) ]}" ] ; then
|
||||
|
@ -303,7 +324,7 @@ __%[1]s_handle_flag()
|
|||
|
||||
# skip the argument to a two word flag
|
||||
if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
|
||||
c=$((c+1))
|
||||
# if we are looking for a flags value, don't show commands
|
||||
if [[ $c -eq $cword ]]; then
|
||||
|
@ -363,7 +384,7 @@ __%[1]s_handle_word()
|
|||
__%[1]s_handle_command
|
||||
elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then
|
||||
# aliashash variable is an associative array which is only supported in bash > 3.
|
||||
if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then
|
||||
if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then
|
||||
words[c]=${aliashash[${words[c]}]}
|
||||
__%[1]s_handle_command
|
||||
else
|
||||
|
@ -377,14 +398,14 @@ __%[1]s_handle_word()
|
|||
|
||||
`, name, ShellCompNoDescRequestCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func writePostscript(buf io.StringWriter, name string) {
|
||||
name = strings.Replace(name, ":", "__", -1)
|
||||
name = strings.ReplaceAll(name, ":", "__")
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`{
|
||||
local cur prev words cword
|
||||
local cur prev words cword split
|
||||
declare -A flaghash 2>/dev/null || :
|
||||
declare -A aliashash 2>/dev/null || :
|
||||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
|
@ -394,17 +415,20 @@ func writePostscript(buf io.StringWriter, name string) {
|
|||
fi
|
||||
|
||||
local c=0
|
||||
local flag_parsing_disabled=
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local local_nonpersistent_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%[1]s")
|
||||
local command_aliases=()
|
||||
local must_have_one_flag=()
|
||||
local must_have_one_noun=()
|
||||
local has_completion_function
|
||||
local last_command
|
||||
local has_completion_function=""
|
||||
local last_command=""
|
||||
local nouns=()
|
||||
local noun_aliases=()
|
||||
|
||||
__%[1]s_handle_word
|
||||
}
|
||||
|
@ -510,6 +534,8 @@ func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
|
|||
|
||||
// Setup annotations for go completions for registered flags
|
||||
func prepareCustomAnnotationsForFlags(cmd *Command) {
|
||||
flagCompletionMutex.RLock()
|
||||
defer flagCompletionMutex.RUnlock()
|
||||
for flag := range flagCompletionFunctions {
|
||||
// Make sure the completion script calls the __*_go_custom_completion function for
|
||||
// every registered flag. We need to do this here (and not when the flag was registered
|
||||
|
@ -531,6 +557,11 @@ func writeFlags(buf io.StringWriter, cmd *Command) {
|
|||
flags_completion=()
|
||||
|
||||
`)
|
||||
|
||||
if cmd.DisableFlagParsing {
|
||||
WriteStringAndCheck(buf, " flag_parsing_disabled=1\n")
|
||||
}
|
||||
|
||||
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
|
@ -605,7 +636,7 @@ func writeCmdAliases(buf io.StringWriter, cmd *Command) {
|
|||
|
||||
sort.Strings(cmd.Aliases)
|
||||
|
||||
WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))
|
||||
WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n"))
|
||||
for _, value := range cmd.Aliases {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
|
||||
|
@ -629,8 +660,8 @@ func gen(buf io.StringWriter, cmd *Command) {
|
|||
gen(buf, c)
|
||||
}
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.Replace(commandName, " ", "_", -1)
|
||||
commandName = strings.Replace(commandName, ":", "__", -1)
|
||||
commandName = strings.ReplaceAll(commandName, " ", "_")
|
||||
commandName = strings.ReplaceAll(commandName, ":", "__")
|
||||
|
||||
if cmd.Root() == cmd {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))
|
||||
|
|
2
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
2
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
|
@ -6,6 +6,8 @@ Please refer to [Shell Completions](shell_completions.md) for details.
|
|||
|
||||
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:
|
||||
|
|
383
vendor/github.com/spf13/cobra/bash_completionsV2.go
generated
vendored
Normal file
383
vendor/github.com/spf13/cobra/bash_completionsV2.go
generated
vendored
Normal file
|
@ -0,0 +1,383 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genBashComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-
|
||||
|
||||
__%[1]s_debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Macs have bash3 for which the bash-completion package doesn't include
|
||||
# _init_completion. This is a minimal version of that function.
|
||||
__%[1]s_init_completion()
|
||||
{
|
||||
COMPREPLY=()
|
||||
_get_comp_words_by_ref "$@" cur prev words cword
|
||||
}
|
||||
|
||||
# This function calls the %[1]s program to obtain the completion
|
||||
# results and the directive. It fills the 'out' and 'directive' vars.
|
||||
__%[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
|
||||
args=("${words[@]:1}")
|
||||
requestComp="${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
lastParam=${words[$((${#words[@]}-1))]}
|
||||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
__%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"
|
||||
|
||||
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"
|
||||
requestComp="${requestComp} ''"
|
||||
fi
|
||||
|
||||
# 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
|
||||
cur="${cur#*=}"
|
||||
fi
|
||||
|
||||
__%[1]s_debug "Calling ${requestComp}"
|
||||
# Use eval to handle any environment variables and such
|
||||
out=$(eval "${requestComp}" 2>/dev/null)
|
||||
|
||||
# Extract the directive integer at the very end of the output following a colon (:)
|
||||
directive=${out##*:}
|
||||
# Remove the directive
|
||||
out=${out%%:*}
|
||||
if [ "${directive}" = "${out}" ]; then
|
||||
# There is not directive specified
|
||||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "The completion directive is: ${directive}"
|
||||
__%[1]s_debug "The completions are: ${out}"
|
||||
}
|
||||
|
||||
__%[1]s_process_completion_results() {
|
||||
local shellCompDirectiveError=%[3]d
|
||||
local shellCompDirectiveNoSpace=%[4]d
|
||||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 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
|
||||
__%[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
|
||||
__%[1]s_debug "Activating no file completion"
|
||||
compopt +o default
|
||||
else
|
||||
__%[1]s_debug "No file completion directive not supported in this version of bash"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Separate activeHelp from normal completions
|
||||
local completions=()
|
||||
local activeHelp=()
|
||||
__%[1]s_extract_activeHelp
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local fullFilter filter filteringCmd
|
||||
|
||||
# Do not use quotes around the $completions variable or else newline
|
||||
# characters will be kept.
|
||||
for filter in ${completions[*]}; do
|
||||
fullFilter+="$filter|"
|
||||
done
|
||||
|
||||
filteringCmd="_filedir $fullFilter"
|
||||
__%[1]s_debug "File filtering command: $filteringCmd"
|
||||
$filteringCmd
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 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
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
|
||||
else
|
||||
__%[1]s_debug "Listing directories in ."
|
||||
_filedir -d
|
||||
fi
|
||||
else
|
||||
__%[1]s_handle_completion_types
|
||||
fi
|
||||
|
||||
__%[1]s_handle_special_char "$cur" :
|
||||
__%[1]s_handle_special_char "$cur" =
|
||||
|
||||
# Print the activeHelp statements before we finish
|
||||
if [ ${#activeHelp[*]} -ne 0 ]; then
|
||||
printf "\n";
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
printf "\n"
|
||||
|
||||
# The prompt format is only available from bash 4.4.
|
||||
# We test if it is available before using it.
|
||||
if (x=${PS1@P}) 2> /dev/null; then
|
||||
printf "%%s" "${PS1@P}${COMP_LINE[@]}"
|
||||
else
|
||||
# Can't print the prompt. Just print the
|
||||
# text the user had typed, it is workable enough.
|
||||
printf "%%s" "${COMP_LINE[@]}"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Separate activeHelp lines from real completions.
|
||||
# Fills the $activeHelp and $completions arrays.
|
||||
__%[1]s_extract_activeHelp() {
|
||||
local activeHelpMarker="%[8]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then
|
||||
comp=${comp:endIndex}
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
if [ -n "$comp" ]; then
|
||||
activeHelp+=("$comp")
|
||||
fi
|
||||
else
|
||||
# Not an activeHelp line but a normal completion
|
||||
completions+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out}")
|
||||
}
|
||||
|
||||
__%[1]s_handle_completion_types() {
|
||||
__%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"
|
||||
|
||||
case $COMP_TYPE in
|
||||
37|42)
|
||||
# Type: menu-complete/menu-complete-backward and insert-completions
|
||||
# If the user requested inserting one completion at a time, or all
|
||||
# completions at once on the command-line we must remove the descriptions.
|
||||
# https://github.com/spf13/cobra/issues/1508
|
||||
local tab=$'\t' comp
|
||||
while IFS='' read -r comp; do
|
||||
[[ -z $comp ]] && continue
|
||||
# Strip any description
|
||||
comp=${comp%%%%$tab*}
|
||||
# Only consider the completions that match
|
||||
if [[ $comp == "$cur"* ]]; then
|
||||
COMPREPLY+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
;;
|
||||
|
||||
*)
|
||||
# Type: complete (normal completion)
|
||||
__%[1]s_handle_standard_completion_case
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
__%[1]s_handle_standard_completion_case() {
|
||||
local tab=$'\t' comp
|
||||
|
||||
# Short circuit to optimize if we don't have descriptions
|
||||
if [[ "${completions[*]}" != *$tab* ]]; then
|
||||
IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
|
||||
return 0
|
||||
fi
|
||||
|
||||
local longest=0
|
||||
local compline
|
||||
# Look for the longest completion so that we can format things nicely
|
||||
while IFS='' read -r compline; do
|
||||
[[ -z $compline ]] && continue
|
||||
# Strip any description before checking the length
|
||||
comp=${compline%%%%$tab*}
|
||||
# Only consider the completions that match
|
||||
[[ $comp == "$cur"* ]] || continue
|
||||
COMPREPLY+=("$compline")
|
||||
if ((${#comp}>longest)); then
|
||||
longest=${#comp}
|
||||
fi
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
|
||||
# If there is a single completion left, remove the description text
|
||||
if [ ${#COMPREPLY[*]} -eq 1 ]; then
|
||||
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
|
||||
comp="${COMPREPLY[0]%%%%$tab*}"
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
|
||||
COMPREPLY[0]=$comp
|
||||
else # Format the descriptions
|
||||
__%[1]s_format_comp_descriptions $longest
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_handle_special_char()
|
||||
{
|
||||
local comp="$1"
|
||||
local char=$2
|
||||
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"}
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_format_comp_descriptions()
|
||||
{
|
||||
local tab=$'\t'
|
||||
local comp desc maxdesclength
|
||||
local longest=$1
|
||||
|
||||
local i ci
|
||||
for ci in ${!COMPREPLY[*]}; do
|
||||
comp=${COMPREPLY[ci]}
|
||||
# Properly format the description string which follows a tab character if there is one
|
||||
if [[ "$comp" == *$tab* ]]; then
|
||||
__%[1]s_debug "Original comp: $comp"
|
||||
desc=${comp#*$tab}
|
||||
comp=${comp%%%%$tab*}
|
||||
|
||||
# $COLUMNS stores the current shell width.
|
||||
# Remove an extra 4 because we add 2 spaces and 2 parentheses.
|
||||
maxdesclength=$(( COLUMNS - longest - 4 ))
|
||||
|
||||
# Make sure we can fit a description of at least 8 characters
|
||||
# if we are to align the descriptions.
|
||||
if [[ $maxdesclength -gt 8 ]]; then
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
for ((i = ${#comp} ; i < longest ; i++)); do
|
||||
comp+=" "
|
||||
done
|
||||
else
|
||||
# Don't pad the descriptions so we can fit more text after the completion
|
||||
maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
|
||||
fi
|
||||
|
||||
# If there is enough space for any description text,
|
||||
# truncate the descriptions that are too long for the shell width
|
||||
if [ $maxdesclength -gt 0 ]; then
|
||||
if [ ${#desc} -gt $maxdesclength ]; then
|
||||
desc=${desc:0:$(( maxdesclength - 1 ))}
|
||||
desc+="…"
|
||||
fi
|
||||
comp+=" ($desc)"
|
||||
fi
|
||||
COMPREPLY[ci]=$comp
|
||||
__%[1]s_debug "Final comp: $comp"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
__start_%[1]s()
|
||||
{
|
||||
local cur prev words cword split
|
||||
|
||||
COMPREPLY=()
|
||||
|
||||
# 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
|
||||
else
|
||||
__%[1]s_init_completion -n "=:" || return
|
||||
fi
|
||||
|
||||
__%[1]s_debug
|
||||
__%[1]s_debug "========= starting completion logic =========="
|
||||
__%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"
|
||||
|
||||
# The user could have moved the cursor backwards on the command-line.
|
||||
# We need to trigger completion from the $cword location, so we need
|
||||
# to truncate the command-line ($words) up to the $cword location.
|
||||
words=("${words[@]:0:$cword+1}")
|
||||
__%[1]s_debug "Truncated words[*]: ${words[*]},"
|
||||
|
||||
local out directive
|
||||
__%[1]s_get_completion_results
|
||||
__%[1]s_process_completion_results
|
||||
}
|
||||
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
complete -o default -F __start_%[1]s %[1]s
|
||||
else
|
||||
complete -o default -o nospace -F __start_%[1]s %[1]s
|
||||
fi
|
||||
|
||||
# ex: ts=4 sw=4 et filetype=sh
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
||||
// GenBashCompletionFileV2 generates Bash completion version 2.
|
||||
func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenBashCompletionV2(outFile, includeDesc)
|
||||
}
|
||||
|
||||
// GenBashCompletionV2 generates Bash completion file version 2
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {
|
||||
return c.genBashCompletion(w, includeDesc)
|
||||
}
|
25
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
25
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
|
@ -1,9 +1,10 @@
|
|||
// Copyright © 2013 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
|
@ -39,15 +40,25 @@ var templateFuncs = template.FuncMap{
|
|||
}
|
||||
|
||||
var initializers []func()
|
||||
var finalizers []func()
|
||||
|
||||
const (
|
||||
defaultPrefixMatching = false
|
||||
defaultCommandSorting = true
|
||||
defaultCaseInsensitive = false
|
||||
)
|
||||
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = false
|
||||
var EnablePrefixMatching = defaultPrefixMatching
|
||||
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// To disable sorting, set it to false.
|
||||
var EnableCommandSorting = true
|
||||
var EnableCommandSorting = defaultCommandSorting
|
||||
|
||||
// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
|
||||
var EnableCaseInsensitive = defaultCaseInsensitive
|
||||
|
||||
// MousetrapHelpText enables an information splash screen on Windows
|
||||
// if the CLI is started from explorer.exe.
|
||||
|
@ -84,6 +95,12 @@ func OnInitialize(y ...func()) {
|
|||
initializers = append(initializers, y...)
|
||||
}
|
||||
|
||||
// OnFinalize sets the passed functions to be run when each command's
|
||||
// Execute method is terminated.
|
||||
func OnFinalize(y ...func()) {
|
||||
finalizers = append(finalizers, y...)
|
||||
}
|
||||
|
||||
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
|
|
192
vendor/github.com/spf13/cobra/command.go
generated
vendored
192
vendor/github.com/spf13/cobra/command.go
generated
vendored
|
@ -1,9 +1,10 @@
|
|||
// Copyright © 2013 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
|
@ -18,6 +19,7 @@ package cobra
|
|||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
@ -28,9 +30,17 @@ import (
|
|||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
|
||||
|
||||
// FParseErrWhitelist configures Flag parse errors to be ignored
|
||||
type FParseErrWhitelist flag.ParseErrorsWhitelist
|
||||
|
||||
// Structure to manage groups for commands
|
||||
type Group struct {
|
||||
ID string
|
||||
Title string
|
||||
}
|
||||
|
||||
// Command is just that, a command for your application.
|
||||
// E.g. 'go run ...' - 'run' is the command. Cobra requires
|
||||
// you to define the usage and description as part of your command
|
||||
|
@ -57,15 +67,18 @@ type Command struct {
|
|||
// Short is the short description shown in the 'help' output.
|
||||
Short string
|
||||
|
||||
// The group id under which this subcommand is grouped in the 'help' output of its parent.
|
||||
GroupID string
|
||||
|
||||
// Long is the long message shown in the 'help <this-command>' output.
|
||||
Long string
|
||||
|
||||
// Example is examples of how to use the command.
|
||||
Example string
|
||||
|
||||
// ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
|
||||
// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
|
||||
ValidArgs []string
|
||||
// ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
|
||||
// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.
|
||||
// It is a dynamic version of using ValidArgs.
|
||||
// Only one of ValidArgs and ValidArgsFunction can be used for a command.
|
||||
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
|
@ -74,11 +87,12 @@ type Command struct {
|
|||
Args PositionalArgs
|
||||
|
||||
// ArgAliases is List of aliases for ValidArgs.
|
||||
// These are not suggested to the user in the bash completion,
|
||||
// These are not suggested to the user in the shell completion,
|
||||
// but accepted if entered manually.
|
||||
ArgAliases []string
|
||||
|
||||
// BashCompletionFunction is custom functions used by the bash autocompletion generator.
|
||||
// BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.
|
||||
// For portability with other shells, it is recommended to instead use ValidArgsFunction
|
||||
BashCompletionFunction string
|
||||
|
||||
// Deprecated defines, if this command is deprecated and should print this string when used.
|
||||
|
@ -123,6 +137,9 @@ type Command struct {
|
|||
// PersistentPostRunE: PersistentPostRun but returns an error.
|
||||
PersistentPostRunE func(cmd *Command, args []string) error
|
||||
|
||||
// groups for subcommands
|
||||
commandgroups []*Group
|
||||
|
||||
// args is actual args parsed from flags.
|
||||
args []string
|
||||
// flagErrorBuf contains all error messages from pflag.
|
||||
|
@ -155,6 +172,12 @@ type Command struct {
|
|||
// helpCommand is command with usage 'help'. If it's not defined by user,
|
||||
// cobra uses default help command.
|
||||
helpCommand *Command
|
||||
// helpCommandGroupID is the group id for the helpCommand
|
||||
helpCommandGroupID string
|
||||
|
||||
// completionCommandGroupID is the group id for the completion command
|
||||
completionCommandGroupID string
|
||||
|
||||
// versionTemplate is the version template defined by user.
|
||||
versionTemplate string
|
||||
|
||||
|
@ -165,9 +188,12 @@ type Command struct {
|
|||
// errWriter is a writer defined by the user that replaces stderr
|
||||
errWriter io.Writer
|
||||
|
||||
//FParseErrWhitelist flag parse errors to be ignored
|
||||
// FParseErrWhitelist flag parse errors to be ignored
|
||||
FParseErrWhitelist FParseErrWhitelist
|
||||
|
||||
// CompletionOptions is a set of options to control the handling of shell completion
|
||||
CompletionOptions CompletionOptions
|
||||
|
||||
// commandsAreSorted defines, if command slice are sorted or not.
|
||||
commandsAreSorted bool
|
||||
// commandCalledAs is the name or alias value used to call this command.
|
||||
|
@ -220,12 +246,23 @@ type Command struct {
|
|||
SuggestionsMinimumDistance int
|
||||
}
|
||||
|
||||
// Context returns underlying command context. If command wasn't
|
||||
// executed with ExecuteContext Context returns Background context.
|
||||
// Context returns underlying command context. If command was executed
|
||||
// with ExecuteContext or the context was set with SetContext, the
|
||||
// previously set context will be returned. Otherwise, nil is returned.
|
||||
//
|
||||
// Notice that a call to Execute and ExecuteC will replace a nil context of
|
||||
// a command with a context.Background, so a background context will be
|
||||
// returned by Context after one of these functions has been called.
|
||||
func (c *Command) Context() context.Context {
|
||||
return c.ctx
|
||||
}
|
||||
|
||||
// SetContext sets context for the command. This context will be overwritten by
|
||||
// Command.ExecuteContext or Command.ExecuteContextC.
|
||||
func (c *Command) SetContext(ctx context.Context) {
|
||||
c.ctx = ctx
|
||||
}
|
||||
|
||||
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
||||
// particularly useful when testing.
|
||||
func (c *Command) SetArgs(a []string) {
|
||||
|
@ -284,6 +321,21 @@ func (c *Command) SetHelpCommand(cmd *Command) {
|
|||
c.helpCommand = cmd
|
||||
}
|
||||
|
||||
// SetHelpCommandGroup sets the group id of the help command.
|
||||
func (c *Command) SetHelpCommandGroupID(groupID string) {
|
||||
if c.helpCommand != nil {
|
||||
c.helpCommand.GroupID = groupID
|
||||
}
|
||||
// helpCommandGroupID is used if no helpCommand is defined by the user
|
||||
c.helpCommandGroupID = groupID
|
||||
}
|
||||
|
||||
// SetCompletionCommandGroup 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
|
||||
}
|
||||
|
||||
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
|
||||
func (c *Command) SetHelpTemplate(s string) {
|
||||
c.helpTemplate = s
|
||||
|
@ -492,10 +544,16 @@ Aliases:
|
|||
{{.NameAndAliases}}{{end}}{{if .HasExample}}
|
||||
|
||||
Examples:
|
||||
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
|
||||
|
||||
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
|
||||
|
||||
{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
|
||||
|
||||
Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
|
||||
Flags:
|
||||
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
|
||||
|
@ -660,7 +718,7 @@ func (c *Command) findSuggestions(arg string) string {
|
|||
func (c *Command) findNext(next string) *Command {
|
||||
matches := make([]*Command, 0)
|
||||
for _, cmd := range c.commands {
|
||||
if cmd.Name() == next || cmd.HasAlias(next) {
|
||||
if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {
|
||||
cmd.commandCalledAs.name = next
|
||||
return cmd
|
||||
}
|
||||
|
@ -817,6 +875,8 @@ func (c *Command) execute(a []string) (err error) {
|
|||
|
||||
c.preRun()
|
||||
|
||||
defer c.postRun()
|
||||
|
||||
argWoFlags := c.Flags().Args()
|
||||
if c.DisableFlagParsing {
|
||||
argWoFlags = a
|
||||
|
@ -845,9 +905,13 @@ func (c *Command) execute(a []string) (err error) {
|
|||
c.PreRun(c, argWoFlags)
|
||||
}
|
||||
|
||||
if err := c.validateRequiredFlags(); err != nil {
|
||||
if err := c.ValidateRequiredFlags(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.ValidateFlagGroups(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if c.RunE != nil {
|
||||
if err := c.RunE(c, argWoFlags); err != nil {
|
||||
return err
|
||||
|
@ -883,8 +947,15 @@ func (c *Command) preRun() {
|
|||
}
|
||||
}
|
||||
|
||||
func (c *Command) postRun() {
|
||||
for _, x := range finalizers {
|
||||
x()
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteContext is the same as Execute(), but sets the ctx on the command.
|
||||
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.
|
||||
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
|
||||
// functions.
|
||||
func (c *Command) ExecuteContext(ctx context.Context) error {
|
||||
c.ctx = ctx
|
||||
return c.Execute()
|
||||
|
@ -898,6 +969,14 @@ func (c *Command) Execute() error {
|
|||
return err
|
||||
}
|
||||
|
||||
// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.
|
||||
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
|
||||
// functions.
|
||||
func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {
|
||||
c.ctx = ctx
|
||||
return c.ExecuteC()
|
||||
}
|
||||
|
||||
// ExecuteC executes the command.
|
||||
func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
if c.ctx == nil {
|
||||
|
@ -914,9 +993,14 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
preExecHookFn(c)
|
||||
}
|
||||
|
||||
// initialize help as the last point possible to allow for user
|
||||
// overriding
|
||||
// initialize help at the last point to allow for user overriding
|
||||
c.InitDefaultHelpCmd()
|
||||
// initialize completion at the last point to allow for user overriding
|
||||
c.InitDefaultCompletionCmd()
|
||||
|
||||
// Now that all commands have been created, let's make sure all groups
|
||||
// are properly created also
|
||||
c.checkCommandGroups()
|
||||
|
||||
args := c.args
|
||||
|
||||
|
@ -925,7 +1009,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
args = os.Args[1:]
|
||||
}
|
||||
|
||||
// initialize the hidden command to be used for bash completion
|
||||
// initialize the hidden command to be used for shell completion
|
||||
c.initCompleteCmd(args)
|
||||
|
||||
var flags []string
|
||||
|
@ -961,7 +1045,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
if err != nil {
|
||||
// Always show help if requested, even if SilenceErrors is in
|
||||
// effect
|
||||
if err == flag.ErrHelp {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
cmd.HelpFunc()(cmd, args)
|
||||
return cmd, nil
|
||||
}
|
||||
|
@ -983,12 +1067,13 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
|
||||
func (c *Command) ValidateArgs(args []string) error {
|
||||
if c.Args == nil {
|
||||
return nil
|
||||
return ArbitraryArgs(c, args)
|
||||
}
|
||||
return c.Args(c, args)
|
||||
}
|
||||
|
||||
func (c *Command) validateRequiredFlags() error {
|
||||
// ValidateRequiredFlags validates all required flags are present and returns an error otherwise
|
||||
func (c *Command) ValidateRequiredFlags() error {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
|
@ -1011,6 +1096,19 @@ func (c *Command) validateRequiredFlags() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// checkCommandGroups checks if a command has been added to a group that does not exists.
|
||||
// If so, we panic because it indicates a coding error that should be corrected.
|
||||
func (c *Command) checkCommandGroups() {
|
||||
for _, sub := range c.commands {
|
||||
// if Group is not defined let the developer know right away
|
||||
if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {
|
||||
panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))
|
||||
}
|
||||
|
||||
sub.checkCommandGroups()
|
||||
}
|
||||
}
|
||||
|
||||
// InitDefaultHelpFlag adds default help flag to c.
|
||||
// It is called automatically by executing the c or by calling help and usage.
|
||||
// If c already has help flag, it will do nothing.
|
||||
|
@ -1024,6 +1122,7 @@ func (c *Command) InitDefaultHelpFlag() {
|
|||
usage += c.Name()
|
||||
}
|
||||
c.Flags().BoolP("help", "h", false, usage)
|
||||
_ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1049,6 +1148,7 @@ func (c *Command) InitDefaultVersionFlag() {
|
|||
} else {
|
||||
c.Flags().Bool("version", false, usage)
|
||||
}
|
||||
_ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1091,10 +1191,12 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
|
|||
c.Printf("Unknown help topic %#q\n", args)
|
||||
CheckErr(c.Root().Usage())
|
||||
} else {
|
||||
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
|
||||
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
|
||||
cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
|
||||
CheckErr(cmd.Help())
|
||||
}
|
||||
},
|
||||
GroupID: c.helpCommandGroupID,
|
||||
}
|
||||
}
|
||||
c.RemoveCommand(c.helpCommand)
|
||||
|
@ -1155,6 +1257,36 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
|||
}
|
||||
}
|
||||
|
||||
// Groups returns a slice of child command groups.
|
||||
func (c *Command) Groups() []*Group {
|
||||
return c.commandgroups
|
||||
}
|
||||
|
||||
// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
|
||||
func (c *Command) AllChildCommandsHaveGroup() bool {
|
||||
for _, sub := range c.commands {
|
||||
if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ContainGroups 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 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AddGroup adds one or more command groups to this parent command.
|
||||
func (c *Command) AddGroup(groups ...*Group) {
|
||||
c.commandgroups = append(c.commandgroups, groups...)
|
||||
}
|
||||
|
||||
// RemoveCommand removes one or more commands from a parent command.
|
||||
func (c *Command) RemoveCommand(cmds ...*Command) {
|
||||
commands := []*Command{}
|
||||
|
@ -1298,7 +1430,7 @@ func (c *Command) Name() string {
|
|||
// HasAlias determines if a given string is an alias of the command.
|
||||
func (c *Command) HasAlias(s string) bool {
|
||||
for _, a := range c.Aliases {
|
||||
if a == s {
|
||||
if commandNameMatches(a, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
@ -1475,7 +1607,8 @@ func (c *Command) LocalFlags() *flag.FlagSet {
|
|||
}
|
||||
|
||||
addToLocal := func(f *flag.Flag) {
|
||||
if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {
|
||||
// Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
|
||||
if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
|
||||
c.lflags.AddFlag(f)
|
||||
}
|
||||
}
|
||||
|
@ -1664,3 +1797,14 @@ func (c *Command) updateParentsPflags() {
|
|||
c.parentsPflags.AddFlagSet(parent.PersistentFlags())
|
||||
})
|
||||
}
|
||||
|
||||
// commandNameMatches checks if two command names are equal
|
||||
// taking into account case sensitivity according to
|
||||
// EnableCaseInsensitive global configuration.
|
||||
func commandNameMatches(s string, t string) bool {
|
||||
if EnableCaseInsensitive {
|
||||
return strings.EqualFold(s, t)
|
||||
}
|
||||
|
||||
return s == t
|
||||
}
|
||||
|
|
15
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
15
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
|
@ -1,3 +1,18 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package cobra
|
||||
|
|
15
vendor/github.com/spf13/cobra/command_win.go
generated
vendored
15
vendor/github.com/spf13/cobra/command_win.go
generated
vendored
|
@ -1,3 +1,18 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package cobra
|
||||
|
|
|
@ -1,9 +1,24 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
@ -17,13 +32,25 @@ const (
|
|||
ShellCompNoDescRequestCmd = "__completeNoDesc"
|
||||
)
|
||||
|
||||
// Global map of flag completion functions.
|
||||
// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.
|
||||
var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
|
||||
|
||||
// lock for reading and writing from flagCompletionFunctions
|
||||
var flagCompletionMutex = &sync.RWMutex{}
|
||||
|
||||
// ShellCompDirective is a bit map representing the different behaviors the shell
|
||||
// can be instructed to have once completions have been provided.
|
||||
type ShellCompDirective int
|
||||
|
||||
type flagCompError struct {
|
||||
subCommand string
|
||||
flagName string
|
||||
}
|
||||
|
||||
func (e *flagCompError) Error() string {
|
||||
return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"
|
||||
}
|
||||
|
||||
const (
|
||||
// ShellCompDirectiveError indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError ShellCompDirective = 1 << iota
|
||||
|
@ -34,7 +61,6 @@ const (
|
|||
|
||||
// ShellCompDirectiveNoFileComp indicates that the shell should not provide
|
||||
// file completion even when no completion is provided.
|
||||
// This currently does not work for zsh or bash < 4
|
||||
ShellCompDirectiveNoFileComp
|
||||
|
||||
// ShellCompDirectiveFilterFileExt indicates that the provided completions
|
||||
|
@ -63,12 +89,51 @@ const (
|
|||
ShellCompDirectiveDefault ShellCompDirective = 0
|
||||
)
|
||||
|
||||
const (
|
||||
// Constants for the completion command
|
||||
compCmdName = "completion"
|
||||
compCmdNoDescFlagName = "no-descriptions"
|
||||
compCmdNoDescFlagDesc = "disable completion descriptions"
|
||||
compCmdNoDescFlagDefault = false
|
||||
)
|
||||
|
||||
// CompletionOptions are the options to control shell completion
|
||||
type CompletionOptions struct {
|
||||
// DisableDefaultCmd prevents Cobra from creating a default 'completion' command
|
||||
DisableDefaultCmd bool
|
||||
// DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag
|
||||
// for shells that support completion descriptions
|
||||
DisableNoDescFlag bool
|
||||
// DisableDescriptions turns off all completion descriptions for shells
|
||||
// that support them
|
||||
DisableDescriptions bool
|
||||
// HiddenDefaultCmd makes the default 'completion' command hidden
|
||||
HiddenDefaultCmd bool
|
||||
}
|
||||
|
||||
// NoFileCompletions can be used to disable file completion for commands that should
|
||||
// not trigger file completions.
|
||||
func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return nil, ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
||||
// FixedCompletions can be used to create a completion function which always
|
||||
// returns the same results.
|
||||
func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return choices, directive
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
|
||||
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
|
||||
flag := c.Flag(flagName)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
|
||||
}
|
||||
flagCompletionMutex.Lock()
|
||||
defer flagCompletionMutex.Unlock()
|
||||
|
||||
if _, exists := flagCompletionFunctions[flag]; exists {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)
|
||||
}
|
||||
|
@ -127,6 +192,12 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
|
||||
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
|
||||
for _, comp := range completions {
|
||||
if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
|
||||
// Remove all activeHelp entries in this case
|
||||
if strings.HasPrefix(comp, activeHelpMarker) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if noDescriptions {
|
||||
// Remove any description that may be included following a tab character.
|
||||
comp = strings.Split(comp, "\t")[0]
|
||||
|
@ -149,10 +220,6 @@ func (c *Command) initCompleteCmd(args []string) {
|
|||
fmt.Fprintln(finalCmd.OutOrStdout(), comp)
|
||||
}
|
||||
|
||||
if directive >= shellCompDirectiveMaxValue {
|
||||
directive = ShellCompDirectiveDefault
|
||||
}
|
||||
|
||||
// As the last printout, print the completion directive for the completion script to parse.
|
||||
// The directive integer must be that last character following a single colon (:).
|
||||
// The completion script expects :<directive>
|
||||
|
@ -189,29 +256,75 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
if c.Root().TraverseChildren {
|
||||
finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)
|
||||
} else {
|
||||
finalCmd, finalArgs, err = c.Root().Find(trimmedArgs)
|
||||
// For Root commands that don't specify any value for their Args fields, when we call
|
||||
// Find(), if those Root commands don't have any sub-commands, they will accept arguments.
|
||||
// However, because we have added the __complete sub-command in the current code path, the
|
||||
// call to Find() -> legacyArgs() will return an error if there are any arguments.
|
||||
// To avoid this, we first remove the __complete command to get back to having no sub-commands.
|
||||
rootCmd := c.Root()
|
||||
if len(rootCmd.Commands()) == 1 {
|
||||
rootCmd.RemoveCommand(c)
|
||||
}
|
||||
|
||||
finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)
|
||||
}
|
||||
if err != nil {
|
||||
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
|
||||
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
|
||||
}
|
||||
finalCmd.ctx = c.ctx
|
||||
|
||||
// These flags are normally added when `execute()` is called on `finalCmd`,
|
||||
// however, when doing completion, we don't call `finalCmd.execute()`.
|
||||
// Let's add the --help and --version flag ourselves.
|
||||
finalCmd.InitDefaultHelpFlag()
|
||||
finalCmd.InitDefaultVersionFlag()
|
||||
|
||||
// Check if we are doing flag value completion before parsing the flags.
|
||||
// This is important because if we are completing a flag value, we need to also
|
||||
// remove the flag name argument from the list of finalArgs or else the parsing
|
||||
// could fail due to an invalid value (incomplete) for the flag.
|
||||
flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
|
||||
if err != nil {
|
||||
// Error while attempting to parse flags
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, err
|
||||
}
|
||||
flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
|
||||
|
||||
// Check if interspersed is false or -- was set on a previous arg.
|
||||
// This works by counting the arguments. Normally -- is not counted as arg but
|
||||
// if -- was already set or interspersed is false and there is already one arg then
|
||||
// the extra added -- is counted as arg.
|
||||
flagCompletion := true
|
||||
_ = finalCmd.ParseFlags(append(finalArgs, "--"))
|
||||
newArgCount := finalCmd.Flags().NArg()
|
||||
|
||||
// Parse the flags early so we can check if required flags are set
|
||||
if err = finalCmd.ParseFlags(finalArgs); err != nil {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
}
|
||||
|
||||
if flag != nil {
|
||||
realArgCount := finalCmd.Flags().NArg()
|
||||
if newArgCount > realArgCount {
|
||||
// don't do flag completion (see above)
|
||||
flagCompletion = false
|
||||
}
|
||||
// Error while attempting to parse flags
|
||||
if flagErr != nil {
|
||||
// If error type is flagCompError and we don't want flagCompletion we should ignore the error
|
||||
if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
// Look for the --help or --version flags. If they are present,
|
||||
// there should be no further completions.
|
||||
if helpOrVersionFlagPresent(finalCmd) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil
|
||||
}
|
||||
|
||||
// We only remove the flags from the arguments if DisableFlagParsing is not set.
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
finalArgs = finalCmd.Flags().Args()
|
||||
}
|
||||
|
||||
if flag != nil && flagCompletion {
|
||||
// Check if we are completing a flag value subject to annotations
|
||||
if validExts, present := flag.Annotations[BashCompFilenameExt]; present {
|
||||
if len(validExts) != 0 {
|
||||
|
@ -235,12 +348,19 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
var directive ShellCompDirective
|
||||
|
||||
// Enforce flag groups before doing flag completions
|
||||
finalCmd.enforceFlagGroupsForCompletion()
|
||||
|
||||
// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;
|
||||
// doing this allows for completion of persistent flag names even for commands that disable flag parsing.
|
||||
//
|
||||
// When doing completion of a flag name, as soon as an argument starts with
|
||||
// a '-' we know it is a flag. We cannot use isFlagArg() here as it requires
|
||||
// the flag name to be complete
|
||||
if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {
|
||||
var completions []string
|
||||
|
||||
if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {
|
||||
// First check for required flags
|
||||
completions = completeRequireFlags(finalCmd, toComplete)
|
||||
|
||||
|
@ -267,92 +387,94 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
})
|
||||
}
|
||||
|
||||
directive := ShellCompDirectiveNoFileComp
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {
|
||||
// If there is a single completion, the shell usually adds a space
|
||||
// after the completion. We don't want that if the flag ends with an =
|
||||
directive = ShellCompDirectiveNoSpace
|
||||
}
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
// We only remove the flags from the arguments if DisableFlagParsing is not set.
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
finalArgs = finalCmd.Flags().Args()
|
||||
}
|
||||
|
||||
var completions []string
|
||||
directive := ShellCompDirectiveDefault
|
||||
if flag == nil {
|
||||
foundLocalNonPersistentFlag := false
|
||||
// If TraverseChildren is true on the root command we don't check for
|
||||
// local flags because we can use a local flag on a parent command
|
||||
if !finalCmd.Root().TraverseChildren {
|
||||
// Check if there are any local, non-persistent flags on the command-line
|
||||
localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {
|
||||
foundLocalNonPersistentFlag = true
|
||||
}
|
||||
})
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
// If DisableFlagParsing==false, we have completed the flags as known by Cobra;
|
||||
// we can return what we found.
|
||||
// If DisableFlagParsing==true, Cobra may not be aware of all flags, so we
|
||||
// let the logic continue to see if ValidArgsFunction needs to be called.
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
// Complete subcommand names, including the help command
|
||||
if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {
|
||||
// We only complete sub-commands if:
|
||||
// - there are no arguments on the command-line and
|
||||
// - there are no local, non-peristent flag on the command-line or TraverseChildren is true
|
||||
for _, subCmd := range finalCmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
|
||||
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
} else {
|
||||
directive = ShellCompDirectiveDefault
|
||||
if flag == nil {
|
||||
foundLocalNonPersistentFlag := false
|
||||
// If TraverseChildren is true on the root command we don't check for
|
||||
// local flags because we can use a local flag on a parent command
|
||||
if !finalCmd.Root().TraverseChildren {
|
||||
// Check if there are any local, non-persistent flags on the command-line
|
||||
localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {
|
||||
foundLocalNonPersistentFlag = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Complete subcommand names, including the help command
|
||||
if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {
|
||||
// We only complete sub-commands if:
|
||||
// - there are no arguments on the command-line and
|
||||
// - there are no local, non-persistent flags on the command-line or TraverseChildren is true
|
||||
for _, subCmd := range finalCmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
|
||||
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Complete required flags even without the '-' prefix
|
||||
completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)
|
||||
// Complete required flags even without the '-' prefix
|
||||
completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)
|
||||
|
||||
// Always complete ValidArgs, even if we are completing a subcommand name.
|
||||
// This is for commands that have both subcommands and ValidArgs.
|
||||
if len(finalCmd.ValidArgs) > 0 {
|
||||
if len(finalArgs) == 0 {
|
||||
// ValidArgs are only for the first argument
|
||||
for _, validArg := range finalCmd.ValidArgs {
|
||||
if strings.HasPrefix(validArg, toComplete) {
|
||||
completions = append(completions, validArg)
|
||||
// Always complete ValidArgs, even if we are completing a subcommand name.
|
||||
// This is for commands that have both subcommands and ValidArgs.
|
||||
if len(finalCmd.ValidArgs) > 0 {
|
||||
if len(finalArgs) == 0 {
|
||||
// ValidArgs are only for the first argument
|
||||
for _, validArg := range finalCmd.ValidArgs {
|
||||
if strings.HasPrefix(validArg, toComplete) {
|
||||
completions = append(completions, validArg)
|
||||
}
|
||||
}
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
|
||||
// If no completions were found within commands or ValidArgs,
|
||||
// see if there are any ArgAliases that should be completed.
|
||||
if len(completions) == 0 {
|
||||
for _, argAlias := range finalCmd.ArgAliases {
|
||||
if strings.HasPrefix(argAlias, toComplete) {
|
||||
completions = append(completions, argAlias)
|
||||
// If no completions were found within commands or ValidArgs,
|
||||
// see if there are any ArgAliases that should be completed.
|
||||
if len(completions) == 0 {
|
||||
for _, argAlias := range finalCmd.ArgAliases {
|
||||
if strings.HasPrefix(argAlias, toComplete) {
|
||||
completions = append(completions, argAlias)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If there are ValidArgs specified (even if they don't match), we stop completion.
|
||||
// Only one of ValidArgs or ValidArgsFunction can be used for a single command.
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
// If there are ValidArgs specified (even if they don't match), we stop completion.
|
||||
// Only one of ValidArgs or ValidArgsFunction can be used for a single command.
|
||||
return finalCmd, completions, directive, nil
|
||||
// Let the logic continue so as to add any ValidArgsFunction completions,
|
||||
// even if we already found sub-commands.
|
||||
// This is for commands that have subcommands but also specify a ValidArgsFunction.
|
||||
}
|
||||
|
||||
// Let the logic continue so as to add any ValidArgsFunction completions,
|
||||
// even if we already found sub-commands.
|
||||
// This is for commands that have subcommands but also specify a ValidArgsFunction.
|
||||
}
|
||||
|
||||
// Find the completion function for the flag or command
|
||||
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
if flag != nil {
|
||||
if flag != nil && flagCompletion {
|
||||
flagCompletionMutex.RLock()
|
||||
completionFn = flagCompletionFunctions[flag]
|
||||
flagCompletionMutex.RUnlock()
|
||||
} else {
|
||||
completionFn = finalCmd.ValidArgsFunction
|
||||
}
|
||||
|
@ -367,6 +489,18 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
|
|||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
func helpOrVersionFlagPresent(cmd *Command) bool {
|
||||
if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&
|
||||
len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
|
||||
return true
|
||||
}
|
||||
if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&
|
||||
len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
||||
if nonCompletableFlag(flag) {
|
||||
return []string{}
|
||||
|
@ -435,6 +569,7 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
var flagName string
|
||||
trimmedArgs := args
|
||||
flagWithEqual := false
|
||||
orgLastArg := lastArg
|
||||
|
||||
// When doing completion of a flag name, as soon as an argument starts with
|
||||
// a '-' we know it is a flag. We cannot use isFlagArg() here as that function
|
||||
|
@ -442,7 +577,16 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
if len(lastArg) > 0 && lastArg[0] == '-' {
|
||||
if index := strings.Index(lastArg, "="); index >= 0 {
|
||||
// Flag with an =
|
||||
flagName = strings.TrimLeft(lastArg[:index], "-")
|
||||
if strings.HasPrefix(lastArg[:index], "--") {
|
||||
// Flag has full name
|
||||
flagName = lastArg[2:index]
|
||||
} else {
|
||||
// Flag is shorthand
|
||||
// We have to get the last shorthand flag name
|
||||
// e.g. `-asd` => d to provide the correct completion
|
||||
// https://github.com/spf13/cobra/issues/1257
|
||||
flagName = lastArg[index-1 : index]
|
||||
}
|
||||
lastArg = lastArg[index+1:]
|
||||
flagWithEqual = true
|
||||
} else {
|
||||
|
@ -459,8 +603,16 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
// If the flag contains an = it means it has already been fully processed,
|
||||
// so we don't need to deal with it here.
|
||||
if index := strings.Index(prevArg, "="); index < 0 {
|
||||
flagName = strings.TrimLeft(prevArg, "-")
|
||||
|
||||
if strings.HasPrefix(prevArg, "--") {
|
||||
// Flag has full name
|
||||
flagName = prevArg[2:]
|
||||
} else {
|
||||
// Flag is shorthand
|
||||
// We have to get the last shorthand flag name
|
||||
// e.g. `-asd` => d to provide the correct completion
|
||||
// https://github.com/spf13/cobra/issues/1257
|
||||
flagName = prevArg[len(prevArg)-1:]
|
||||
}
|
||||
// Remove the uncompleted flag or else there could be an error created
|
||||
// for an invalid value for that flag
|
||||
trimmedArgs = args[:len(args)-1]
|
||||
|
@ -476,9 +628,8 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
|
||||
flag := findFlag(finalCmd, flagName)
|
||||
if flag == nil {
|
||||
// Flag not supported by this command, nothing to complete
|
||||
err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)
|
||||
return nil, nil, "", err
|
||||
// Flag not supported by this command, the interspersed option might be set so return the original args
|
||||
return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}
|
||||
}
|
||||
|
||||
if !flagWithEqual {
|
||||
|
@ -494,6 +645,169 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p
|
|||
return flag, trimmedArgs, lastArg, nil
|
||||
}
|
||||
|
||||
// InitDefaultCompletionCmd adds a default 'completion' command to c.
|
||||
// This function will do nothing if any of the following is true:
|
||||
// 1- the feature has been explicitly disabled by the program,
|
||||
// 2- c has no subcommands (to avoid creating one),
|
||||
// 3- c already has a 'completion' command provided by the program.
|
||||
func (c *Command) InitDefaultCompletionCmd() {
|
||||
if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
|
||||
return
|
||||
}
|
||||
|
||||
for _, cmd := range c.commands {
|
||||
if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {
|
||||
// A completion command is already available
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions
|
||||
|
||||
completionCmd := &Command{
|
||||
Use: compCmdName,
|
||||
Short: "Generate the autocompletion script for the specified shell",
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.
|
||||
See each sub-command's help for details on how to use the generated script.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
Hidden: c.CompletionOptions.HiddenDefaultCmd,
|
||||
GroupID: c.completionCommandGroupID,
|
||||
}
|
||||
c.AddCommand(completionCmd)
|
||||
|
||||
out := c.OutOrStdout()
|
||||
noDesc := c.CompletionOptions.DisableDescriptions
|
||||
shortDesc := "Generate the autocompletion script for %s"
|
||||
bash := &Command{
|
||||
Use: "bash",
|
||||
Short: fmt.Sprintf(shortDesc, "bash"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell.
|
||||
|
||||
This script depends on the 'bash-completion' package.
|
||||
If it is not installed already, you can install it via your OS's package manager.
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
source <(%[1]s completion bash)
|
||||
|
||||
To load completions for every new 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
|
||||
|
||||
You will need to start a new shell for this setup to take effect.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
return cmd.Root().GenBashCompletionV2(out, !noDesc)
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
zsh := &Command{
|
||||
Use: "zsh",
|
||||
Short: fmt.Sprintf(shortDesc, "zsh"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell.
|
||||
|
||||
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 in your current shell session:
|
||||
|
||||
source <(%[1]s completion zsh); compdef _%[1]s %[1]s
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
#### Linux:
|
||||
|
||||
%[1]s completion zsh > "${fpath[1]}/_%[1]s"
|
||||
|
||||
#### macOS:
|
||||
|
||||
%[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s
|
||||
|
||||
You will need to start a new shell for this setup to take effect.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
if noDesc {
|
||||
return cmd.Root().GenZshCompletionNoDesc(out)
|
||||
}
|
||||
return cmd.Root().GenZshCompletion(out)
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
fish := &Command{
|
||||
Use: "fish",
|
||||
Short: fmt.Sprintf(shortDesc, "fish"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell.
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
%[1]s completion fish | source
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
%[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
|
||||
|
||||
You will need to start a new shell for this setup to take effect.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
return cmd.Root().GenFishCompletion(out, !noDesc)
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
powershell := &Command{
|
||||
Use: "powershell",
|
||||
Short: fmt.Sprintf(shortDesc, "powershell"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for powershell.
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
%[1]s completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
To load completions for every new session, add the output of the above command
|
||||
to your powershell profile.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
if noDesc {
|
||||
return cmd.Root().GenPowerShellCompletion(out)
|
||||
}
|
||||
return cmd.Root().GenPowerShellCompletionWithDesc(out)
|
||||
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
completionCmd.AddCommand(bash, zsh, fish, powershell)
|
||||
}
|
||||
|
||||
func findFlag(cmd *Command, name string) *pflag.Flag {
|
||||
flagSet := cmd.Flags()
|
||||
if len(name) == 1 {
|
197
vendor/github.com/spf13/cobra/fish_completions.go
generated
vendored
197
vendor/github.com/spf13/cobra/fish_completions.go
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
|
@ -11,8 +25,8 @@ import (
|
|||
func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
|
||||
nameForVar = strings.Replace(nameForVar, ":", "_", -1)
|
||||
nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
|
||||
nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
|
@ -21,44 +35,48 @@ func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
|
|||
WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`
|
||||
function __%[1]s_debug
|
||||
set file "$BASH_COMP_DEBUG_FILE"
|
||||
set -l file "$BASH_COMP_DEBUG_FILE"
|
||||
if test -n "$file"
|
||||
echo "$argv" >> $file
|
||||
end
|
||||
end
|
||||
|
||||
function __%[1]s_perform_completion
|
||||
__%[1]s_debug "Starting __%[1]s_perform_completion with: $argv"
|
||||
__%[1]s_debug "Starting __%[1]s_perform_completion"
|
||||
|
||||
set args (string split -- " " "$argv")
|
||||
set lastArg "$args[-1]"
|
||||
# Extract all args except the last one
|
||||
set -l args (commandline -opc)
|
||||
# Extract the last arg and escape it in case it is a space
|
||||
set -l lastArg (string escape -- (commandline -ct))
|
||||
|
||||
__%[1]s_debug "args: $args"
|
||||
__%[1]s_debug "last arg: $lastArg"
|
||||
|
||||
set emptyArg ""
|
||||
if test -z "$lastArg"
|
||||
__%[1]s_debug "Setting emptyArg"
|
||||
set emptyArg \"\"
|
||||
end
|
||||
__%[1]s_debug "emptyArg: $emptyArg"
|
||||
# Disable ActiveHelp which is not supported for fish shell
|
||||
set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
|
||||
|
||||
if not type -q "$args[1]"
|
||||
# This can happen when "complete --do-complete %[2]s" is called when running this script.
|
||||
__%[1]s_debug "Cannot find $args[1]. No completions."
|
||||
return
|
||||
end
|
||||
|
||||
set requestComp "$args[1] %[3]s $args[2..-1] $emptyArg"
|
||||
__%[1]s_debug "Calling $requestComp"
|
||||
set -l results (eval $requestComp 2> /dev/null)
|
||||
|
||||
set results (eval $requestComp 2> /dev/null)
|
||||
set comps $results[1..-2]
|
||||
set directiveLine $results[-1]
|
||||
# Some programs may output extra empty lines after the directive.
|
||||
# Let's ignore them or else it will break completion.
|
||||
# Ref: https://github.com/spf13/cobra/issues/1279
|
||||
for line in $results[-1..1]
|
||||
if test (string trim -- $line) = ""
|
||||
# Found an empty line, remove it
|
||||
set results $results[1..-2]
|
||||
else
|
||||
# Found non-empty line, we have our proper output
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
set -l comps $results[1..-2]
|
||||
set -l directiveLine $results[-1]
|
||||
|
||||
# For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
|
||||
# completions must be prefixed with the flag
|
||||
set flagPrefix (string match -r -- '-.*=' "$lastArg")
|
||||
set -l flagPrefix (string match -r -- '-.*=' "$lastArg")
|
||||
|
||||
__%[1]s_debug "Comps: $comps"
|
||||
__%[1]s_debug "DirectiveLine: $directiveLine"
|
||||
|
@ -71,120 +89,129 @@ function __%[1]s_perform_completion
|
|||
printf "%%s\n" "$directiveLine"
|
||||
end
|
||||
|
||||
# This function does three things:
|
||||
# 1- Obtain the completions and store them in the global __%[1]s_comp_results
|
||||
# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed
|
||||
# and unset it otherwise
|
||||
# 3- Return true if the completion results are not empty
|
||||
# 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
|
||||
function __%[1]s_prepare_completions
|
||||
__%[1]s_debug ""
|
||||
__%[1]s_debug "========= starting completion logic =========="
|
||||
|
||||
# Start fresh
|
||||
set --erase __%[1]s_comp_do_file_comp
|
||||
set --erase __%[1]s_comp_results
|
||||
|
||||
# Check if the command-line is already provided. This is useful for testing.
|
||||
if not set --query __%[1]s_comp_commandLine
|
||||
# Use the -c flag to allow for completion in the middle of the line
|
||||
set __%[1]s_comp_commandLine (commandline -c)
|
||||
end
|
||||
__%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine"
|
||||
|
||||
set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")
|
||||
set --erase __%[1]s_comp_commandLine
|
||||
set -l results (__%[1]s_perform_completion)
|
||||
__%[1]s_debug "Completion results: $results"
|
||||
|
||||
if test -z "$results"
|
||||
__%[1]s_debug "No completion, probably due to a failure"
|
||||
# Might as well do file completion, in case it helps
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
return 1
|
||||
end
|
||||
|
||||
set directive (string sub --start 2 $results[-1])
|
||||
set -l directive (string sub --start 2 $results[-1])
|
||||
set --global __%[1]s_comp_results $results[1..-2]
|
||||
|
||||
__%[1]s_debug "Completions are: $__%[1]s_comp_results"
|
||||
__%[1]s_debug "Directive is: $directive"
|
||||
|
||||
set shellCompDirectiveError %[4]d
|
||||
set shellCompDirectiveNoSpace %[5]d
|
||||
set shellCompDirectiveNoFileComp %[6]d
|
||||
set shellCompDirectiveFilterFileExt %[7]d
|
||||
set shellCompDirectiveFilterDirs %[8]d
|
||||
set -l shellCompDirectiveError %[4]d
|
||||
set -l shellCompDirectiveNoSpace %[5]d
|
||||
set -l shellCompDirectiveNoFileComp %[6]d
|
||||
set -l shellCompDirectiveFilterFileExt %[7]d
|
||||
set -l shellCompDirectiveFilterDirs %[8]d
|
||||
|
||||
if test -z "$directive"
|
||||
set directive 0
|
||||
end
|
||||
|
||||
set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)
|
||||
set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)
|
||||
if test $compErr -eq 1
|
||||
__%[1]s_debug "Received error directive: aborting."
|
||||
# Might as well do file completion, in case it helps
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
return 1
|
||||
end
|
||||
|
||||
set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)
|
||||
set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)
|
||||
set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)
|
||||
set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)
|
||||
if test $filefilter -eq 1; or test $dirfilter -eq 1
|
||||
__%[1]s_debug "File extension filtering or directory filtering not supported"
|
||||
# Do full file completion instead
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
return 1
|
||||
end
|
||||
|
||||
set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)
|
||||
set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)
|
||||
set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)
|
||||
set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)
|
||||
|
||||
__%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
|
||||
|
||||
# Important not to quote the variable for count to work
|
||||
set numComps (count $__%[1]s_comp_results)
|
||||
__%[1]s_debug "numComps: $numComps"
|
||||
# If we want to prevent a space, or if file completion is NOT disabled,
|
||||
# we need to count the number of valid completions.
|
||||
# To do so, we will filter on prefix as the completions we have received
|
||||
# may not already be filtered so as to allow fish to match on different
|
||||
# criteria than the prefix.
|
||||
if test $nospace -ne 0; or test $nofiles -eq 0
|
||||
set -l prefix (commandline -t | string escape --style=regex)
|
||||
__%[1]s_debug "prefix: $prefix"
|
||||
|
||||
if test $numComps -eq 1; and test $nospace -ne 0
|
||||
# To support the "nospace" directive we trick the shell
|
||||
# by outputting an extra, longer completion.
|
||||
__%[1]s_debug "Adding second completion to perform nospace directive"
|
||||
set --append __%[1]s_comp_results $__%[1]s_comp_results[1].
|
||||
set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results)
|
||||
set --global __%[1]s_comp_results $completions
|
||||
__%[1]s_debug "Filtered completions are: $__%[1]s_comp_results"
|
||||
|
||||
# Important not to quote the variable for count to work
|
||||
set -l numComps (count $__%[1]s_comp_results)
|
||||
__%[1]s_debug "numComps: $numComps"
|
||||
|
||||
if test $numComps -eq 1; and test $nospace -ne 0
|
||||
# We must first split on \t to get rid of the descriptions to be
|
||||
# able to check what the actual completion will be.
|
||||
# We don't need descriptions anyway since there is only a single
|
||||
# real completion which the shell will expand immediately.
|
||||
set -l split (string split --max 1 \t $__%[1]s_comp_results[1])
|
||||
|
||||
# Fish won't add a space if the completion ends with any
|
||||
# of the following characters: @=/:.,
|
||||
set -l lastChar (string sub -s -1 -- $split)
|
||||
if not string match -r -q "[@=/:.,]" -- "$lastChar"
|
||||
# In other cases, to support the "nospace" directive we trick the shell
|
||||
# by outputting an extra, longer completion.
|
||||
__%[1]s_debug "Adding second completion to perform nospace directive"
|
||||
set --global __%[1]s_comp_results $split[1] $split[1].
|
||||
__%[1]s_debug "Completions are now: $__%[1]s_comp_results"
|
||||
end
|
||||
end
|
||||
|
||||
if test $numComps -eq 0; and test $nofiles -eq 0
|
||||
# To be consistent with bash and zsh, we only trigger file
|
||||
# completion when there are no other completions
|
||||
__%[1]s_debug "Requesting file completion"
|
||||
return 1
|
||||
end
|
||||
end
|
||||
|
||||
if test $numComps -eq 0; and test $nofiles -eq 0
|
||||
__%[1]s_debug "Requesting file completion"
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
end
|
||||
|
||||
# If we don't want file completion, we must return true even if there
|
||||
# are no completions found. This is because fish will perform the last
|
||||
# completion command, even if its condition is false, if no other
|
||||
# completion command was triggered
|
||||
return (not set --query __%[1]s_comp_do_file_comp)
|
||||
return 0
|
||||
end
|
||||
|
||||
# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
|
||||
# so we can properly delete any completions provided by another script.
|
||||
# The space after the the program name is essential to trigger completion for the program
|
||||
# and not completion of the program name itself.
|
||||
complete --do-complete "%[2]s " > /dev/null 2>&1
|
||||
# Using '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
|
||||
# Only do this if the program can be found, or else fish may print some errors; besides,
|
||||
# the existing completions will only be loaded if the program can be found.
|
||||
if type -q "%[2]s"
|
||||
# The space after the program name is essential to trigger completion for the program
|
||||
# and not completion of the program name itself.
|
||||
# Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
|
||||
complete --do-complete "%[2]s " > /dev/null 2>&1
|
||||
end
|
||||
|
||||
# Remove any pre-existing completions for the program since we will be handling all of them.
|
||||
complete -c %[2]s -e
|
||||
|
||||
# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions
|
||||
# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable.
|
||||
#
|
||||
# This completion will be run second as complete commands are added FILO.
|
||||
# It triggers file completion choices when __%[1]s_comp_do_file_comp is set.
|
||||
complete -c %[2]s -n 'set --query __%[1]s_comp_do_file_comp'
|
||||
|
||||
# This completion will be run first as complete commands are added FILO.
|
||||
# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results and __%[1]s_comp_do_file_comp.
|
||||
# It provides the program's completion choices.
|
||||
# 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'
|
||||
|
||||
`, nameForVar, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
// GenFishCompletion generates fish completion file and writes to the passed writer.
|
||||
|
|
224
vendor/github.com/spf13/cobra/flag_groups.go
generated
vendored
Normal file
224
vendor/github.com/spf13/cobra/flag_groups.go
generated
vendored
Normal file
|
@ -0,0 +1,224 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
requiredAsGroup = "cobra_annotation_required_if_others_set"
|
||||
mutuallyExclusive = "cobra_annotation_mutually_exclusive"
|
||||
)
|
||||
|
||||
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked with a subset (but not all) of the given flags.
|
||||
func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))
|
||||
}
|
||||
if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil {
|
||||
// Only errs if the flag isn't found.
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked with more than one flag from the given set of flags.
|
||||
func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))
|
||||
}
|
||||
// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.
|
||||
if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the
|
||||
// first error encountered.
|
||||
func (c *Command) ValidateFlagGroups() error {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
|
||||
flags := c.Flags()
|
||||
|
||||
// groupStatus format is the list of flags as a unique ID,
|
||||
// then a map of each flag name and whether it is set or not.
|
||||
groupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
flags.VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
if err := validateRequiredFlagGroups(groupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {
|
||||
for _, fname := range flagnames {
|
||||
f := fs.Lookup(fname)
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {
|
||||
groupInfo, found := pflag.Annotations[annotation]
|
||||
if found {
|
||||
for _, group := range groupInfo {
|
||||
if groupStatus[group] == nil {
|
||||
flagnames := strings.Split(group, " ")
|
||||
|
||||
// Only consider this flag group at all if all the flags are defined.
|
||||
if !hasAllFlags(flags, flagnames...) {
|
||||
continue
|
||||
}
|
||||
|
||||
groupStatus[group] = map[string]bool{}
|
||||
for _, name := range flagnames {
|
||||
groupStatus[group][name] = false
|
||||
}
|
||||
}
|
||||
|
||||
groupStatus[group][pflag.Name] = pflag.Changed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateRequiredFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
|
||||
unset := []string{}
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if !isSet {
|
||||
unset = append(unset, flagname)
|
||||
}
|
||||
}
|
||||
if len(unset) == len(flagnameAndStatus) || len(unset) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(unset)
|
||||
return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
var set []string
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
set = append(set, flagname)
|
||||
}
|
||||
}
|
||||
if len(set) == 0 || len(set) == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(set)
|
||||
return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]map[string]bool) []string {
|
||||
keys := make([]string, len(m))
|
||||
i := 0
|
||||
for k := range m {
|
||||
keys[i] = k
|
||||
i++
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// enforceFlagGroupsForCompletion will do the following:
|
||||
// - when a flag in a group is present, other flags in the group will be marked required
|
||||
// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
|
||||
// This allows the standard completion logic to behave appropriately for flag groups
|
||||
func (c *Command) enforceFlagGroupsForCompletion() {
|
||||
if c.DisableFlagParsing {
|
||||
return
|
||||
}
|
||||
|
||||
flags := c.Flags()
|
||||
groupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
c.Flags().VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
// If a flag that is part of a group is present, we make all the other flags
|
||||
// of that group required so that the shell completion suggests them automatically
|
||||
for flagList, flagnameAndStatus := range groupStatus {
|
||||
for _, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
// One of the flags of the group is set, mark the other ones as required
|
||||
for _, fName := range strings.Split(flagList, " ") {
|
||||
_ = c.MarkFlagRequired(fName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If a flag that is mutually exclusive to others is present, we hide the other
|
||||
// flags of that group so the shell completion does not suggest them
|
||||
for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {
|
||||
for flagName, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
// One of the flags of the mutually exclusive group is set, mark the other ones as hidden
|
||||
// Don't mark the flag that is already set as hidden because it may be an
|
||||
// array or slice flag and therefore must continue being suggested
|
||||
for _, fName := range strings.Split(flagList, " ") {
|
||||
if fName != flagName {
|
||||
flag := c.Flags().Lookup(fName)
|
||||
flag.Hidden = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
93
vendor/github.com/spf13/cobra/powershell_completions.go
generated
vendored
93
vendor/github.com/spf13/cobra/powershell_completions.go
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
|
||||
// can be downloaded separately for windows 7 or 8.1).
|
||||
|
||||
|
@ -8,9 +22,15 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
|
||||
nameForVar = strings.Replace(nameForVar, ":", "_", -1)
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
|
@ -27,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars {
|
|||
`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
||||
[scriptblock]$__%[2]sCompleterBlock = {
|
||||
param(
|
||||
$WordToComplete,
|
||||
$CommandAst,
|
||||
|
@ -50,18 +70,19 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
if ($Command.Length -gt $CursorPosition) {
|
||||
$Command=$Command.Substring(0,$CursorPosition)
|
||||
}
|
||||
__%[1]s_debug "Truncated command: $Command"
|
||||
__%[1]s_debug "Truncated command: $Command"
|
||||
|
||||
$ShellCompDirectiveError=%[3]d
|
||||
$ShellCompDirectiveNoSpace=%[4]d
|
||||
$ShellCompDirectiveNoFileComp=%[5]d
|
||||
$ShellCompDirectiveFilterFileExt=%[6]d
|
||||
$ShellCompDirectiveFilterDirs=%[7]d
|
||||
$ShellCompDirectiveError=%[4]d
|
||||
$ShellCompDirectiveNoSpace=%[5]d
|
||||
$ShellCompDirectiveNoFileComp=%[6]d
|
||||
$ShellCompDirectiveFilterFileExt=%[7]d
|
||||
$ShellCompDirectiveFilterDirs=%[8]d
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Prepare the command to request completions for the program.
|
||||
# Split the command at the first space to separate the program and arguments.
|
||||
$Program,$Arguments = $Command.Split(" ",2)
|
||||
$RequestComp="$Program %[2]s $Arguments"
|
||||
|
||||
$RequestComp="$Program %[3]s $Arguments"
|
||||
__%[1]s_debug "RequestComp: $RequestComp"
|
||||
|
||||
# we cannot use $WordToComplete because it
|
||||
|
@ -86,15 +107,17 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
# 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\" + ' `\"`\"' "+`
|
||||
`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
|
||||
}
|
||||
|
||||
__%[1]s_debug "Calling $RequestComp"
|
||||
# First disable ActiveHelp which is not supported for Powershell
|
||||
$env:%[9]s=0
|
||||
|
||||
#call the command store the output in $out and redirect stderr and stdout to null
|
||||
# $Out is an array contains each line per element
|
||||
Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
|
||||
|
||||
|
||||
# get directive from last line
|
||||
[int]$Directive = $Out[-1].TrimStart(':')
|
||||
if ($Directive -eq "") {
|
||||
|
@ -140,6 +163,25 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
$Space = ""
|
||||
}
|
||||
|
||||
if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
|
||||
(($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
|
||||
__%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
|
||||
|
||||
# return here to prevent the completion of the extensions
|
||||
return
|
||||
}
|
||||
|
||||
$Values = $Values | Where-Object {
|
||||
# filter the result
|
||||
$_.Name -like "$WordToComplete*"
|
||||
|
||||
# Join the flag back if we have an equal sign flag
|
||||
if ( $IsEqualFlag ) {
|
||||
__%[1]s_debug "Join the equal sign flag back to the completion value"
|
||||
$_.Name = $Flag + "=" + $_.Name
|
||||
}
|
||||
}
|
||||
|
||||
if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
|
||||
__%[1]s_debug "ShellCompDirectiveNoFileComp is called"
|
||||
|
||||
|
@ -153,32 +195,13 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
}
|
||||
}
|
||||
|
||||
if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
|
||||
(($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
|
||||
__%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
|
||||
|
||||
# return here to prevent the completion of the extensions
|
||||
return
|
||||
}
|
||||
|
||||
$Values = $Values | Where-Object {
|
||||
# filter the result
|
||||
$_.Name -like "$WordToComplete*"
|
||||
|
||||
# Join the flag back if we have a equal sign flag
|
||||
if ( $IsEqualFlag ) {
|
||||
__%[1]s_debug "Join the equal sign flag back to the completion value"
|
||||
$_.Name = $Flag + "=" + $_.Name
|
||||
}
|
||||
}
|
||||
|
||||
# Get the current mode
|
||||
$Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
|
||||
__%[1]s_debug "Mode: $Mode"
|
||||
|
||||
$Values | ForEach-Object {
|
||||
|
||||
# store temporay because switch will overwrite $_
|
||||
# store temporary because switch will overwrite $_
|
||||
$comp = $_
|
||||
|
||||
# PowerShell supports three different completion modes
|
||||
|
@ -233,16 +256,18 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
|
|||
Default {
|
||||
# Like MenuComplete but we don't want to add a space here because
|
||||
# the user need to press space anyway to get the completion.
|
||||
# Description will not be shown because thats not possible with TabCompleteNext
|
||||
# Description will not be shown because that's not possible with TabCompleteNext
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
`, name, compCmd,
|
||||
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock
|
||||
`, name, nameForVar, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {
|
||||
|
|
34
vendor/github.com/spf13/cobra/projects_using_cobra.md
generated
vendored
34
vendor/github.com/spf13/cobra/projects_using_cobra.md
generated
vendored
|
@ -1,38 +1,60 @@
|
|||
## Projects using Cobra
|
||||
|
||||
- [Allero](https://github.com/allero-io/allero)
|
||||
- [Arduino CLI](https://github.com/arduino/arduino-cli)
|
||||
- [Bleve](http://www.blevesearch.com/)
|
||||
- [CockroachDB](http://www.cockroachlabs.com/)
|
||||
- [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 CLI](https://github.com/cli/cli)
|
||||
- [GitHub Labeler](https://github.com/erdaltsksn/gh-label)
|
||||
- [Golangci-lint](https://golangci-lint.run)
|
||||
- [GopherJS](http://www.gopherjs.org/)
|
||||
- [GopherJS](https://github.com/gopherjs/gopherjs)
|
||||
- [GoReleaser](https://goreleaser.com)
|
||||
- [Helm](https://helm.sh)
|
||||
- [Hugo](https://gohugo.io)
|
||||
- [Infracost](https://github.com/infracost/infracost)
|
||||
- [Istio](https://istio.io)
|
||||
- [Kool](https://github.com/kool-dev/kool)
|
||||
- [Kubernetes](http://kubernetes.io/)
|
||||
- [Kubernetes](https://kubernetes.io/)
|
||||
- [Kubescape](https://github.com/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)](http://www.projectatomic.io/)
|
||||
- [ProjectAtomic (enterprise)](https://www.projectatomic.io/)
|
||||
- [Prototool](https://github.com/uber/prototool)
|
||||
- [Pulumi](https://www.pulumi.com)
|
||||
- [QRcp](https://github.com/claudiodangelis/qrcp)
|
||||
- [Random](https://github.com/erdaltsksn/random)
|
||||
- [Rclone](https://rclone.org/)
|
||||
- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)
|
||||
- [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)
|
||||
|
|
14
vendor/github.com/spf13/cobra/shell_completions.go
generated
vendored
14
vendor/github.com/spf13/cobra/shell_completions.go
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
|
|
119
vendor/github.com/spf13/cobra/shell_completions.md
generated
vendored
119
vendor/github.com/spf13/cobra/shell_completions.md
generated
vendored
|
@ -7,10 +7,21 @@ The currently supported shells are:
|
|||
- fish
|
||||
- PowerShell
|
||||
|
||||
If you are using the generator, you can create a completion command by running
|
||||
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 add completion
|
||||
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):
|
||||
|
@ -19,17 +30,17 @@ and then modifying the generated `cmd/completion.go` file to look something like
|
|||
var completionCmd = &cobra.Command{
|
||||
Use: "completion [bash|zsh|fish|powershell]",
|
||||
Short: "Generate completion script",
|
||||
Long: `To load completions:
|
||||
Long: fmt.Sprintf(`To load completions:
|
||||
|
||||
Bash:
|
||||
|
||||
$ source <(yourprogram completion bash)
|
||||
$ source <(%[1]s completion bash)
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
# Linux:
|
||||
$ yourprogram completion bash > /etc/bash_completion.d/yourprogram
|
||||
$ %[1]s completion bash > /etc/bash_completion.d/%[1]s
|
||||
# macOS:
|
||||
$ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram
|
||||
$ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
|
||||
|
||||
Zsh:
|
||||
|
||||
|
@ -39,25 +50,25 @@ Zsh:
|
|||
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ yourprogram completion zsh > "${fpath[1]}/_yourprogram"
|
||||
$ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
|
||||
|
||||
# You will need to start a new shell for this setup to take effect.
|
||||
|
||||
fish:
|
||||
|
||||
$ yourprogram completion fish | source
|
||||
$ %[1]s completion fish | source
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish
|
||||
$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
|
||||
|
||||
PowerShell:
|
||||
|
||||
PS> yourprogram completion powershell | Out-String | Invoke-Expression
|
||||
PS> %[1]s completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
# To load completions for every new session, run:
|
||||
PS> yourprogram completion powershell > yourprogram.ps1
|
||||
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),
|
||||
|
@ -70,7 +81,7 @@ PowerShell:
|
|||
case "fish":
|
||||
cmd.Root().GenFishCompletion(os.Stdout, true)
|
||||
case "powershell":
|
||||
cmd.Root().GenPowerShellCompletion(os.Stdout)
|
||||
cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
@ -78,6 +89,31 @@ PowerShell:
|
|||
|
||||
**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.
|
||||
|
@ -91,7 +127,7 @@ For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns
|
|||
Some simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pod", "node", "service", "replicationcontroller" }
|
||||
validArgs = []string{ "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
|
@ -117,7 +153,7 @@ node pod replicationcontroller service
|
|||
If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go
|
||||
argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
|
@ -323,7 +359,10 @@ cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string,
|
|||
```
|
||||
### Descriptions for completions
|
||||
|
||||
`zsh`, `fish` and `powershell` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:
|
||||
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
|
||||
|
@ -336,7 +375,7 @@ $ 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 annotations to your own completions. Simply add the annotation text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
|
||||
Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. 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
|
||||
|
@ -371,6 +410,37 @@ completion firstcommand secondcommand
|
|||
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`.
|
||||
|
@ -465,6 +535,21 @@ search for a keyword in charts
|
|||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
### Aliases
|
||||
|
||||
You can also configure `powershell` aliases for your program and they will also support completions.
|
||||
|
||||
```
|
||||
$ sal aliasname origcommand
|
||||
$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$ aliasname <tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
||||
The name of the completer block variable is of the form `$__<programName>CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax.
|
||||
|
||||
### Limitations
|
||||
|
||||
|
|
695
vendor/github.com/spf13/cobra/user_guide.md
generated
vendored
Normal file
695
vendor/github.com/spf13/cobra/user_guide.md
generated
vendored
Normal file
|
@ -0,0 +1,695 @@
|
|||
# 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).
|
105
vendor/github.com/spf13/cobra/zsh_completions.go
generated
vendored
105
vendor/github.com/spf13/cobra/zsh_completions.go
generated
vendored
|
@ -1,3 +1,17 @@
|
|||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
|
@ -75,7 +89,7 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
|
|||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
|
||||
|
||||
# zsh completion for %-36[1]s -*- shell-script -*-
|
||||
|
||||
|
@ -95,7 +109,7 @@ _%[1]s()
|
|||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
|
||||
local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp
|
||||
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
|
||||
local -a completions
|
||||
|
||||
__%[1]s_debug "\n========= starting completion logic =========="
|
||||
|
@ -163,8 +177,24 @@ _%[1]s()
|
|||
return
|
||||
fi
|
||||
|
||||
compCount=0
|
||||
local activeHelpMarker="%[8]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
local startIndex=$((${#activeHelpMarker}+1))
|
||||
local hasActiveHelp=0
|
||||
while IFS='\n' read -r comp; do
|
||||
# Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
|
||||
if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
comp="${comp[$startIndex,-1]}"
|
||||
if [ -n "$comp" ]; then
|
||||
compadd -x "${comp}"
|
||||
__%[1]s_debug "ActiveHelp will need delimiter"
|
||||
hasActiveHelp=1
|
||||
fi
|
||||
|
||||
continue
|
||||
fi
|
||||
|
||||
if [ -n "$comp" ]; then
|
||||
# If requested, completions are returned with a description.
|
||||
# The description is preceded by a TAB character.
|
||||
|
@ -172,16 +202,31 @@ _%[1]s()
|
|||
# We first need to escape any : as part of the completion itself.
|
||||
comp=${comp//:/\\:}
|
||||
|
||||
local tab=$(printf '\t')
|
||||
local tab="$(printf '\t')"
|
||||
comp=${comp//$tab/:}
|
||||
|
||||
((compCount++))
|
||||
__%[1]s_debug "Adding completion: ${comp}"
|
||||
completions+=${comp}
|
||||
lastComp=$comp
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
|
||||
# Add a delimiter after the activeHelp statements, but only if:
|
||||
# - there are completions following the activeHelp statements, or
|
||||
# - file completion will be performed (so there will be choices after the activeHelp)
|
||||
if [ $hasActiveHelp -eq 1 ]; then
|
||||
if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
|
||||
__%[1]s_debug "Adding activeHelp delimiter"
|
||||
compadd -x "--"
|
||||
hasActiveHelp=0
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
|
||||
__%[1]s_debug "Activating nospace."
|
||||
noSpace="-S ''"
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local filteringCmd
|
||||
|
@ -199,7 +244,7 @@ _%[1]s()
|
|||
_arguments '*:filename:'"$filteringCmd"
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
# File completion for directories only
|
||||
local subDir
|
||||
local subdir
|
||||
subdir="${completions[1]}"
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
|
@ -208,33 +253,49 @@ _%[1]s()
|
|||
__%[1]s_debug "Listing directories in ."
|
||||
fi
|
||||
|
||||
local result
|
||||
_arguments '*:dirname:_files -/'" ${flagPrefix}"
|
||||
result=$?
|
||||
if [ -n "$subdir" ]; then
|
||||
popd >/dev/null 2>&1
|
||||
fi
|
||||
elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then
|
||||
__%[1]s_debug "Activating nospace."
|
||||
# We can use compadd here as there is no description when
|
||||
# there is only one completion.
|
||||
compadd -S '' "${lastComp}"
|
||||
elif [ ${compCount} -eq 0 ]; then
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
__%[1]s_debug "deactivating file completion"
|
||||
else
|
||||
# Perform file completion
|
||||
__%[1]s_debug "activating file completion"
|
||||
_arguments '*:filename:_files'" ${flagPrefix}"
|
||||
fi
|
||||
return $result
|
||||
else
|
||||
_describe "completions" completions $(echo $flagPrefix)
|
||||
__%[1]s_debug "Calling _describe"
|
||||
if eval _describe "completions" completions $flagPrefix $noSpace; then
|
||||
__%[1]s_debug "_describe found some completions"
|
||||
|
||||
# Return the success of having called _describe
|
||||
return 0
|
||||
else
|
||||
__%[1]s_debug "_describe did not find completions."
|
||||
__%[1]s_debug "Checking if we should do file completion."
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
__%[1]s_debug "deactivating file completion"
|
||||
|
||||
# We must return an error code here to let zsh know that there were no
|
||||
# completions found by _describe; this is what will trigger other
|
||||
# matching algorithms to attempt to find completions.
|
||||
# For example zsh can match letters in the middle of words.
|
||||
return 1
|
||||
else
|
||||
# Perform file completion
|
||||
__%[1]s_debug "Activating file completion"
|
||||
|
||||
# We must return the result of this command, so it must be the
|
||||
# last command, or else we must store its result to return it.
|
||||
_arguments '*:filename:_files'" ${flagPrefix}"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# don't run the completion function when being source-ed or eval-ed
|
||||
if [ "$funcstack[1]" = "_%[1]s" ]; then
|
||||
_%[1]s
|
||||
_%[1]s
|
||||
fi
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
|
8
vendor/modules.txt
vendored
8
vendor/modules.txt
vendored
|
@ -446,8 +446,8 @@ github.com/hashicorp/serf/serf
|
|||
# github.com/imdario/mergo v0.3.12
|
||||
## explicit; go 1.13
|
||||
github.com/imdario/mergo
|
||||
# github.com/inconshreveable/mousetrap v1.0.0
|
||||
## explicit
|
||||
# github.com/inconshreveable/mousetrap v1.0.1
|
||||
## explicit; go 1.18
|
||||
github.com/inconshreveable/mousetrap
|
||||
# github.com/ishidawataru/sctp v0.0.0-20210707070123-9a39160e9062
|
||||
## explicit; go 1.12
|
||||
|
@ -758,8 +758,8 @@ github.com/sean-/seed
|
|||
# github.com/sirupsen/logrus v1.9.0
|
||||
## explicit; go 1.13
|
||||
github.com/sirupsen/logrus
|
||||
# github.com/spf13/cobra v1.1.3
|
||||
## explicit; go 1.12
|
||||
# github.com/spf13/cobra v1.6.1
|
||||
## explicit; go 1.15
|
||||
github.com/spf13/cobra
|
||||
# github.com/spf13/pflag v1.0.5
|
||||
## explicit; go 1.12
|
||||
|
|
Loading…
Reference in a new issue