aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/spf13/cobra
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/github.com/spf13/cobra')
-rw-r--r--vendor/github.com/spf13/cobra/.gitignore38
-rw-r--r--vendor/github.com/spf13/cobra/.mailmap3
-rw-r--r--vendor/github.com/spf13/cobra/.travis.yml31
-rw-r--r--vendor/github.com/spf13/cobra/LICENSE.txt174
-rw-r--r--vendor/github.com/spf13/cobra/README.md741
-rw-r--r--vendor/github.com/spf13/cobra/args.go101
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.go547
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.md256
-rw-r--r--vendor/github.com/spf13/cobra/cobra.go207
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden202
-rw-r--r--vendor/github.com/spf13/cobra/command.go1594
-rw-r--r--vendor/github.com/spf13/cobra/command_notwin.go5
-rw-r--r--vendor/github.com/spf13/cobra/command_win.go26
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_docs.go247
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_docs.md31
-rw-r--r--vendor/github.com/spf13/cobra/doc/md_docs.go159
-rw-r--r--vendor/github.com/spf13/cobra/doc/md_docs.md115
-rw-r--r--vendor/github.com/spf13/cobra/doc/rest_docs.go185
-rw-r--r--vendor/github.com/spf13/cobra/doc/rest_docs.md114
-rw-r--r--vendor/github.com/spf13/cobra/doc/util.go51
-rw-r--r--vendor/github.com/spf13/cobra/doc/yaml_docs.go169
-rw-r--r--vendor/github.com/spf13/cobra/doc/yaml_docs.md112
-rw-r--r--vendor/github.com/spf13/cobra/go.mod13
-rw-r--r--vendor/github.com/spf13/cobra/go.sum51
-rw-r--r--vendor/github.com/spf13/cobra/powershell_completions.go100
-rw-r--r--vendor/github.com/spf13/cobra/powershell_completions.md14
-rw-r--r--vendor/github.com/spf13/cobra/shell_completions.go85
-rw-r--r--vendor/github.com/spf13/cobra/zsh_completions.go336
-rw-r--r--vendor/github.com/spf13/cobra/zsh_completions.md39
29 files changed, 0 insertions, 5746 deletions
diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore
deleted file mode 100644
index 3b053c59..00000000
--- a/vendor/github.com/spf13/cobra/.gitignore
+++ /dev/null
@@ -1,38 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
-# swap
-[._]*.s[a-w][a-z]
-[._]s[a-w][a-z]
-# session
-Session.vim
-# temporary
-.netrwhist
-*~
-# auto-generated tag files
-tags
-
-*.exe
-
-cobra.test
-
-.idea/*
diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap
deleted file mode 100644
index 94ec5306..00000000
--- a/vendor/github.com/spf13/cobra/.mailmap
+++ /dev/null
@@ -1,3 +0,0 @@
-Steve Francia <steve.francia@gmail.com>
-Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
-Fabiano Franz <ffranz@redhat.com> <contact@fabianofranz.com>
diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml
deleted file mode 100644
index 38b85f49..00000000
--- a/vendor/github.com/spf13/cobra/.travis.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-language: go
-
-stages:
- - diff
- - test
-
-go:
- - 1.10.x
- - 1.11.x
- - 1.12.x
- - tip
-
-matrix:
- allow_failures:
- - go: tip
- include:
- - stage: diff
- go: 1.12.x
- script: diff -u <(echo -n) <(gofmt -d -s .)
-
-before_install:
- - mkdir -p bin
- - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.6.0/shellcheck
- - chmod +x bin/shellcheck
- - go get -u github.com/kyoh86/richgo
-script:
- - PATH=$PATH:$PWD/bin richgo test -v ./...
- - go build
- - if [ -z $NOVET ]; then
- diff -u <(echo -n) <(go vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint');
- fi
diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt
deleted file mode 100644
index 298f0e26..00000000
--- a/vendor/github.com/spf13/cobra/LICENSE.txt
+++ /dev/null
@@ -1,174 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "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.
diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md
deleted file mode 100644
index 60c5a425..00000000
--- a/vendor/github.com/spf13/cobra/README.md
+++ /dev/null
@@ -1,741 +0,0 @@
-![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.
-
-Many of the most widely used Go projects are built using Cobra, such as:
-[Kubernetes](http://kubernetes.io/),
-[Hugo](http://gohugo.io),
-[rkt](https://github.com/coreos/rkt),
-[etcd](https://github.com/coreos/etcd),
-[Moby (former Docker)](https://github.com/moby/moby),
-[Docker (distribution)](https://github.com/docker/distribution),
-[OpenShift](https://www.openshift.com/),
-[Delve](https://github.com/derekparker/delve),
-[GopherJS](http://www.gopherjs.org/),
-[CockroachDB](http://www.cockroachlabs.com/),
-[Bleve](http://www.blevesearch.com/),
-[ProjectAtomic (enterprise)](http://www.projectatomic.io/),
-[Giant Swarm's gsctl](https://github.com/giantswarm/gsctl),
-[Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack),
-[rclone](http://rclone.org/),
-[nehm](https://github.com/bogem/nehm),
-[Pouch](https://github.com/alibaba/pouch),
-[Istio](https://istio.io),
-[Prototool](https://github.com/uber/prototool),
-[mattermost-server](https://github.com/mattermost/mattermost-server),
-[Gardener](https://github.com/gardener/gardenctl),
-etc.
-
-[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
-[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra)
-[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
-
-# 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 bash completions](#generating-bash-completions)
- * [Generating zsh completions](#generating-zsh-completions)
-- [Contributing](#contributing)
-- [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
-* Automatic help flag recognition of `-h`, `--help`, etc.
-* Automatically generated bash autocomplete for your application
-* 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
-
-# Concepts
-
-Cobra is built on a structure of commands, arguments & flags.
-
-**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
-
-The best applications will read like sentences when used. Users will know how
-to use the application because they will natively understand how to use it.
-
-The pattern to follow is
-`APPNAME VERB NOUN --ADJECTIVE.`
- or
-`APPNAME COMMAND ARG --FLAG`
-
-A few good real world examples may better illustrate this point.
-
-In the following example, 'server' is a command, and 'port' is a flag:
-
- hugo server --port=1313
-
-In this command we are telling Git to clone the url bare.
-
- git clone URL --bare
-
-## Commands
-
-Command is the central point of the application. Each interaction that
-the application supports will be contained in a Command. A command can
-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)
-
-## Flags
-
-A flag is a way to modify the behavior of a command. Cobra supports
-fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
-A Cobra command can define flags that persist through to children commands
-and flags that are only available to that command.
-
-In the example above, 'port' is the flag.
-
-Flag functionality is provided by the [pflag
-library](https://github.com/spf13/pflag), a fork of the flag standard library
-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:
-
- go get -u github.com/spf13/cobra/cobra
-
-Next, include Cobra in your application:
-
-```go
-import "github.com/spf13/cobra"
-```
-
-# Getting Started
-
-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 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.Println(err)
- os.Exit(1)
- }
-}
-```
-
-You will additionally define flags and handle configuration in your init() function.
-
-For example cmd/root.go:
-
-```go
-import (
- "fmt"
- "os"
-
- homedir "github.com/mitchellh/go-homedir"
- "github.com/spf13/cobra"
- "github.com/spf13/viper"
-)
-
-func init() {
- cobra.OnInitialize(initConfig)
- rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
- rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
- rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
- rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
- rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
- viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
- viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase"))
- viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
- viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
- viper.SetDefault("license", "apache")
-}
-
-func initConfig() {
- // Don't forget to read config either from cfgFile or from home directory!
- if cfgFile != "" {
- // Use config file from the flag.
- viper.SetConfigFile(cfgFile)
- } else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-
- // Search config in home directory with name ".cobra" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".cobra")
- }
-
- if err := viper.ReadInConfig(); err != nil {
- fmt.Println("Can't read config:", err)
- os.Exit(1)
- }
-}
-```
-
-### 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")
- },
-}
-```
-
-## 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, 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**, that 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")
-```
-
-## 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("Print: " + 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. in the following formats:
-
-- [Markdown](doc/md_docs.md)
-- [ReStructured Text](doc/rest_docs.md)
-- [Man Page](doc/man_docs.md)
-
-## Generating bash completions
-
-Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).
-
-## Generating zsh completions
-
-Cobra can generate zsh-completion file. Read more about it in
-[Zsh Completions](zsh_completions.md).
-
-# Contributing
-
-1. Fork it
-2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
-3. Create your feature branch (`git checkout -b my-new-feature`)
-4. Make changes and add them (`git add .`)
-5. Commit your changes (`git commit -m 'Add some feature'`)
-6. Push to the branch (`git push origin my-new-feature`)
-7. Create new pull request
-
-# License
-
-Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go
deleted file mode 100644
index c4d820b8..00000000
--- a/vendor/github.com/spf13/cobra/args.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package cobra
-
-import (
- "fmt"
-)
-
-type PositionalArgs func(cmd *Command, args []string) error
-
-// Legacy arg validation has the following behaviour:
-// - root commands with no subcommands can take arbitrary arguments
-// - root commands with subcommands will do subcommand validity checking
-// - subcommands will always accept arbitrary arguments
-func legacyArgs(cmd *Command, args []string) error {
- // no subcommand, always take args
- if !cmd.HasSubCommands() {
- return nil
- }
-
- // root command with subcommands, do subcommand checking.
- if !cmd.HasParent() && len(args) > 0 {
- return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
- }
- return nil
-}
-
-// NoArgs returns an error if any args are included.
-func NoArgs(cmd *Command, args []string) error {
- if len(args) > 0 {
- return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
- }
- return nil
-}
-
-// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.
-func OnlyValidArgs(cmd *Command, args []string) error {
- if len(cmd.ValidArgs) > 0 {
- for _, v := range args {
- if !stringInSlice(v, cmd.ValidArgs) {
- return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
- }
- }
- }
- return nil
-}
-
-// ArbitraryArgs never returns an error.
-func ArbitraryArgs(cmd *Command, args []string) error {
- return nil
-}
-
-// MinimumNArgs returns an error if there is not at least N args.
-func MinimumNArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) < n {
- return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
- }
- return nil
- }
-}
-
-// MaximumNArgs returns an error if there are more than N args.
-func MaximumNArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) > n {
- return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
- }
- return nil
- }
-}
-
-// ExactArgs returns an error if there are not exactly n args.
-func ExactArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) != n {
- return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
- }
- 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`
-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 {
- if len(args) < min || len(args) > max {
- return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
- }
- return nil
- }
-}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
deleted file mode 100644
index 57bb8e1b..00000000
--- a/vendor/github.com/spf13/cobra/bash_completions.go
+++ /dev/null
@@ -1,547 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
-
- "github.com/spf13/pflag"
-)
-
-// Annotations for Bash completion.
-const (
- BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
- BashCompCustom = "cobra_annotation_bash_completion_custom"
- BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
- BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
-)
-
-func writePreamble(buf *bytes.Buffer, name string) {
- buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
- buf.WriteString(fmt.Sprintf(`
-__%[1]s_debug()
-{
- if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
- echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
- fi
-}
-
-# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
-# _init_completion. This is a very minimal version of that function.
-__%[1]s_init_completion()
-{
- COMPREPLY=()
- _get_comp_words_by_ref "$@" cur prev words cword
-}
-
-__%[1]s_index_of_word()
-{
- local w word=$1
- shift
- index=0
- for w in "$@"; do
- [[ $w = "$word" ]] && return
- index=$((index+1))
- done
- index=-1
-}
-
-__%[1]s_contains_word()
-{
- local w word=$1; shift
- for w in "$@"; do
- [[ $w = "$word" ]] && return
- done
- return 1
-}
-
-__%[1]s_handle_reply()
-{
- __%[1]s_debug "${FUNCNAME[0]}"
- case $cur in
- -*)
- if [[ $(type -t compopt) = "builtin" ]]; then
- compopt -o nospace
- fi
- local allflags
- if [ ${#must_have_one_flag[@]} -ne 0 ]; then
- allflags=("${must_have_one_flag[@]}")
- else
- allflags=("${flags[*]} ${two_word_flags[*]}")
- fi
- COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
- if [[ $(type -t compopt) = "builtin" ]]; then
- [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
- fi
-
- # complete after --flag=abc
- if [[ $cur == *=* ]]; then
- if [[ $(type -t compopt) = "builtin" ]]; then
- compopt +o nospace
- fi
-
- local index flag
- flag="${cur%%=*}"
- __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"
- COMPREPLY=()
- if [[ ${index} -ge 0 ]]; then
- PREFIX=""
- cur="${cur#*=}"
- ${flags_completion[${index}]}
- if [ -n "${ZSH_VERSION}" ]; then
- # zsh completion needs --flag= prefix
- eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
- fi
- fi
- fi
- return 0;
- ;;
- esac
-
- # check if we are handling a flag with special work handling
- local index
- __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"
- if [[ ${index} -ge 0 ]]; then
- ${flags_completion[${index}]}
- return
- fi
-
- # we are parsing a flag and don't have a special handler, no completion
- if [[ ${cur} != "${words[cword]}" ]]; then
- return
- fi
-
- local completions
- completions=("${commands[@]}")
- if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
- completions=("${must_have_one_noun[@]}")
- fi
- if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
- completions+=("${must_have_one_flag[@]}")
- fi
- COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
-
- if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
- COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )
- 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
- fi
-
- # available in bash-completion >= 2, not always present on macOS
- if declare -F __ltrim_colon_completions >/dev/null; then
- __ltrim_colon_completions "$cur"
- fi
-
- # If there is only 1 completion and it is a flag with an = it will be completed
- # but we don't want a space after the =
- if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
- compopt -o nospace
- fi
-}
-
-# The arguments should be in the form "ext1|ext2|extn"
-__%[1]s_handle_filename_extension_flag()
-{
- local ext="$1"
- _filedir "@(${ext})"
-}
-
-__%[1]s_handle_subdirs_in_dir_flag()
-{
- local dir="$1"
- pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1
-}
-
-__%[1]s_handle_flag()
-{
- __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- # if a command required a flag, and we found it, unset must_have_one_flag()
- local flagname=${words[c]}
- local flagvalue
- # if the word contained an =
- if [[ ${words[c]} == *"="* ]]; then
- flagvalue=${flagname#*=} # take in as flagvalue after the =
- flagname=${flagname%%=*} # strip everything after the =
- flagname="${flagname}=" # but put the = back
- fi
- __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"
- if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then
- must_have_one_flag=()
- fi
-
- # if you set a flag which only applies to this command, don't show subcommands
- if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
- commands=()
- fi
-
- # 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 [ -n "${flagvalue}" ] ; then
- flaghash[${flagname}]=${flagvalue}
- elif [ -n "${words[ $((c+1)) ]}" ] ; then
- flaghash[${flagname}]=${words[ $((c+1)) ]}
- else
- flaghash[${flagname}]="true" # pad "true" for bool flag
- fi
- fi
-
- # 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"
- c=$((c+1))
- # if we are looking for a flags value, don't show commands
- if [[ $c -eq $cword ]]; then
- commands=()
- fi
- fi
-
- c=$((c+1))
-
-}
-
-__%[1]s_handle_noun()
-{
- __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
- must_have_one_noun=()
- elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then
- must_have_one_noun=()
- fi
-
- nouns+=("${words[c]}")
- c=$((c+1))
-}
-
-__%[1]s_handle_command()
-{
- __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- local next_command
- if [[ -n ${last_command} ]]; then
- next_command="_${last_command}_${words[c]//:/__}"
- else
- if [[ $c -eq 0 ]]; then
- next_command="_%[1]s_root_command"
- else
- next_command="_${words[c]//:/__}"
- fi
- fi
- c=$((c+1))
- __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"
- declare -F "$next_command" >/dev/null && $next_command
-}
-
-__%[1]s_handle_word()
-{
- if [[ $c -ge $cword ]]; then
- __%[1]s_handle_reply
- return
- fi
- __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
- if [[ "${words[c]}" == -* ]]; then
- __%[1]s_handle_flag
- elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
- __%[1]s_handle_command
- elif [[ $c -eq 0 ]]; then
- __%[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
- words[c]=${aliashash[${words[c]}]}
- __%[1]s_handle_command
- else
- __%[1]s_handle_noun
- fi
- else
- __%[1]s_handle_noun
- fi
- __%[1]s_handle_word
-}
-
-`, name))
-}
-
-func writePostscript(buf *bytes.Buffer, name string) {
- name = strings.Replace(name, ":", "__", -1)
- buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
- buf.WriteString(fmt.Sprintf(`{
- local cur prev words cword
- declare -A flaghash 2>/dev/null || :
- declare -A aliashash 2>/dev/null || :
- if declare -F _init_completion >/dev/null 2>&1; then
- _init_completion -s || return
- else
- __%[1]s_init_completion -n "=" || return
- fi
-
- local c=0
- local flags=()
- local two_word_flags=()
- local local_nonpersistent_flags=()
- local flags_with_completion=()
- local flags_completion=()
- local commands=("%[1]s")
- local must_have_one_flag=()
- local must_have_one_noun=()
- local last_command
- local nouns=()
-
- __%[1]s_handle_word
-}
-
-`, name))
- buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
- complete -o default -F __start_%s %s
-else
- complete -o default -o nospace -F __start_%s %s
-fi
-
-`, name, name, name, name))
- buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
-}
-
-func writeCommands(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" commands=()\n")
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c == cmd.helpCommand {
- continue
- }
- buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))
- writeCmdAliases(buf, c)
- }
- buf.WriteString("\n")
-}
-
-func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {
- for key, value := range annotations {
- switch key {
- case BashCompFilenameExt:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- var ext string
- if len(value) > 0 {
- ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
- } else {
- ext = "_filedir"
- }
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- case BashCompCustom:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
- if len(value) > 0 {
- handlers := strings.Join(value, "; ")
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
- } else {
- buf.WriteString(" flags_completion+=(:)\n")
- }
- case BashCompSubdirsInDir:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- var ext string
- if len(value) == 1 {
- ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
- } else {
- ext = "_filedir -d"
- }
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- }
- }
-}
-
-func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
- name := flag.Shorthand
- format := " "
- if len(flag.NoOptDefVal) == 0 {
- format += "two_word_"
- }
- format += "flags+=(\"-%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
-}
-
-func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
- name := flag.Name
- format := " flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- if len(flag.NoOptDefVal) == 0 {
- format = " two_word_flags+=(\"--%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- }
- writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
-}
-
-func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
- name := flag.Name
- format := " local_nonpersistent_flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
-}
-
-func writeFlags(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(` flags=()
- two_word_flags=()
- local_nonpersistent_flags=()
- flags_with_completion=()
- flags_completion=()
-
-`)
- localNonPersistentFlags := cmd.LocalNonPersistentFlags()
- cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- writeFlag(buf, flag, cmd)
- if len(flag.Shorthand) > 0 {
- writeShortFlag(buf, flag, cmd)
- }
- if localNonPersistentFlags.Lookup(flag.Name) != nil {
- writeLocalNonPersistentFlag(buf, flag)
- }
- })
- cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- writeFlag(buf, flag, cmd)
- if len(flag.Shorthand) > 0 {
- writeShortFlag(buf, flag, cmd)
- }
- })
-
- buf.WriteString("\n")
-}
-
-func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_flag=()\n")
- flags := cmd.NonInheritedFlags()
- flags.VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- for key := range flag.Annotations {
- switch key {
- case BashCompOneRequiredFlag:
- format := " must_have_one_flag+=(\"--%s"
- if flag.Value.Type() != "bool" {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, flag.Name))
-
- if len(flag.Shorthand) > 0 {
- buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
- }
- }
- }
- })
-}
-
-func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_noun=()\n")
- sort.Sort(sort.StringSlice(cmd.ValidArgs))
- for _, value := range cmd.ValidArgs {
- buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
- }
-}
-
-func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {
- if len(cmd.Aliases) == 0 {
- return
- }
-
- sort.Sort(sort.StringSlice(cmd.Aliases))
-
- buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))
- for _, value := range cmd.Aliases {
- buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value))
- buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
- }
- buf.WriteString(` fi`)
- buf.WriteString("\n")
-}
-func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" noun_aliases=()\n")
- sort.Sort(sort.StringSlice(cmd.ArgAliases))
- for _, value := range cmd.ArgAliases {
- buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))
- }
-}
-
-func gen(buf *bytes.Buffer, cmd *Command) {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c == cmd.helpCommand {
- continue
- }
- gen(buf, c)
- }
- commandName := cmd.CommandPath()
- commandName = strings.Replace(commandName, " ", "_", -1)
- commandName = strings.Replace(commandName, ":", "__", -1)
-
- if cmd.Root() == cmd {
- buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))
- } else {
- buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
- }
-
- buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
- buf.WriteString("\n")
- buf.WriteString(" command_aliases=()\n")
- buf.WriteString("\n")
-
- writeCommands(buf, cmd)
- writeFlags(buf, cmd)
- writeRequiredFlag(buf, cmd)
- writeRequiredNouns(buf, cmd)
- writeArgAliases(buf, cmd)
- buf.WriteString("}\n\n")
-}
-
-// GenBashCompletion generates bash completion file and writes to the passed writer.
-func (c *Command) GenBashCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
- writePreamble(buf, c.Name())
- if len(c.BashCompletionFunction) > 0 {
- buf.WriteString(c.BashCompletionFunction + "\n")
- }
- gen(buf, c)
- writePostscript(buf, c.Name())
-
- _, err := buf.WriteTo(w)
- return err
-}
-
-func nonCompletableFlag(flag *pflag.Flag) bool {
- return flag.Hidden || len(flag.Deprecated) > 0
-}
-
-// GenBashCompletionFile generates bash completion file.
-func (c *Command) GenBashCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenBashCompletion(outFile)
-}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md
deleted file mode 100644
index 4ac61ee1..00000000
--- a/vendor/github.com/spf13/cobra/bash_completions.md
+++ /dev/null
@@ -1,256 +0,0 @@
-# Generating Bash Completions For Your Own cobra.Command
-
-If you are using the generator you can create a completion command by running
-
-```bash
-cobra add completion
-```
-
-Update the help text show how to install the bash_completion Linux show here [Kubectl docs show mac options](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)
-
-Writing the shell script to stdout allows the most flexible use.
-
-```go
-// completionCmd represents the completion command
-var completionCmd = &cobra.Command{
- Use: "completion",
- Short: "Generates bash completion scripts",
- Long: `To load completion run
-
-. <(bitbucket completion)
-
-To configure your bash shell to load completions for each session add to your bashrc
-
-# ~/.bashrc or ~/.profile
-. <(bitbucket completion)
-`,
- Run: func(cmd *cobra.Command, args []string) {
- rootCmd.GenBashCompletion(os.Stdout);
- },
-}
-```
-
-**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script
-
-
-## Example from kubectl
-
-Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
-
-```go
-package main
-
-import (
- "io/ioutil"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- kubectl.GenBashCompletionFile("out.sh")
-}
-```
-
-`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
-
-## Creating your own custom functions
-
-Some more actual code that works in kubernetes:
-
-```bash
-const (
- bash_completion_func = `__kubectl_parse_get()
-{
- local kubectl_output out
- if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
- out=($(echo "${kubectl_output}" | awk '{print $1}'))
- COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
- fi
-}
-
-__kubectl_get_resource()
-{
- if [[ ${#nouns[@]} -eq 0 ]]; then
- return 1
- fi
- __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
- if [[ $? -eq 0 ]]; then
- return 0
- fi
-}
-
-__kubectl_custom_func() {
- case ${last_command} in
- kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
- __kubectl_get_resource
- return
- ;;
- *)
- ;;
- esac
-}
-`)
-```
-
-And then I set that in my command definition:
-
-```go
-cmds := &cobra.Command{
- Use: "kubectl",
- Short: "kubectl controls the Kubernetes cluster manager",
- Long: `kubectl controls the Kubernetes cluster manager.
-
-Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
- Run: runHelp,
- BashCompletionFunction: bash_completion_func,
-}
-```
-
-The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`__<command-use>_custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
-
-## Have the completions code complete your 'nouns'
-
-In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
-
-```go
-validArgs []string = { "pod", "node", "service", "replicationcontroller" }
-
-cmd := &cobra.Command{
- Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
- Short: "Display one or many resources",
- Long: get_long,
- Example: get_example,
- Run: func(cmd *cobra.Command, args []string) {
- err := RunGet(f, out, cmd, args)
- util.CheckErr(err)
- },
- ValidArgs: validArgs,
-}
-```
-
-Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
-
-```bash
-# kubectl get [tab][tab]
-node pod replicationcontroller service
-```
-
-## Plural form and shortcuts for nouns
-
-If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
-
-```go
-argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
-
-cmd := &cobra.Command{
- ...
- ValidArgs: validArgs,
- ArgAliases: argAliases
-}
-```
-
-The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
-the completion algorithm if entered manually, e.g. in:
-
-```bash
-# kubectl get rc [tab][tab]
-backend frontend database
-```
-
-Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns
-in this example again instead of the replication controllers.
-
-## Mark flags as required
-
-Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
-
-```go
-cmd.MarkFlagRequired("pod")
-cmd.MarkFlagRequired("container")
-```
-
-and you'll get something like
-
-```bash
-# kubectl exec [tab][tab][tab]
--c --container= -p --pod=
-```
-
-# Specify valid filename extensions for flags that take a filename
-
-In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
-
-```go
- annotations := []string{"json", "yaml", "yml"}
- annotation := make(map[string][]string)
- annotation[cobra.BashCompFilenameExt] = annotations
-
- flag := &pflag.Flag{
- Name: "filename",
- Shorthand: "f",
- Usage: usage,
- Value: value,
- DefValue: value.String(),
- Annotations: annotation,
- }
- cmd.Flags().AddFlag(flag)
-```
-
-Now when you run a command with this filename flag you'll get something like
-
-```bash
-# kubectl create -f
-test/ example/ rpmbuild/
-hello.yml test.json
-```
-
-So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
-
-# Specify custom flag completion
-
-Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specify
-a custom flag completion function with cobra.BashCompCustom:
-
-```go
- annotation := make(map[string][]string)
- annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
-
- flag := &pflag.Flag{
- Name: "namespace",
- Usage: usage,
- Annotations: annotation,
- }
- cmd.Flags().AddFlag(flag)
-```
-
-In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction`
-value, e.g.:
-
-```bash
-__kubectl_get_namespaces()
-{
- local template
- template="{{ range .items }}{{ .metadata.name }} {{ end }}"
- local kubectl_out
- if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
- COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
- fi
-}
-```
-# Using bash aliases for commands
-
-You can also configure the `bash aliases` for the commands and they will also support completions.
-
-```bash
-alias aliasname=origcommand
-complete -o default -F __start_origcommand aliasname
-
-# and now when you run `aliasname` completion will make
-# suggestions as it did for `origcommand`.
-
-$) aliasname <tab><tab>
-completion firstcommand secondcommand
-```
diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go
deleted file mode 100644
index 6505c070..00000000
--- a/vendor/github.com/spf13/cobra/cobra.go
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright © 2013 Steve Francia <spf@spf13.com>.
-//
-// 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.
-
-// Commands similar to git, go tools and other modern CLI tools
-// inspired by go, go-Commander, gh and subcommand
-
-package cobra
-
-import (
- "fmt"
- "io"
- "reflect"
- "strconv"
- "strings"
- "text/template"
- "time"
- "unicode"
-)
-
-var templateFuncs = template.FuncMap{
- "trim": strings.TrimSpace,
- "trimRightSpace": trimRightSpace,
- "trimTrailingWhitespaces": trimRightSpace,
- "appendIfNotPresent": appendIfNotPresent,
- "rpad": rpad,
- "gt": Gt,
- "eq": Eq,
-}
-
-var initializers []func()
-
-// 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
-
-// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
-// To disable sorting, set it to false.
-var EnableCommandSorting = true
-
-// MousetrapHelpText enables an information splash screen on Windows
-// if the CLI is started from explorer.exe.
-// To disable the mousetrap, just set this variable to blank string ("").
-// Works only on Microsoft Windows.
-var MousetrapHelpText string = `This is a command line tool.
-
-You need to open cmd.exe and run it from there.
-`
-
-// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows
-// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed.
-// To disable the mousetrap, just set MousetrapHelpText to blank string ("").
-// Works only on Microsoft Windows.
-var MousetrapDisplayDuration time.Duration = 5 * time.Second
-
-// AddTemplateFunc adds a template function that's available to Usage and Help
-// template generation.
-func AddTemplateFunc(name string, tmplFunc interface{}) {
- templateFuncs[name] = tmplFunc
-}
-
-// AddTemplateFuncs adds multiple template functions that are available to Usage and
-// Help template generation.
-func AddTemplateFuncs(tmplFuncs template.FuncMap) {
- for k, v := range tmplFuncs {
- templateFuncs[k] = v
- }
-}
-
-// OnInitialize sets the passed functions to be run when each command's
-// Execute method is called.
-func OnInitialize(y ...func()) {
- initializers = append(initializers, 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,
-// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
-// ints and then compared.
-func Gt(a interface{}, b interface{}) bool {
- var left, right int64
- av := reflect.ValueOf(a)
-
- switch av.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- left = int64(av.Len())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- left = av.Int()
- case reflect.String:
- left, _ = strconv.ParseInt(av.String(), 10, 64)
- }
-
- bv := reflect.ValueOf(b)
-
- switch bv.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- right = int64(bv.Len())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- right = bv.Int()
- case reflect.String:
- right, _ = strconv.ParseInt(bv.String(), 10, 64)
- }
-
- return left > right
-}
-
-// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
-func Eq(a interface{}, b interface{}) bool {
- av := reflect.ValueOf(a)
- bv := reflect.ValueOf(b)
-
- switch av.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- panic("Eq called on unsupported type")
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return av.Int() == bv.Int()
- case reflect.String:
- return av.String() == bv.String()
- }
- return false
-}
-
-func trimRightSpace(s string) string {
- return strings.TrimRightFunc(s, unicode.IsSpace)
-}
-
-// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
-func appendIfNotPresent(s, stringToAppend string) string {
- if strings.Contains(s, stringToAppend) {
- return s
- }
- return s + " " + stringToAppend
-}
-
-// rpad adds padding to the right of a string.
-func rpad(s string, padding int) string {
- template := fmt.Sprintf("%%-%ds", padding)
- return fmt.Sprintf(template, s)
-}
-
-// tmpl executes the given template text on data, writing the result to w.
-func tmpl(w io.Writer, text string, data interface{}) error {
- t := template.New("top")
- t.Funcs(templateFuncs)
- template.Must(t.Parse(text))
- return t.Execute(w, data)
-}
-
-// ld compares two strings and returns the levenshtein distance between them.
-func ld(s, t string, ignoreCase bool) int {
- if ignoreCase {
- s = strings.ToLower(s)
- t = strings.ToLower(t)
- }
- d := make([][]int, len(s)+1)
- for i := range d {
- d[i] = make([]int, len(t)+1)
- }
- for i := range d {
- d[i][0] = i
- }
- for j := range d[0] {
- d[0][j] = j
- }
- for j := 1; j <= len(t); j++ {
- for i := 1; i <= len(s); i++ {
- if s[i-1] == t[j-1] {
- d[i][j] = d[i-1][j-1]
- } else {
- min := d[i-1][j]
- if d[i][j-1] < min {
- min = d[i][j-1]
- }
- if d[i-1][j-1] < min {
- min = d[i-1][j-1]
- }
- d[i][j] = min + 1
- }
- }
-
- }
- return d[len(s)][len(t)]
-}
-
-func stringInSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden
deleted file mode 100644
index d6456956..00000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden
+++ /dev/null
@@ -1,202 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "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 [yyyy] [name of copyright owner]
-
- 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.
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
deleted file mode 100644
index c7e89830..00000000
--- a/vendor/github.com/spf13/cobra/command.go
+++ /dev/null
@@ -1,1594 +0,0 @@
-// Copyright © 2013 Steve Francia <spf@spf13.com>.
-//
-// 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 is a commander providing a simple interface to create powerful modern CLI interfaces.
-// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- flag "github.com/spf13/pflag"
-)
-
-// FParseErrWhitelist configures Flag parse errors to be ignored
-type FParseErrWhitelist flag.ParseErrorsWhitelist
-
-// 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
-// definition to ensure usability.
-type Command struct {
- // Use is the one-line usage message.
- Use string
-
- // Aliases is an array of aliases that can be used instead of the first word in Use.
- Aliases []string
-
- // SuggestFor is an array of command names for which this command will be suggested -
- // similar to aliases but only suggests.
- SuggestFor []string
-
- // Short is the short description shown in the 'help' output.
- Short 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 []string
-
- // Expected arguments
- Args PositionalArgs
-
- // ArgAliases is List of aliases for ValidArgs.
- // These are not suggested to the user in the bash completion,
- // but accepted if entered manually.
- ArgAliases []string
-
- // BashCompletionFunction is custom functions used by the bash autocompletion generator.
- BashCompletionFunction string
-
- // Deprecated defines, if this command is deprecated and should print this string when used.
- Deprecated string
-
- // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
- Hidden bool
-
- // Annotations are key/value pairs that can be used by applications to identify or
- // group commands.
- Annotations map[string]string
-
- // Version defines the version for this command. If this value is non-empty and the command does not
- // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
- // will print content of the "Version" variable.
- Version string
-
- // The *Run functions are executed in the following order:
- // * PersistentPreRun()
- // * PreRun()
- // * Run()
- // * PostRun()
- // * PersistentPostRun()
- // All functions get the same args, the arguments after the command name.
- //
- // PersistentPreRun: children of this command will inherit and execute.
- PersistentPreRun func(cmd *Command, args []string)
- // PersistentPreRunE: PersistentPreRun but returns an error.
- PersistentPreRunE func(cmd *Command, args []string) error
- // PreRun: children of this command will not inherit.
- PreRun func(cmd *Command, args []string)
- // PreRunE: PreRun but returns an error.
- PreRunE func(cmd *Command, args []string) error
- // Run: Typically the actual work function. Most commands will only implement this.
- Run func(cmd *Command, args []string)
- // RunE: Run but returns an error.
- RunE func(cmd *Command, args []string) error
- // PostRun: run after the Run command.
- PostRun func(cmd *Command, args []string)
- // PostRunE: PostRun but returns an error.
- PostRunE func(cmd *Command, args []string) error
- // PersistentPostRun: children of this command will inherit and execute after PostRun.
- PersistentPostRun func(cmd *Command, args []string)
- // PersistentPostRunE: PersistentPostRun but returns an error.
- PersistentPostRunE func(cmd *Command, args []string) error
-
- // SilenceErrors is an option to quiet errors down stream.
- SilenceErrors bool
-
- // SilenceUsage is an option to silence usage when an error occurs.
- SilenceUsage bool
-
- // DisableFlagParsing disables the flag parsing.
- // If this is true all flags will be passed to the command as arguments.
- DisableFlagParsing bool
-
- // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
- // will be printed by generating docs for this command.
- DisableAutoGenTag bool
-
- // DisableFlagsInUseLine will disable the addition of [flags] to the usage
- // line of a command when printing help or generating docs
- DisableFlagsInUseLine bool
-
- // DisableSuggestions disables the suggestions based on Levenshtein distance
- // that go along with 'unknown command' messages.
- DisableSuggestions bool
- // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
- // Must be > 0.
- SuggestionsMinimumDistance int
-
- // TraverseChildren parses flags on all parents before executing child command.
- TraverseChildren bool
-
- //FParseErrWhitelist flag parse errors to be ignored
- FParseErrWhitelist FParseErrWhitelist
-
- // commands is the list of commands supported by this program.
- commands []*Command
- // parent is a parent command for this command.
- parent *Command
- // Max lengths of commands' string lengths for use in padding.
- commandsMaxUseLen int
- commandsMaxCommandPathLen int
- commandsMaxNameLen int
- // commandsAreSorted defines, if command slice are sorted or not.
- commandsAreSorted bool
- // commandCalledAs is the name or alias value used to call this command.
- commandCalledAs struct {
- name string
- called bool
- }
-
- // args is actual args parsed from flags.
- args []string
- // flagErrorBuf contains all error messages from pflag.
- flagErrorBuf *bytes.Buffer
- // flags is full set of flags.
- flags *flag.FlagSet
- // pflags contains persistent flags.
- pflags *flag.FlagSet
- // lflags contains local flags.
- lflags *flag.FlagSet
- // iflags contains inherited flags.
- iflags *flag.FlagSet
- // parentsPflags is all persistent flags of cmd's parents.
- parentsPflags *flag.FlagSet
- // globNormFunc is the global normalization function
- // that we can use on every pflag set and children commands
- globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
-
- // usageFunc is usage func defined by user.
- usageFunc func(*Command) error
- // usageTemplate is usage template defined by user.
- usageTemplate string
- // flagErrorFunc is func defined by user and it's called when the parsing of
- // flags returns an error.
- flagErrorFunc func(*Command, error) error
- // helpTemplate is help template defined by user.
- helpTemplate string
- // helpFunc is help func defined by user.
- helpFunc func(*Command, []string)
- // helpCommand is command with usage 'help'. If it's not defined by user,
- // cobra uses default help command.
- helpCommand *Command
- // versionTemplate is the version template defined by user.
- versionTemplate string
-
- // inReader is a reader defined by the user that replaces stdin
- inReader io.Reader
- // outWriter is a writer defined by the user that replaces stdout
- outWriter io.Writer
- // errWriter is a writer defined by the user that replaces stderr
- errWriter io.Writer
-}
-
-// 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) {
- c.args = a
-}
-
-// SetOutput sets the destination for usage and error messages.
-// If output is nil, os.Stderr is used.
-// Deprecated: Use SetOut and/or SetErr instead
-func (c *Command) SetOutput(output io.Writer) {
- c.outWriter = output
- c.errWriter = output
-}
-
-// SetOut sets the destination for usage messages.
-// If newOut is nil, os.Stdout is used.
-func (c *Command) SetOut(newOut io.Writer) {
- c.outWriter = newOut
-}
-
-// SetErr sets the destination for error messages.
-// If newErr is nil, os.Stderr is used.
-func (c *Command) SetErr(newErr io.Writer) {
- c.errWriter = newErr
-}
-
-// SetOut sets the source for input data
-// If newIn is nil, os.Stdin is used.
-func (c *Command) SetIn(newIn io.Reader) {
- c.inReader = newIn
-}
-
-// SetUsageFunc sets usage function. Usage can be defined by application.
-func (c *Command) SetUsageFunc(f func(*Command) error) {
- c.usageFunc = f
-}
-
-// SetUsageTemplate sets usage template. Can be defined by Application.
-func (c *Command) SetUsageTemplate(s string) {
- c.usageTemplate = s
-}
-
-// SetFlagErrorFunc sets a function to generate an error when flag parsing
-// fails.
-func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
- c.flagErrorFunc = f
-}
-
-// SetHelpFunc sets help function. Can be defined by Application.
-func (c *Command) SetHelpFunc(f func(*Command, []string)) {
- c.helpFunc = f
-}
-
-// SetHelpCommand sets help command.
-func (c *Command) SetHelpCommand(cmd *Command) {
- c.helpCommand = cmd
-}
-
-// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
-func (c *Command) SetHelpTemplate(s string) {
- c.helpTemplate = s
-}
-
-// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
-func (c *Command) SetVersionTemplate(s string) {
- c.versionTemplate = s
-}
-
-// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
-// The user should not have a cyclic dependency on commands.
-func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
- c.Flags().SetNormalizeFunc(n)
- c.PersistentFlags().SetNormalizeFunc(n)
- c.globNormFunc = n
-
- for _, command := range c.commands {
- command.SetGlobalNormalizationFunc(n)
- }
-}
-
-// OutOrStdout returns output to stdout.
-func (c *Command) OutOrStdout() io.Writer {
- return c.getOut(os.Stdout)
-}
-
-// OutOrStderr returns output to stderr
-func (c *Command) OutOrStderr() io.Writer {
- return c.getOut(os.Stderr)
-}
-
-// ErrOrStderr returns output to stderr
-func (c *Command) ErrOrStderr() io.Writer {
- return c.getErr(os.Stderr)
-}
-
-// ErrOrStderr returns output to stderr
-func (c *Command) InOrStdin() io.Reader {
- return c.getIn(os.Stdin)
-}
-
-func (c *Command) getOut(def io.Writer) io.Writer {
- if c.outWriter != nil {
- return c.outWriter
- }
- if c.HasParent() {
- return c.parent.getOut(def)
- }
- return def
-}
-
-func (c *Command) getErr(def io.Writer) io.Writer {
- if c.errWriter != nil {
- return c.errWriter
- }
- if c.HasParent() {
- return c.parent.getErr(def)
- }
- return def
-}
-
-func (c *Command) getIn(def io.Reader) io.Reader {
- if c.inReader != nil {
- return c.inReader
- }
- if c.HasParent() {
- return c.parent.getIn(def)
- }
- return def
-}
-
-// UsageFunc returns either the function set by SetUsageFunc for this command
-// or a parent, or it returns a default usage function.
-func (c *Command) UsageFunc() (f func(*Command) error) {
- if c.usageFunc != nil {
- return c.usageFunc
- }
- if c.HasParent() {
- return c.Parent().UsageFunc()
- }
- return func(c *Command) error {
- c.mergePersistentFlags()
- err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- return err
- }
-}
-
-// Usage puts out the usage for the command.
-// Used when a user provides invalid input.
-// Can be defined by user by overriding UsageFunc.
-func (c *Command) Usage() error {
- return c.UsageFunc()(c)
-}
-
-// HelpFunc returns either the function set by SetHelpFunc for this command
-// or a parent, or it returns a function with default help behavior.
-func (c *Command) HelpFunc() func(*Command, []string) {
- if c.helpFunc != nil {
- return c.helpFunc
- }
- if c.HasParent() {
- return c.Parent().HelpFunc()
- }
- return func(c *Command, a []string) {
- c.mergePersistentFlags()
- err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- }
-}
-
-// Help puts out the help for the command.
-// Used when a user calls help [command].
-// Can be defined by user by overriding HelpFunc.
-func (c *Command) Help() error {
- c.HelpFunc()(c, []string{})
- return nil
-}
-
-// UsageString returns usage string.
-func (c *Command) UsageString() string {
- // Storing normal writers
- tmpOutput := c.outWriter
- tmpErr := c.errWriter
-
- bb := new(bytes.Buffer)
- c.outWriter = bb
- c.errWriter = bb
-
- c.Usage()
-
- // Setting things back to normal
- c.outWriter = tmpOutput
- c.errWriter = tmpErr
-
- return bb.String()
-}
-
-// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
-// command or a parent, or it returns a function which returns the original
-// error.
-func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
- if c.flagErrorFunc != nil {
- return c.flagErrorFunc
- }
-
- if c.HasParent() {
- return c.parent.FlagErrorFunc()
- }
- return func(c *Command, err error) error {
- return err
- }
-}
-
-var minUsagePadding = 25
-
-// UsagePadding return padding for the usage.
-func (c *Command) UsagePadding() int {
- if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
- return minUsagePadding
- }
- return c.parent.commandsMaxUseLen
-}
-
-var minCommandPathPadding = 11
-
-// CommandPathPadding return padding for the command path.
-func (c *Command) CommandPathPadding() int {
- if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
- return minCommandPathPadding
- }
- return c.parent.commandsMaxCommandPathLen
-}
-
-var minNamePadding = 11
-
-// NamePadding returns padding for the name.
-func (c *Command) NamePadding() int {
- if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
- return minNamePadding
- }
- return c.parent.commandsMaxNameLen
-}
-
-// UsageTemplate returns usage template for the command.
-func (c *Command) UsageTemplate() string {
- if c.usageTemplate != "" {
- return c.usageTemplate
- }
-
- if c.HasParent() {
- return c.parent.UsageTemplate()
- }
- return `Usage:{{if .Runnable}}
- {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
- {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
-
-Aliases:
- {{.NameAndAliases}}{{end}}{{if .HasExample}}
-
-Examples:
-{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
-
-Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
-
-Flags:
-{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
-
-Global Flags:
-{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
-
-Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
- {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
-
-Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
-`
-}
-
-// HelpTemplate return help template for the command.
-func (c *Command) HelpTemplate() string {
- if c.helpTemplate != "" {
- return c.helpTemplate
- }
-
- if c.HasParent() {
- return c.parent.HelpTemplate()
- }
- return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
-
-{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
-}
-
-// VersionTemplate return version template for the command.
-func (c *Command) VersionTemplate() string {
- if c.versionTemplate != "" {
- return c.versionTemplate
- }
-
- if c.HasParent() {
- return c.parent.VersionTemplate()
- }
- return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
-`
-}
-
-func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
- flag := fs.Lookup(name)
- if flag == nil {
- return false
- }
- return flag.NoOptDefVal != ""
-}
-
-func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
- if len(name) == 0 {
- return false
- }
-
- flag := fs.ShorthandLookup(name[:1])
- if flag == nil {
- return false
- }
- return flag.NoOptDefVal != ""
-}
-
-func stripFlags(args []string, c *Command) []string {
- if len(args) == 0 {
- return args
- }
- c.mergePersistentFlags()
-
- commands := []string{}
- flags := c.Flags()
-
-Loop:
- for len(args) > 0 {
- s := args[0]
- args = args[1:]
- switch {
- case s == "--":
- // "--" terminates the flags
- break Loop
- case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
- // If '--flag arg' then
- // delete arg from args.
- fallthrough // (do the same as below)
- case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
- // If '-f arg' then
- // delete 'arg' from args or break the loop if len(args) <= 1.
- if len(args) <= 1 {
- break Loop
- } else {
- args = args[1:]
- continue
- }
- case s != "" && !strings.HasPrefix(s, "-"):
- commands = append(commands, s)
- }
- }
-
- return commands
-}
-
-// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
-// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
-func argsMinusFirstX(args []string, x string) []string {
- for i, y := range args {
- if x == y {
- ret := []string{}
- ret = append(ret, args[:i]...)
- ret = append(ret, args[i+1:]...)
- return ret
- }
- }
- return args
-}
-
-func isFlagArg(arg string) bool {
- return ((len(arg) >= 3 && arg[1] == '-') ||
- (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
-}
-
-// Find the target command given the args and command tree
-// Meant to be run on the highest node. Only searches down.
-func (c *Command) Find(args []string) (*Command, []string, error) {
- var innerfind func(*Command, []string) (*Command, []string)
-
- innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
- argsWOflags := stripFlags(innerArgs, c)
- if len(argsWOflags) == 0 {
- return c, innerArgs
- }
- nextSubCmd := argsWOflags[0]
-
- cmd := c.findNext(nextSubCmd)
- if cmd != nil {
- return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
- }
- return c, innerArgs
- }
-
- commandFound, a := innerfind(c, args)
- if commandFound.Args == nil {
- return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
- }
- return commandFound, a, nil
-}
-
-func (c *Command) findSuggestions(arg string) string {
- if c.DisableSuggestions {
- return ""
- }
- if c.SuggestionsMinimumDistance <= 0 {
- c.SuggestionsMinimumDistance = 2
- }
- suggestionsString := ""
- if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
- suggestionsString += "\n\nDid you mean this?\n"
- for _, s := range suggestions {
- suggestionsString += fmt.Sprintf("\t%v\n", s)
- }
- }
- return suggestionsString
-}
-
-func (c *Command) findNext(next string) *Command {
- matches := make([]*Command, 0)
- for _, cmd := range c.commands {
- if cmd.Name() == next || cmd.HasAlias(next) {
- cmd.commandCalledAs.name = next
- return cmd
- }
- if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {
- matches = append(matches, cmd)
- }
- }
-
- if len(matches) == 1 {
- return matches[0]
- }
-
- return nil
-}
-
-// Traverse the command tree to find the command, and parse args for
-// each parent.
-func (c *Command) Traverse(args []string) (*Command, []string, error) {
- flags := []string{}
- inFlag := false
-
- for i, arg := range args {
- switch {
- // A long flag with a space separated value
- case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
- // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
- inFlag = !hasNoOptDefVal(arg[2:], c.Flags())
- flags = append(flags, arg)
- continue
- // A short flag with a space separated value
- case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):
- inFlag = true
- flags = append(flags, arg)
- continue
- // The value for a flag
- case inFlag:
- inFlag = false
- flags = append(flags, arg)
- continue
- // A flag without a value, or with an `=` separated value
- case isFlagArg(arg):
- flags = append(flags, arg)
- continue
- }
-
- cmd := c.findNext(arg)
- if cmd == nil {
- return c, args, nil
- }
-
- if err := c.ParseFlags(flags); err != nil {
- return nil, args, err
- }
- return cmd.Traverse(args[i+1:])
- }
- return c, args, nil
-}
-
-// SuggestionsFor provides suggestions for the typedName.
-func (c *Command) SuggestionsFor(typedName string) []string {
- suggestions := []string{}
- for _, cmd := range c.commands {
- if cmd.IsAvailableCommand() {
- levenshteinDistance := ld(typedName, cmd.Name(), true)
- suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
- suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
- if suggestByLevenshtein || suggestByPrefix {
- suggestions = append(suggestions, cmd.Name())
- }
- for _, explicitSuggestion := range cmd.SuggestFor {
- if strings.EqualFold(typedName, explicitSuggestion) {
- suggestions = append(suggestions, cmd.Name())
- }
- }
- }
- }
- return suggestions
-}
-
-// VisitParents visits all parents of the command and invokes fn on each parent.
-func (c *Command) VisitParents(fn func(*Command)) {
- if c.HasParent() {
- fn(c.Parent())
- c.Parent().VisitParents(fn)
- }
-}
-
-// Root finds root command.
-func (c *Command) Root() *Command {
- if c.HasParent() {
- return c.Parent().Root()
- }
- return c
-}
-
-// ArgsLenAtDash will return the length of c.Flags().Args at the moment
-// when a -- was found during args parsing.
-func (c *Command) ArgsLenAtDash() int {
- return c.Flags().ArgsLenAtDash()
-}
-
-func (c *Command) execute(a []string) (err error) {
- if c == nil {
- return fmt.Errorf("Called Execute() on a nil Command")
- }
-
- if len(c.Deprecated) > 0 {
- c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
- }
-
- // initialize help and version flag at the last point possible to allow for user
- // overriding
- c.InitDefaultHelpFlag()
- c.InitDefaultVersionFlag()
-
- err = c.ParseFlags(a)
- if err != nil {
- return c.FlagErrorFunc()(c, err)
- }
-
- // If help is called, regardless of other flags, return we want help.
- // Also say we need help if the command isn't runnable.
- helpVal, err := c.Flags().GetBool("help")
- if err != nil {
- // should be impossible to get here as we always declare a help
- // flag in InitDefaultHelpFlag()
- c.Println("\"help\" flag declared as non-bool. Please correct your code")
- return err
- }
-
- if helpVal {
- return flag.ErrHelp
- }
-
- // for back-compat, only add version flag behavior if version is defined
- if c.Version != "" {
- versionVal, err := c.Flags().GetBool("version")
- if err != nil {
- c.Println("\"version\" flag declared as non-bool. Please correct your code")
- return err
- }
- if versionVal {
- err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- return err
- }
- }
-
- if !c.Runnable() {
- return flag.ErrHelp
- }
-
- c.preRun()
-
- argWoFlags := c.Flags().Args()
- if c.DisableFlagParsing {
- argWoFlags = a
- }
-
- if err := c.ValidateArgs(argWoFlags); err != nil {
- return err
- }
-
- for p := c; p != nil; p = p.Parent() {
- if p.PersistentPreRunE != nil {
- if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
- return err
- }
- break
- } else if p.PersistentPreRun != nil {
- p.PersistentPreRun(c, argWoFlags)
- break
- }
- }
- if c.PreRunE != nil {
- if err := c.PreRunE(c, argWoFlags); err != nil {
- return err
- }
- } else if c.PreRun != nil {
- c.PreRun(c, argWoFlags)
- }
-
- if err := c.validateRequiredFlags(); err != nil {
- return err
- }
- if c.RunE != nil {
- if err := c.RunE(c, argWoFlags); err != nil {
- return err
- }
- } else {
- c.Run(c, argWoFlags)
- }
- if c.PostRunE != nil {
- if err := c.PostRunE(c, argWoFlags); err != nil {
- return err
- }
- } else if c.PostRun != nil {
- c.PostRun(c, argWoFlags)
- }
- for p := c; p != nil; p = p.Parent() {
- if p.PersistentPostRunE != nil {
- if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
- return err
- }
- break
- } else if p.PersistentPostRun != nil {
- p.PersistentPostRun(c, argWoFlags)
- break
- }
- }
-
- return nil
-}
-
-func (c *Command) preRun() {
- for _, x := range initializers {
- x()
- }
-}
-
-// Execute uses the args (os.Args[1:] by default)
-// and run through the command tree finding appropriate matches
-// for commands and then corresponding flags.
-func (c *Command) Execute() error {
- _, err := c.ExecuteC()
- return err
-}
-
-// ExecuteC executes the command.
-func (c *Command) ExecuteC() (cmd *Command, err error) {
- // Regardless of what command execute is called on, run on Root only
- if c.HasParent() {
- return c.Root().ExecuteC()
- }
-
- // windows hook
- if preExecHookFn != nil {
- preExecHookFn(c)
- }
-
- // initialize help as the last point possible to allow for user
- // overriding
- c.InitDefaultHelpCmd()
-
- args := c.args
-
- // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
- if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
- args = os.Args[1:]
- }
-
- var flags []string
- if c.TraverseChildren {
- cmd, flags, err = c.Traverse(args)
- } else {
- cmd, flags, err = c.Find(args)
- }
- if err != nil {
- // If found parse to a subcommand and then failed, talk about the subcommand
- if cmd != nil {
- c = cmd
- }
- if !c.SilenceErrors {
- c.Println("Error:", err.Error())
- c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
- }
- return c, err
- }
-
- cmd.commandCalledAs.called = true
- if cmd.commandCalledAs.name == "" {
- cmd.commandCalledAs.name = cmd.Name()
- }
-
- err = cmd.execute(flags)
- if err != nil {
- // Always show help if requested, even if SilenceErrors is in
- // effect
- if err == flag.ErrHelp {
- cmd.HelpFunc()(cmd, args)
- return cmd, nil
- }
-
- // If root command has SilentErrors flagged,
- // all subcommands should respect it
- if !cmd.SilenceErrors && !c.SilenceErrors {
- c.Println("Error:", err.Error())
- }
-
- // If root command has SilentUsage flagged,
- // all subcommands should respect it
- if !cmd.SilenceUsage && !c.SilenceUsage {
- c.Println(cmd.UsageString())
- }
- }
- return cmd, err
-}
-
-func (c *Command) ValidateArgs(args []string) error {
- if c.Args == nil {
- return nil
- }
- return c.Args(c, args)
-}
-
-func (c *Command) validateRequiredFlags() error {
- flags := c.Flags()
- missingFlagNames := []string{}
- flags.VisitAll(func(pflag *flag.Flag) {
- requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
- if !found {
- return
- }
- if (requiredAnnotation[0] == "true") && !pflag.Changed {
- missingFlagNames = append(missingFlagNames, pflag.Name)
- }
- })
-
- if len(missingFlagNames) > 0 {
- return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))
- }
- return nil
-}
-
-// 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.
-func (c *Command) InitDefaultHelpFlag() {
- c.mergePersistentFlags()
- if c.Flags().Lookup("help") == nil {
- usage := "help for "
- if c.Name() == "" {
- usage += "this command"
- } else {
- usage += c.Name()
- }
- c.Flags().BoolP("help", "h", false, usage)
- }
-}
-
-// InitDefaultVersionFlag adds default version flag to c.
-// It is called automatically by executing the c.
-// If c already has a version flag, it will do nothing.
-// If c.Version is empty, it will do nothing.
-func (c *Command) InitDefaultVersionFlag() {
- if c.Version == "" {
- return
- }
-
- c.mergePersistentFlags()
- if c.Flags().Lookup("version") == nil {
- usage := "version for "
- if c.Name() == "" {
- usage += "this command"
- } else {
- usage += c.Name()
- }
- c.Flags().Bool("version", false, usage)
- }
-}
-
-// InitDefaultHelpCmd adds default help command to c.
-// It is called automatically by executing the c or by calling help and usage.
-// If c already has help command or c has no subcommands, it will do nothing.
-func (c *Command) InitDefaultHelpCmd() {
- if !c.HasSubCommands() {
- return
- }
-
- if c.helpCommand == nil {
- c.helpCommand = &Command{
- Use: "help [command]",
- Short: "Help about any command",
- Long: `Help provides help for any command in the application.
-Simply type ` + c.Name() + ` help [path to command] for full details.`,
-
- Run: func(c *Command, args []string) {
- cmd, _, e := c.Root().Find(args)
- if cmd == nil || e != nil {
- c.Printf("Unknown help topic %#q\n", args)
- c.Root().Usage()
- } else {
- cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
- cmd.Help()
- }
- },
- }
- }
- c.RemoveCommand(c.helpCommand)
- c.AddCommand(c.helpCommand)
-}
-
-// ResetCommands delete parent, subcommand and help command from c.
-func (c *Command) ResetCommands() {
- c.parent = nil
- c.commands = nil
- c.helpCommand = nil
- c.parentsPflags = nil
-}
-
-// Sorts commands by their names.
-type commandSorterByName []*Command
-
-func (c commandSorterByName) Len() int { return len(c) }
-func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
-func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
-
-// Commands returns a sorted slice of child commands.
-func (c *Command) Commands() []*Command {
- // do not sort commands if it already sorted or sorting was disabled
- if EnableCommandSorting && !c.commandsAreSorted {
- sort.Sort(commandSorterByName(c.commands))
- c.commandsAreSorted = true
- }
- return c.commands
-}
-
-// AddCommand adds one or more commands to this parent command.
-func (c *Command) AddCommand(cmds ...*Command) {
- for i, x := range cmds {
- if cmds[i] == c {
- panic("Command can't be a child of itself")
- }
- cmds[i].parent = c
- // update max lengths
- usageLen := len(x.Use)
- if usageLen > c.commandsMaxUseLen {
- c.commandsMaxUseLen = usageLen
- }
- commandPathLen := len(x.CommandPath())
- if commandPathLen > c.commandsMaxCommandPathLen {
- c.commandsMaxCommandPathLen = commandPathLen
- }
- nameLen := len(x.Name())
- if nameLen > c.commandsMaxNameLen {
- c.commandsMaxNameLen = nameLen
- }
- // If global normalization function exists, update all children
- if c.globNormFunc != nil {
- x.SetGlobalNormalizationFunc(c.globNormFunc)
- }
- c.commands = append(c.commands, x)
- c.commandsAreSorted = false
- }
-}
-
-// RemoveCommand removes one or more commands from a parent command.
-func (c *Command) RemoveCommand(cmds ...*Command) {
- commands := []*Command{}
-main:
- for _, command := range c.commands {
- for _, cmd := range cmds {
- if command == cmd {
- command.parent = nil
- continue main
- }
- }
- commands = append(commands, command)
- }
- c.commands = commands
- // recompute all lengths
- c.commandsMaxUseLen = 0
- c.commandsMaxCommandPathLen = 0
- c.commandsMaxNameLen = 0
- for _, command := range c.commands {
- usageLen := len(command.Use)
- if usageLen > c.commandsMaxUseLen {
- c.commandsMaxUseLen = usageLen
- }
- commandPathLen := len(command.CommandPath())
- if commandPathLen > c.commandsMaxCommandPathLen {
- c.commandsMaxCommandPathLen = commandPathLen
- }
- nameLen := len(command.Name())
- if nameLen > c.commandsMaxNameLen {
- c.commandsMaxNameLen = nameLen
- }
- }
-}
-
-// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
-func (c *Command) Print(i ...interface{}) {
- fmt.Fprint(c.OutOrStderr(), i...)
-}
-
-// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
-func (c *Command) Println(i ...interface{}) {
- c.Print(fmt.Sprintln(i...))
-}
-
-// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
-func (c *Command) Printf(format string, i ...interface{}) {
- c.Print(fmt.Sprintf(format, i...))
-}
-
-// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
-func (c *Command) PrintErr(i ...interface{}) {
- fmt.Fprint(c.ErrOrStderr(), i...)
-}
-
-// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
-func (c *Command) PrintErrln(i ...interface{}) {
- c.Print(fmt.Sprintln(i...))
-}
-
-// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
-func (c *Command) PrintErrf(format string, i ...interface{}) {
- c.Print(fmt.Sprintf(format, i...))
-}
-
-// CommandPath returns the full path to this command.
-func (c *Command) CommandPath() string {
- if c.HasParent() {
- return c.Parent().CommandPath() + " " + c.Name()
- }
- return c.Name()
-}
-
-// UseLine puts out the full usage for a given command (including parents).
-func (c *Command) UseLine() string {
- var useline string
- if c.HasParent() {
- useline = c.parent.CommandPath() + " " + c.Use
- } else {
- useline = c.Use
- }
- if c.DisableFlagsInUseLine {
- return useline
- }
- if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
- useline += " [flags]"
- }
- return useline
-}
-
-// DebugFlags used to determine which flags have been assigned to which commands
-// and which persist.
-func (c *Command) DebugFlags() {
- c.Println("DebugFlags called on", c.Name())
- var debugflags func(*Command)
-
- debugflags = func(x *Command) {
- if x.HasFlags() || x.HasPersistentFlags() {
- c.Println(x.Name())
- }
- if x.HasFlags() {
- x.flags.VisitAll(func(f *flag.Flag) {
- if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
- } else {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
- }
- })
- }
- if x.HasPersistentFlags() {
- x.pflags.VisitAll(func(f *flag.Flag) {
- if x.HasFlags() {
- if x.flags.Lookup(f.Name) == nil {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
- }
- } else {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
- }
- })
- }
- c.Println(x.flagErrorBuf)
- if x.HasSubCommands() {
- for _, y := range x.commands {
- debugflags(y)
- }
- }
- }
-
- debugflags(c)
-}
-
-// Name returns the command's name: the first word in the use line.
-func (c *Command) Name() string {
- name := c.Use
- i := strings.Index(name, " ")
- if i >= 0 {
- name = name[:i]
- }
- return name
-}
-
-// 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 {
- return true
- }
- }
- return false
-}
-
-// CalledAs returns the command name or alias that was used to invoke
-// this command or an empty string if the command has not been called.
-func (c *Command) CalledAs() string {
- if c.commandCalledAs.called {
- return c.commandCalledAs.name
- }
- return ""
-}
-
-// hasNameOrAliasPrefix returns true if the Name or any of aliases start
-// with prefix
-func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
- if strings.HasPrefix(c.Name(), prefix) {
- c.commandCalledAs.name = c.Name()
- return true
- }
- for _, alias := range c.Aliases {
- if strings.HasPrefix(alias, prefix) {
- c.commandCalledAs.name = alias
- return true
- }
- }
- return false
-}
-
-// NameAndAliases returns a list of the command name and all aliases
-func (c *Command) NameAndAliases() string {
- return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
-}
-
-// HasExample determines if the command has example.
-func (c *Command) HasExample() bool {
- return len(c.Example) > 0
-}
-
-// Runnable determines if the command is itself runnable.
-func (c *Command) Runnable() bool {
- return c.Run != nil || c.RunE != nil
-}
-
-// HasSubCommands determines if the command has children commands.
-func (c *Command) HasSubCommands() bool {
- return len(c.commands) > 0
-}
-
-// IsAvailableCommand determines if a command is available as a non-help command
-// (this includes all non deprecated/hidden commands).
-func (c *Command) IsAvailableCommand() bool {
- if len(c.Deprecated) != 0 || c.Hidden {
- return false
- }
-
- if c.HasParent() && c.Parent().helpCommand == c {
- return false
- }
-
- if c.Runnable() || c.HasAvailableSubCommands() {
- return true
- }
-
- return false
-}
-
-// IsAdditionalHelpTopicCommand determines if a command is an additional
-// help topic command; additional help topic command is determined by the
-// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
-// are runnable/hidden/deprecated.
-// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
-func (c *Command) IsAdditionalHelpTopicCommand() bool {
- // if a command is runnable, deprecated, or hidden it is not a 'help' command
- if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
- return false
- }
-
- // if any non-help sub commands are found, the command is not a 'help' command
- for _, sub := range c.commands {
- if !sub.IsAdditionalHelpTopicCommand() {
- return false
- }
- }
-
- // the command either has no sub commands, or no non-help sub commands
- return true
-}
-
-// HasHelpSubCommands determines if a command has any available 'help' sub commands
-// that need to be shown in the usage/help default template under 'additional help
-// topics'.
-func (c *Command) HasHelpSubCommands() bool {
- // return true on the first found available 'help' sub command
- for _, sub := range c.commands {
- if sub.IsAdditionalHelpTopicCommand() {
- return true
- }
- }
-
- // the command either has no sub commands, or no available 'help' sub commands
- return false
-}
-
-// HasAvailableSubCommands determines if a command has available sub commands that
-// need to be shown in the usage/help default template under 'available commands'.
-func (c *Command) HasAvailableSubCommands() bool {
- // return true on the first found available (non deprecated/help/hidden)
- // sub command
- for _, sub := range c.commands {
- if sub.IsAvailableCommand() {
- return true
- }
- }
-
- // the command either has no sub commands, or no available (non deprecated/help/hidden)
- // sub commands
- return false
-}
-
-// HasParent determines if the command is a child command.
-func (c *Command) HasParent() bool {
- return c.parent != nil
-}
-
-// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.
-func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
- return c.globNormFunc
-}
-
-// Flags returns the complete FlagSet that applies
-// to this command (local and persistent declared here and by all parents).
-func (c *Command) Flags() *flag.FlagSet {
- if c.flags == nil {
- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.flags.SetOutput(c.flagErrorBuf)
- }
-
- return c.flags
-}
-
-// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
-func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
- persistentFlags := c.PersistentFlags()
-
- out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.LocalFlags().VisitAll(func(f *flag.Flag) {
- if persistentFlags.Lookup(f.Name) == nil {
- out.AddFlag(f)
- }
- })
- return out
-}
-
-// LocalFlags returns the local FlagSet specifically set in the current command.
-func (c *Command) LocalFlags() *flag.FlagSet {
- c.mergePersistentFlags()
-
- if c.lflags == nil {
- c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.lflags.SetOutput(c.flagErrorBuf)
- }
- c.lflags.SortFlags = c.Flags().SortFlags
- if c.globNormFunc != nil {
- c.lflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- addToLocal := func(f *flag.Flag) {
- if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {
- c.lflags.AddFlag(f)
- }
- }
- c.Flags().VisitAll(addToLocal)
- c.PersistentFlags().VisitAll(addToLocal)
- return c.lflags
-}
-
-// InheritedFlags returns all flags which were inherited from parent commands.
-func (c *Command) InheritedFlags() *flag.FlagSet {
- c.mergePersistentFlags()
-
- if c.iflags == nil {
- c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.iflags.SetOutput(c.flagErrorBuf)
- }
-
- local := c.LocalFlags()
- if c.globNormFunc != nil {
- c.iflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- c.parentsPflags.VisitAll(func(f *flag.Flag) {
- if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
- c.iflags.AddFlag(f)
- }
- })
- return c.iflags
-}
-
-// NonInheritedFlags returns all flags which were not inherited from parent commands.
-func (c *Command) NonInheritedFlags() *flag.FlagSet {
- return c.LocalFlags()
-}
-
-// PersistentFlags returns the persistent FlagSet specifically set in the current command.
-func (c *Command) PersistentFlags() *flag.FlagSet {
- if c.pflags == nil {
- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.pflags.SetOutput(c.flagErrorBuf)
- }
- return c.pflags
-}
-
-// ResetFlags deletes all flags from command.
-func (c *Command) ResetFlags() {
- c.flagErrorBuf = new(bytes.Buffer)
- c.flagErrorBuf.Reset()
- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.flags.SetOutput(c.flagErrorBuf)
- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.pflags.SetOutput(c.flagErrorBuf)
-
- c.lflags = nil
- c.iflags = nil
- c.parentsPflags = nil
-}
-
-// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
-func (c *Command) HasFlags() bool {
- return c.Flags().HasFlags()
-}
-
-// HasPersistentFlags checks if the command contains persistent flags.
-func (c *Command) HasPersistentFlags() bool {
- return c.PersistentFlags().HasFlags()
-}
-
-// HasLocalFlags checks if the command has flags specifically declared locally.
-func (c *Command) HasLocalFlags() bool {
- return c.LocalFlags().HasFlags()
-}
-
-// HasInheritedFlags checks if the command has flags inherited from its parent command.
-func (c *Command) HasInheritedFlags() bool {
- return c.InheritedFlags().HasFlags()
-}
-
-// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
-// structure) which are not hidden or deprecated.
-func (c *Command) HasAvailableFlags() bool {
- return c.Flags().HasAvailableFlags()
-}
-
-// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
-func (c *Command) HasAvailablePersistentFlags() bool {
- return c.PersistentFlags().HasAvailableFlags()
-}
-
-// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
-// or deprecated.
-func (c *Command) HasAvailableLocalFlags() bool {
- return c.LocalFlags().HasAvailableFlags()
-}
-
-// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
-// not hidden or deprecated.
-func (c *Command) HasAvailableInheritedFlags() bool {
- return c.InheritedFlags().HasAvailableFlags()
-}
-
-// Flag climbs up the command tree looking for matching flag.
-func (c *Command) Flag(name string) (flag *flag.Flag) {
- flag = c.Flags().Lookup(name)
-
- if flag == nil {
- flag = c.persistentFlag(name)
- }
-
- return
-}
-
-// Recursively find matching persistent flag.
-func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
- if c.HasPersistentFlags() {
- flag = c.PersistentFlags().Lookup(name)
- }
-
- if flag == nil {
- c.updateParentsPflags()
- flag = c.parentsPflags.Lookup(name)
- }
- return
-}
-
-// ParseFlags parses persistent flag tree and local flags.
-func (c *Command) ParseFlags(args []string) error {
- if c.DisableFlagParsing {
- return nil
- }
-
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- beforeErrorBufLen := c.flagErrorBuf.Len()
- c.mergePersistentFlags()
-
- //do it here after merging all flags and just before parse
- c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)
-
- err := c.Flags().Parse(args)
- // Print warnings if they occurred (e.g. deprecated flag messages).
- if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
- c.Print(c.flagErrorBuf.String())
- }
-
- return err
-}
-
-// Parent returns a commands parent command.
-func (c *Command) Parent() *Command {
- return c.parent
-}
-
-// mergePersistentFlags merges c.PersistentFlags() to c.Flags()
-// and adds missing persistent flags of all parents.
-func (c *Command) mergePersistentFlags() {
- c.updateParentsPflags()
- c.Flags().AddFlagSet(c.PersistentFlags())
- c.Flags().AddFlagSet(c.parentsPflags)
-}
-
-// updateParentsPflags updates c.parentsPflags by adding
-// new persistent flags of all parents.
-// If c.parentsPflags == nil, it makes new.
-func (c *Command) updateParentsPflags() {
- if c.parentsPflags == nil {
- c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.parentsPflags.SetOutput(c.flagErrorBuf)
- c.parentsPflags.SortFlags = false
- }
-
- if c.globNormFunc != nil {
- c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
-
- c.VisitParents(func(parent *Command) {
- c.parentsPflags.AddFlagSet(parent.PersistentFlags())
- })
-}
diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go
deleted file mode 100644
index 6159c1cc..00000000
--- a/vendor/github.com/spf13/cobra/command_notwin.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// +build !windows
-
-package cobra
-
-var preExecHookFn func(*Command)
diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go
deleted file mode 100644
index 8768b173..00000000
--- a/vendor/github.com/spf13/cobra/command_win.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// +build windows
-
-package cobra
-
-import (
- "fmt"
- "os"
- "time"
-
- "github.com/inconshreveable/mousetrap"
-)
-
-var preExecHookFn = preExecHook
-
-func preExecHook(c *Command) {
- if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
- c.Print(MousetrapHelpText)
- if MousetrapDisplayDuration > 0 {
- time.Sleep(MousetrapDisplayDuration)
- } else {
- c.Println("Press return to continue...")
- fmt.Scanln()
- }
- os.Exit(1)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.go b/vendor/github.com/spf13/cobra/doc/man_docs.go
deleted file mode 100644
index 4a062339..00000000
--- a/vendor/github.com/spf13/cobra/doc/man_docs.go
+++ /dev/null
@@ -1,247 +0,0 @@
-// Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package doc
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/cpuguy83/go-md2man/md2man"
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
-)
-
-// GenManTree will generate a man page for this command and all descendants
-// in the directory given. The header may be nil. This function may not work
-// correctly if your command names have `-` in them. If you have `cmd` with two
-// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
-// it is undefined which help output will be in the file `cmd-sub-third.1`.
-func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
- return GenManTreeFromOpts(cmd, GenManTreeOptions{
- Header: header,
- Path: dir,
- CommandSeparator: "-",
- })
-}
-
-// GenManTreeFromOpts generates a man page for the command and all descendants.
-// The pages are written to the opts.Path directory.
-func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
- header := opts.Header
- if header == nil {
- header = &GenManHeader{}
- }
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenManTreeFromOpts(c, opts); err != nil {
- return err
- }
- }
- section := "1"
- if header.Section != "" {
- section = header.Section
- }
-
- separator := "_"
- if opts.CommandSeparator != "" {
- separator = opts.CommandSeparator
- }
- basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
- filename := filepath.Join(opts.Path, basename+"."+section)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- headerCopy := *header
- return GenMan(cmd, &headerCopy, f)
-}
-
-// GenManTreeOptions is the options for generating the man pages.
-// Used only in GenManTreeFromOpts.
-type GenManTreeOptions struct {
- Header *GenManHeader
- Path string
- CommandSeparator string
-}
-
-// GenManHeader is a lot like the .TH header at the start of man pages. These
-// include the title, section, date, source, and manual. We will use the
-// current time if Date is unset and will use "Auto generated by spf13/cobra"
-// if the Source is unset.
-type GenManHeader struct {
- Title string
- Section string
- Date *time.Time
- date string
- Source string
- Manual string
-}
-
-// GenMan will generate a man page for the given command and write it to
-// w. The header argument may be nil, however obviously w may not.
-func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
- if header == nil {
- header = &GenManHeader{}
- }
- if err := fillHeader(header, cmd.CommandPath()); err != nil {
- return err
- }
-
- b := genMan(cmd, header)
- _, err := w.Write(md2man.Render(b))
- return err
-}
-
-func fillHeader(header *GenManHeader, name string) error {
- if header.Title == "" {
- header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
- }
- if header.Section == "" {
- header.Section = "1"
- }
- if header.Date == nil {
- now := time.Now()
- if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {
- unixEpoch, err := strconv.ParseInt(epoch, 10, 64)
- if err != nil {
- return fmt.Errorf("invalid SOURCE_DATE_EPOCH: %v", err)
- }
- now = time.Unix(unixEpoch, 0)
- }
- header.Date = &now
- }
- header.date = (*header.Date).Format("Jan 2006")
- if header.Source == "" {
- header.Source = "Auto generated by spf13/cobra"
- }
- return nil
-}
-
-func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
- description := cmd.Long
- if len(description) == 0 {
- description = cmd.Short
- }
-
- buf.WriteString(fmt.Sprintf(`%% %s(%s)%s
-%% %s
-%% %s
-# NAME
-`, header.Title, header.Section, header.date, header.Source, header.Manual))
- buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))
- buf.WriteString("# SYNOPSIS\n")
- buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine()))
- buf.WriteString("# DESCRIPTION\n")
- buf.WriteString(description + "\n\n")
-}
-
-func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {
- flags.VisitAll(func(flag *pflag.Flag) {
- if len(flag.Deprecated) > 0 || flag.Hidden {
- return
- }
- format := ""
- if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
- format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)
- } else {
- format = fmt.Sprintf("**--%s**", flag.Name)
- }
- if len(flag.NoOptDefVal) > 0 {
- format += "["
- }
- if flag.Value.Type() == "string" {
- // put quotes on the value
- format += "=%q"
- } else {
- format += "=%s"
- }
- if len(flag.NoOptDefVal) > 0 {
- format += "]"
- }
- format += "\n\t%s\n\n"
- buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage))
- })
-}
-
-func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
- flags := command.NonInheritedFlags()
- if flags.HasAvailableFlags() {
- buf.WriteString("# OPTIONS\n")
- manPrintFlags(buf, flags)
- buf.WriteString("\n")
- }
- flags = command.InheritedFlags()
- if flags.HasAvailableFlags() {
- buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")
- manPrintFlags(buf, flags)
- buf.WriteString("\n")
- }
-}
-
-func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- // something like `rootcmd-subcmd1-subcmd2`
- dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
-
- buf := new(bytes.Buffer)
-
- manPreamble(buf, header, cmd, dashCommandName)
- manPrintOptions(buf, cmd)
- if len(cmd.Example) > 0 {
- buf.WriteString("# EXAMPLE\n")
- buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))
- }
- if hasSeeAlso(cmd) {
- buf.WriteString("# SEE ALSO\n")
- seealsos := make([]string, 0)
- if cmd.HasParent() {
- parentPath := cmd.Parent().CommandPath()
- dashParentPath := strings.Replace(parentPath, " ", "-", -1)
- seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
- seealsos = append(seealsos, seealso)
- cmd.VisitParents(func(c *cobra.Command) {
- if c.DisableAutoGenTag {
- cmd.DisableAutoGenTag = c.DisableAutoGenTag
- }
- })
- }
- children := cmd.Commands()
- sort.Sort(byName(children))
- for _, c := range children {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
- seealsos = append(seealsos, seealso)
- }
- buf.WriteString(strings.Join(seealsos, ", ") + "\n")
- }
- if !cmd.DisableAutoGenTag {
- buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006")))
- }
- return buf.Bytes()
-}
diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.md b/vendor/github.com/spf13/cobra/doc/man_docs.md
deleted file mode 100644
index 3709160f..00000000
--- a/vendor/github.com/spf13/cobra/doc/man_docs.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Generating Man Pages For Your Own cobra.Command
-
-Generating man pages from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- header := &doc.GenManHeader{
- Title: "MINE",
- Section: "3",
- }
- err := doc.GenManTree(cmd, header, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a man page `/tmp/test.3`
diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.go b/vendor/github.com/spf13/cobra/doc/md_docs.go
deleted file mode 100644
index d76f6d5e..00000000
--- a/vendor/github.com/spf13/cobra/doc/md_docs.go
+++ /dev/null
@@ -1,159 +0,0 @@
-//Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package doc
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/spf13/cobra"
-)
-
-func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
- flags := cmd.NonInheritedFlags()
- flags.SetOutput(buf)
- if flags.HasAvailableFlags() {
- buf.WriteString("### Options\n\n```\n")
- flags.PrintDefaults()
- buf.WriteString("```\n\n")
- }
-
- parentFlags := cmd.InheritedFlags()
- parentFlags.SetOutput(buf)
- if parentFlags.HasAvailableFlags() {
- buf.WriteString("### Options inherited from parent commands\n\n```\n")
- parentFlags.PrintDefaults()
- buf.WriteString("```\n\n")
- }
- return nil
-}
-
-// GenMarkdown creates markdown output.
-func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
- return GenMarkdownCustom(cmd, w, func(s string) string { return s })
-}
-
-// GenMarkdownCustom creates custom markdown output.
-func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- buf := new(bytes.Buffer)
- name := cmd.CommandPath()
-
- short := cmd.Short
- long := cmd.Long
- if len(long) == 0 {
- long = short
- }
-
- buf.WriteString("## " + name + "\n\n")
- buf.WriteString(short + "\n\n")
- buf.WriteString("### Synopsis\n\n")
- buf.WriteString(long + "\n\n")
-
- if cmd.Runnable() {
- buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
- }
-
- if len(cmd.Example) > 0 {
- buf.WriteString("### Examples\n\n")
- buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
- }
-
- if err := printOptions(buf, cmd, name); err != nil {
- return err
- }
- if hasSeeAlso(cmd) {
- buf.WriteString("### SEE ALSO\n\n")
- if cmd.HasParent() {
- parent := cmd.Parent()
- pname := parent.CommandPath()
- link := pname + ".md"
- link = strings.Replace(link, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
- cmd.VisitParents(func(c *cobra.Command) {
- if c.DisableAutoGenTag {
- cmd.DisableAutoGenTag = c.DisableAutoGenTag
- }
- })
- }
-
- children := cmd.Commands()
- sort.Sort(byName(children))
-
- for _, child := range children {
- if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
- continue
- }
- cname := name + " " + child.Name()
- link := cname + ".md"
- link = strings.Replace(link, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
- }
- buf.WriteString("\n")
- }
- if !cmd.DisableAutoGenTag {
- buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
- }
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenMarkdownTree will generate a markdown page for this command and all
-// descendants in the directory given. The header may be nil.
-// This function may not work correctly if your command names have `-` in them.
-// If you have `cmd` with two subcmds, `sub` and `sub-third`,
-// and `sub` has a subcommand called `third`, it is undefined which
-// help output will be in the file `cmd-sub-third.1`.
-func GenMarkdownTree(cmd *cobra.Command, dir string) error {
- identity := func(s string) string { return s }
- emptyStr := func(s string) string { return "" }
- return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
-}
-
-// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
-// with custom filePrepender and linkHandler.
-func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
- return err
- }
- }
-
- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
- filename := filepath.Join(dir, basename)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
- return err
- }
- if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.md b/vendor/github.com/spf13/cobra/doc/md_docs.md
deleted file mode 100644
index 56ce9fe8..00000000
--- a/vendor/github.com/spf13/cobra/doc/md_docs.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Generating Markdown Docs For Your Own cobra.Command
-
-Generating man pages from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- err := doc.GenMarkdownTree(cmd, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a Markdown document `/tmp/test.md`
-
-## Generate markdown docs for the entire command tree
-
-This program can actually generate docs for the kubectl command in the kubernetes project
-
-```go
-package main
-
-import (
- "log"
- "io/ioutil"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- err := doc.GenMarkdownTree(kubectl, "./")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
-
-## Generate markdown docs for a single command
-
-You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`
-
-```go
- out := new(bytes.Buffer)
- err := doc.GenMarkdown(cmd, out)
- if err != nil {
- log.Fatal(err)
- }
-```
-
-This will write the markdown doc for ONLY "cmd" into the out, buffer.
-
-## Customize the output
-
-Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:
-
-```go
-func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
- //...
-}
-```
-
-```go
-func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
- //...
-}
-```
-
-The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
-
-```go
-const fmTemplate = `---
-date: %s
-title: "%s"
-slug: %s
-url: %s
----
-`
-
-filePrepender := func(filename string) string {
- now := time.Now().Format(time.RFC3339)
- name := filepath.Base(filename)
- base := strings.TrimSuffix(name, path.Ext(name))
- url := "/commands/" + strings.ToLower(base) + "/"
- return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
-}
-```
-
-The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
-
-```go
-linkHandler := func(name string) string {
- base := strings.TrimSuffix(name, path.Ext(name))
- return "/commands/" + strings.ToLower(base) + "/"
-}
-```
diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.go b/vendor/github.com/spf13/cobra/doc/rest_docs.go
deleted file mode 100644
index 051d8dc8..00000000
--- a/vendor/github.com/spf13/cobra/doc/rest_docs.go
+++ /dev/null
@@ -1,185 +0,0 @@
-//Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package doc
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/spf13/cobra"
-)
-
-func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
- flags := cmd.NonInheritedFlags()
- flags.SetOutput(buf)
- if flags.HasAvailableFlags() {
- buf.WriteString("Options\n")
- buf.WriteString("~~~~~~~\n\n::\n\n")
- flags.PrintDefaults()
- buf.WriteString("\n")
- }
-
- parentFlags := cmd.InheritedFlags()
- parentFlags.SetOutput(buf)
- if parentFlags.HasAvailableFlags() {
- buf.WriteString("Options inherited from parent commands\n")
- buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")
- parentFlags.PrintDefaults()
- buf.WriteString("\n")
- }
- return nil
-}
-
-// linkHandler for default ReST hyperlink markup
-func defaultLinkHandler(name, ref string) string {
- return fmt.Sprintf("`%s <%s.rst>`_", name, ref)
-}
-
-// GenReST creates reStructured Text output.
-func GenReST(cmd *cobra.Command, w io.Writer) error {
- return GenReSTCustom(cmd, w, defaultLinkHandler)
-}
-
-// GenReSTCustom creates custom reStructured Text output.
-func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- buf := new(bytes.Buffer)
- name := cmd.CommandPath()
-
- short := cmd.Short
- long := cmd.Long
- if len(long) == 0 {
- long = short
- }
- ref := strings.Replace(name, " ", "_", -1)
-
- buf.WriteString(".. _" + ref + ":\n\n")
- buf.WriteString(name + "\n")
- buf.WriteString(strings.Repeat("-", len(name)) + "\n\n")
- buf.WriteString(short + "\n\n")
- buf.WriteString("Synopsis\n")
- buf.WriteString("~~~~~~~~\n\n")
- buf.WriteString("\n" + long + "\n\n")
-
- if cmd.Runnable() {
- buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine()))
- }
-
- if len(cmd.Example) > 0 {
- buf.WriteString("Examples\n")
- buf.WriteString("~~~~~~~~\n\n")
- buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " ")))
- }
-
- if err := printOptionsReST(buf, cmd, name); err != nil {
- return err
- }
- if hasSeeAlso(cmd) {
- buf.WriteString("SEE ALSO\n")
- buf.WriteString("~~~~~~~~\n\n")
- if cmd.HasParent() {
- parent := cmd.Parent()
- pname := parent.CommandPath()
- ref = strings.Replace(pname, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short))
- cmd.VisitParents(func(c *cobra.Command) {
- if c.DisableAutoGenTag {
- cmd.DisableAutoGenTag = c.DisableAutoGenTag
- }
- })
- }
-
- children := cmd.Commands()
- sort.Sort(byName(children))
-
- for _, child := range children {
- if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
- continue
- }
- cname := name + " " + child.Name()
- ref = strings.Replace(cname, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short))
- }
- buf.WriteString("\n")
- }
- if !cmd.DisableAutoGenTag {
- buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n")
- }
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenReSTTree will generate a ReST page for this command and all
-// descendants in the directory given.
-// This function may not work correctly if your command names have `-` in them.
-// If you have `cmd` with two subcmds, `sub` and `sub-third`,
-// and `sub` has a subcommand called `third`, it is undefined which
-// help output will be in the file `cmd-sub-third.1`.
-func GenReSTTree(cmd *cobra.Command, dir string) error {
- emptyStr := func(s string) string { return "" }
- return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
-}
-
-// GenReSTTreeCustom is the the same as GenReSTTree, but
-// with custom filePrepender and linkHandler.
-func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
- return err
- }
- }
-
- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst"
- filename := filepath.Join(dir, basename)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
- return err
- }
- if err := GenReSTCustom(cmd, f, linkHandler); err != nil {
- return err
- }
- return nil
-}
-
-// adapted from: https://github.com/kr/text/blob/main/indent.go
-func indentString(s, p string) string {
- var res []byte
- b := []byte(s)
- prefix := []byte(p)
- bol := true
- for _, c := range b {
- if bol && c != '\n' {
- res = append(res, prefix...)
- }
- res = append(res, c)
- bol = c == '\n'
- }
- return string(res)
-}
diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.md b/vendor/github.com/spf13/cobra/doc/rest_docs.md
deleted file mode 100644
index 6098430e..00000000
--- a/vendor/github.com/spf13/cobra/doc/rest_docs.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# Generating ReStructured Text Docs For Your Own cobra.Command
-
-Generating ReST pages from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- err := doc.GenReSTTree(cmd, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a ReST document `/tmp/test.rst`
-
-## Generate ReST docs for the entire command tree
-
-This program can actually generate docs for the kubectl command in the kubernetes project
-
-```go
-package main
-
-import (
- "log"
- "io/ioutil"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- err := doc.GenReSTTree(kubectl, "./")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
-
-## Generate ReST docs for a single command
-
-You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree`
-
-```go
- out := new(bytes.Buffer)
- err := doc.GenReST(cmd, out)
- if err != nil {
- log.Fatal(err)
- }
-```
-
-This will write the ReST doc for ONLY "cmd" into the out, buffer.
-
-## Customize the output
-
-Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:
-
-```go
-func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
- //...
-}
-```
-
-```go
-func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
- //...
-}
-```
-
-The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
-
-```go
-const fmTemplate = `---
-date: %s
-title: "%s"
-slug: %s
-url: %s
----
-`
-filePrepender := func(filename string) string {
- now := time.Now().Format(time.RFC3339)
- name := filepath.Base(filename)
- base := strings.TrimSuffix(name, path.Ext(name))
- url := "/commands/" + strings.ToLower(base) + "/"
- return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
-}
-```
-
-The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:
-
-```go
-// Sphinx cross-referencing format
-linkHandler := func(name, ref string) string {
- return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
-}
-```
diff --git a/vendor/github.com/spf13/cobra/doc/util.go b/vendor/github.com/spf13/cobra/doc/util.go
deleted file mode 100644
index 8d3dbece..00000000
--- a/vendor/github.com/spf13/cobra/doc/util.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package doc
-
-import (
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-// Test to see if we have a reason to print See Also information in docs
-// Basically this is a test for a parent commend or a subcommand which is
-// both not deprecated and not the autogenerated help command.
-func hasSeeAlso(cmd *cobra.Command) bool {
- if cmd.HasParent() {
- return true
- }
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- return true
- }
- return false
-}
-
-// Temporary workaround for yaml lib generating incorrect yaml with long strings
-// that do not contain \n.
-func forceMultiLine(s string) string {
- if len(s) > 60 && !strings.Contains(s, "\n") {
- s = s + "\n"
- }
- return s
-}
-
-type byName []*cobra.Command
-
-func (s byName) Len() int { return len(s) }
-func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.go b/vendor/github.com/spf13/cobra/doc/yaml_docs.go
deleted file mode 100644
index ea00af07..00000000
--- a/vendor/github.com/spf13/cobra/doc/yaml_docs.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright 2016 French Ben. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package doc
-
-import (
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
- "gopkg.in/yaml.v2"
-)
-
-type cmdOption struct {
- Name string
- Shorthand string `yaml:",omitempty"`
- DefaultValue string `yaml:"default_value,omitempty"`
- Usage string `yaml:",omitempty"`
-}
-
-type cmdDoc struct {
- Name string
- Synopsis string `yaml:",omitempty"`
- Description string `yaml:",omitempty"`
- Options []cmdOption `yaml:",omitempty"`
- InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"`
- Example string `yaml:",omitempty"`
- SeeAlso []string `yaml:"see_also,omitempty"`
-}
-
-// GenYamlTree creates yaml structured ref files for this command and all descendants
-// in the directory given. This function may not work
-// correctly if your command names have `-` in them. If you have `cmd` with two
-// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
-// it is undefined which help output will be in the file `cmd-sub-third.1`.
-func GenYamlTree(cmd *cobra.Command, dir string) error {
- identity := func(s string) string { return s }
- emptyStr := func(s string) string { return "" }
- return GenYamlTreeCustom(cmd, dir, emptyStr, identity)
-}
-
-// GenYamlTreeCustom creates yaml structured ref files.
-func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
- return err
- }
- }
-
- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml"
- filename := filepath.Join(dir, basename)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
- return err
- }
- if err := GenYamlCustom(cmd, f, linkHandler); err != nil {
- return err
- }
- return nil
-}
-
-// GenYaml creates yaml output.
-func GenYaml(cmd *cobra.Command, w io.Writer) error {
- return GenYamlCustom(cmd, w, func(s string) string { return s })
-}
-
-// GenYamlCustom creates custom yaml output.
-func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- yamlDoc := cmdDoc{}
- yamlDoc.Name = cmd.CommandPath()
-
- yamlDoc.Synopsis = forceMultiLine(cmd.Short)
- yamlDoc.Description = forceMultiLine(cmd.Long)
-
- if len(cmd.Example) > 0 {
- yamlDoc.Example = cmd.Example
- }
-
- flags := cmd.NonInheritedFlags()
- if flags.HasFlags() {
- yamlDoc.Options = genFlagResult(flags)
- }
- flags = cmd.InheritedFlags()
- if flags.HasFlags() {
- yamlDoc.InheritedOptions = genFlagResult(flags)
- }
-
- if hasSeeAlso(cmd) {
- result := []string{}
- if cmd.HasParent() {
- parent := cmd.Parent()
- result = append(result, parent.CommandPath()+" - "+parent.Short)
- }
- children := cmd.Commands()
- sort.Sort(byName(children))
- for _, child := range children {
- if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
- continue
- }
- result = append(result, child.Name()+" - "+child.Short)
- }
- yamlDoc.SeeAlso = result
- }
-
- final, err := yaml.Marshal(&yamlDoc)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-
- if _, err := w.Write(final); err != nil {
- return err
- }
- return nil
-}
-
-func genFlagResult(flags *pflag.FlagSet) []cmdOption {
- var result []cmdOption
-
- flags.VisitAll(func(flag *pflag.Flag) {
- // Todo, when we mark a shorthand is deprecated, but specify an empty message.
- // The flag.ShorthandDeprecated is empty as the shorthand is deprecated.
- // Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok.
- if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 {
- opt := cmdOption{
- flag.Name,
- flag.Shorthand,
- flag.DefValue,
- forceMultiLine(flag.Usage),
- }
- result = append(result, opt)
- } else {
- opt := cmdOption{
- Name: flag.Name,
- DefaultValue: forceMultiLine(flag.DefValue),
- Usage: forceMultiLine(flag.Usage),
- }
- result = append(result, opt)
- }
- })
-
- return result
-}
diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.md b/vendor/github.com/spf13/cobra/doc/yaml_docs.md
deleted file mode 100644
index 1a9b7c6a..00000000
--- a/vendor/github.com/spf13/cobra/doc/yaml_docs.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Generating Yaml Docs For Your Own cobra.Command
-
-Generating yaml files from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- err := doc.GenYamlTree(cmd, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a Yaml document `/tmp/test.yaml`
-
-## Generate yaml docs for the entire command tree
-
-This program can actually generate docs for the kubectl command in the kubernetes project
-
-```go
-package main
-
-import (
- "io/ioutil"
- "log"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- err := doc.GenYamlTree(kubectl, "./")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
-
-## Generate yaml docs for a single command
-
-You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`
-
-```go
- out := new(bytes.Buffer)
- doc.GenYaml(cmd, out)
-```
-
-This will write the yaml doc for ONLY "cmd" into the out, buffer.
-
-## Customize the output
-
-Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:
-
-```go
-func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
- //...
-}
-```
-
-```go
-func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
- //...
-}
-```
-
-The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
-
-```go
-const fmTemplate = `---
-date: %s
-title: "%s"
-slug: %s
-url: %s
----
-`
-
-filePrepender := func(filename string) string {
- now := time.Now().Format(time.RFC3339)
- name := filepath.Base(filename)
- base := strings.TrimSuffix(name, path.Ext(name))
- url := "/commands/" + strings.ToLower(base) + "/"
- return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
-}
-```
-
-The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
-
-```go
-linkHandler := func(name string) string {
- base := strings.TrimSuffix(name, path.Ext(name))
- return "/commands/" + strings.ToLower(base) + "/"
-}
-```
diff --git a/vendor/github.com/spf13/cobra/go.mod b/vendor/github.com/spf13/cobra/go.mod
deleted file mode 100644
index 9a9eb65a..00000000
--- a/vendor/github.com/spf13/cobra/go.mod
+++ /dev/null
@@ -1,13 +0,0 @@
-module github.com/spf13/cobra
-
-go 1.12
-
-require (
- github.com/BurntSushi/toml v0.3.1 // indirect
- github.com/cpuguy83/go-md2man v1.0.10
- github.com/inconshreveable/mousetrap v1.0.0
- github.com/mitchellh/go-homedir v1.1.0
- github.com/spf13/pflag v1.0.3
- github.com/spf13/viper v1.3.2
- gopkg.in/yaml.v2 v2.2.2
-)
diff --git a/vendor/github.com/spf13/cobra/go.sum b/vendor/github.com/spf13/cobra/go.sum
deleted file mode 100644
index 9761f4d0..00000000
--- a/vendor/github.com/spf13/cobra/go.sum
+++ /dev/null
@@ -1,51 +0,0 @@
-github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
-github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
-github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
-github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
-github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
-github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
-github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk=
-github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
-github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
-github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
-github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
-github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
-github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
-github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
-github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
-github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
-github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
-github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
-github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
-github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
-github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo=
-github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
-github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
-github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
-github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
-github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
-github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
-github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
-github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
-github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
-github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=
-github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
-github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
-github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
-github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
-github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
-golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
-golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A=
-golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
-gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go
deleted file mode 100644
index 756c61b9..00000000
--- a/vendor/github.com/spf13/cobra/powershell_completions.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// PowerShell completions are based on the amazing work from clap:
-// https://github.com/clap-rs/clap/blob/3294d18efe5f264d12c9035f404c7d189d4824e1/src/completions/powershell.rs
-//
-// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
-// can be downloaded separately for windows 7 or 8.1).
-
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "strings"
-
- "github.com/spf13/pflag"
-)
-
-var powerShellCompletionTemplate = `using namespace System.Management.Automation
-using namespace System.Management.Automation.Language
-Register-ArgumentCompleter -Native -CommandName '%s' -ScriptBlock {
- param($wordToComplete, $commandAst, $cursorPosition)
- $commandElements = $commandAst.CommandElements
- $command = @(
- '%s'
- for ($i = 1; $i -lt $commandElements.Count; $i++) {
- $element = $commandElements[$i]
- if ($element -isnot [StringConstantExpressionAst] -or
- $element.StringConstantType -ne [StringConstantType]::BareWord -or
- $element.Value.StartsWith('-')) {
- break
- }
- $element.Value
- }
- ) -join ';'
- $completions = @(switch ($command) {%s
- })
- $completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
- Sort-Object -Property ListItemText
-}`
-
-func generatePowerShellSubcommandCases(out io.Writer, cmd *Command, previousCommandName string) {
- var cmdName string
- if previousCommandName == "" {
- cmdName = cmd.Name()
- } else {
- cmdName = fmt.Sprintf("%s;%s", previousCommandName, cmd.Name())
- }
-
- fmt.Fprintf(out, "\n '%s' {", cmdName)
-
- cmd.Flags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- usage := escapeStringForPowerShell(flag.Usage)
- if len(flag.Shorthand) > 0 {
- fmt.Fprintf(out, "\n [CompletionResult]::new('-%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Shorthand, flag.Shorthand, usage)
- }
- fmt.Fprintf(out, "\n [CompletionResult]::new('--%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Name, flag.Name, usage)
- })
-
- for _, subCmd := range cmd.Commands() {
- usage := escapeStringForPowerShell(subCmd.Short)
- fmt.Fprintf(out, "\n [CompletionResult]::new('%s', '%s', [CompletionResultType]::ParameterValue, '%s')", subCmd.Name(), subCmd.Name(), usage)
- }
-
- fmt.Fprint(out, "\n break\n }")
-
- for _, subCmd := range cmd.Commands() {
- generatePowerShellSubcommandCases(out, subCmd, cmdName)
- }
-}
-
-func escapeStringForPowerShell(s string) string {
- return strings.Replace(s, "'", "''", -1)
-}
-
-// GenPowerShellCompletion generates PowerShell completion file and writes to the passed writer.
-func (c *Command) GenPowerShellCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
-
- var subCommandCases bytes.Buffer
- generatePowerShellSubcommandCases(&subCommandCases, c, "")
- fmt.Fprintf(buf, powerShellCompletionTemplate, c.Name(), c.Name(), subCommandCases.String())
-
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenPowerShellCompletionFile generates PowerShell completion file.
-func (c *Command) GenPowerShellCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenPowerShellCompletion(outFile)
-}
diff --git a/vendor/github.com/spf13/cobra/powershell_completions.md b/vendor/github.com/spf13/cobra/powershell_completions.md
deleted file mode 100644
index afed8024..00000000
--- a/vendor/github.com/spf13/cobra/powershell_completions.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Generating PowerShell Completions For Your Own cobra.Command
-
-Cobra can generate PowerShell completion scripts. Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
-
-# What's supported
-
-- Completion for subcommands using their `.Short` description
-- Completion for non-hidden flags using their `.Name` and `.Shorthand`
-
-# What's not yet supported
-
-- Command aliases
-- Required, filename or custom flags (they will work like normal flags)
-- Custom completion scripts
diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go
deleted file mode 100644
index ba0af9cb..00000000
--- a/vendor/github.com/spf13/cobra/shell_completions.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package cobra
-
-import (
- "github.com/spf13/pflag"
-)
-
-// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,
-// and causes your command to report an error if invoked without the flag.
-func (c *Command) MarkFlagRequired(name string) error {
- return MarkFlagRequired(c.Flags(), name)
-}
-
-// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists,
-// and causes your command to report an error if invoked without the flag.
-func (c *Command) MarkPersistentFlagRequired(name string) error {
- return MarkFlagRequired(c.PersistentFlags(), name)
-}
-
-// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,
-// and causes your command to report an error if invoked without the flag.
-func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
- return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
-}
-
-// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
-// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
-func (c *Command) MarkFlagFilename(name string, extensions ...string) error {
- return MarkFlagFilename(c.Flags(), name, extensions...)
-}
-
-// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
-// Generated bash autocompletion will call the bash function f for the flag.
-func (c *Command) MarkFlagCustom(name string, f string) error {
- return MarkFlagCustom(c.Flags(), name, f)
-}
-
-// MarkPersistentFlagFilename instructs the various shell completion
-// implementations to limit completions for this persistent flag to the
-// specified extensions (patterns).
-//
-// Shell Completion compatibility matrix: bash, zsh
-func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
- return MarkFlagFilename(c.PersistentFlags(), name, extensions...)
-}
-
-// MarkFlagFilename instructs the various shell completion implementations to
-// limit completions for this flag to the specified extensions (patterns).
-//
-// Shell Completion compatibility matrix: bash, zsh
-func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
- return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
-}
-
-// MarkFlagCustom instructs the various shell completion implementations to
-// limit completions for this flag to the specified extensions (patterns).
-//
-// Shell Completion compatibility matrix: bash, zsh
-func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
- return flags.SetAnnotation(name, BashCompCustom, []string{f})
-}
-
-// MarkFlagDirname instructs the various shell completion implementations to
-// complete only directories with this named flag.
-//
-// Shell Completion compatibility matrix: zsh
-func (c *Command) MarkFlagDirname(name string) error {
- return MarkFlagDirname(c.Flags(), name)
-}
-
-// MarkPersistentFlagDirname instructs the various shell completion
-// implementations to complete only directories with this persistent named flag.
-//
-// Shell Completion compatibility matrix: zsh
-func (c *Command) MarkPersistentFlagDirname(name string) error {
- return MarkFlagDirname(c.PersistentFlags(), name)
-}
-
-// MarkFlagDirname instructs the various shell completion implementations to
-// complete only directories with this specified flag.
-//
-// Shell Completion compatibility matrix: zsh
-func MarkFlagDirname(flags *pflag.FlagSet, name string) error {
- zshPattern := "-(/)"
- return flags.SetAnnotation(name, zshCompDirname, []string{zshPattern})
-}
diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go
deleted file mode 100644
index 12755482..00000000
--- a/vendor/github.com/spf13/cobra/zsh_completions.go
+++ /dev/null
@@ -1,336 +0,0 @@
-package cobra
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
- "text/template"
-
- "github.com/spf13/pflag"
-)
-
-const (
- zshCompArgumentAnnotation = "cobra_annotations_zsh_completion_argument_annotation"
- zshCompArgumentFilenameComp = "cobra_annotations_zsh_completion_argument_file_completion"
- zshCompArgumentWordComp = "cobra_annotations_zsh_completion_argument_word_completion"
- zshCompDirname = "cobra_annotations_zsh_dirname"
-)
-
-var (
- zshCompFuncMap = template.FuncMap{
- "genZshFuncName": zshCompGenFuncName,
- "extractFlags": zshCompExtractFlag,
- "genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,
- "extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,
- }
- zshCompletionText = `
-{{/* should accept Command (that contains subcommands) as parameter */}}
-{{define "argumentsC" -}}
-{{ $cmdPath := genZshFuncName .}}
-function {{$cmdPath}} {
- local -a commands
-
- _arguments -C \{{- range extractFlags .}}
- {{genFlagEntryForZshArguments .}} \{{- end}}
- "1: :->cmnds" \
- "*::arg:->args"
-
- case $state in
- cmnds)
- commands=({{range .Commands}}{{if not .Hidden}}
- "{{.Name}}:{{.Short}}"{{end}}{{end}}
- )
- _describe "command" commands
- ;;
- esac
-
- case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}
- {{.Name}})
- {{$cmdPath}}_{{.Name}}
- ;;{{end}}{{end}}
- esac
-}
-{{range .Commands}}{{if not .Hidden}}
-{{template "selectCmdTemplate" .}}
-{{- end}}{{end}}
-{{- end}}
-
-{{/* should accept Command without subcommands as parameter */}}
-{{define "arguments" -}}
-function {{genZshFuncName .}} {
-{{" _arguments"}}{{range extractFlags .}} \
- {{genFlagEntryForZshArguments . -}}
-{{end}}{{range extractArgsCompletions .}} \
- {{.}}{{end}}
-}
-{{end}}
-
-{{/* dispatcher for commands with or without subcommands */}}
-{{define "selectCmdTemplate" -}}
-{{if .Hidden}}{{/* ignore hidden*/}}{{else -}}
-{{if .Commands}}{{template "argumentsC" .}}{{else}}{{template "arguments" .}}{{end}}
-{{- end}}
-{{- end}}
-
-{{/* template entry point */}}
-{{define "Main" -}}
-#compdef _{{.Name}} {{.Name}}
-
-{{template "selectCmdTemplate" .}}
-{{end}}
-`
-)
-
-// zshCompArgsAnnotation is used to encode/decode zsh completion for
-// arguments to/from Command.Annotations.
-type zshCompArgsAnnotation map[int]zshCompArgHint
-
-type zshCompArgHint struct {
- // Indicates the type of the completion to use. One of:
- // zshCompArgumentFilenameComp or zshCompArgumentWordComp
- Tipe string `json:"type"`
-
- // A value for the type above (globs for file completion or words)
- Options []string `json:"options"`
-}
-
-// GenZshCompletionFile generates zsh completion file.
-func (c *Command) GenZshCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenZshCompletion(outFile)
-}
-
-// GenZshCompletion generates a zsh completion file and writes to the passed
-// writer. The completion always run on the root command regardless of the
-// command it was called from.
-func (c *Command) GenZshCompletion(w io.Writer) error {
- tmpl, err := template.New("Main").Funcs(zshCompFuncMap).Parse(zshCompletionText)
- if err != nil {
- return fmt.Errorf("error creating zsh completion template: %v", err)
- }
- return tmpl.Execute(w, c.Root())
-}
-
-// MarkZshCompPositionalArgumentFile marks the specified argument (first
-// argument is 1) as completed by file selection. patterns (e.g. "*.txt") are
-// optional - if not provided the completion will search for all files.
-func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
- if argPosition < 1 {
- return fmt.Errorf("Invalid argument position (%d)", argPosition)
- }
- annotation, err := c.zshCompGetArgsAnnotations()
- if err != nil {
- return err
- }
- if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
- return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
- }
- annotation[argPosition] = zshCompArgHint{
- Tipe: zshCompArgumentFilenameComp,
- Options: patterns,
- }
- return c.zshCompSetArgsAnnotations(annotation)
-}
-
-// MarkZshCompPositionalArgumentWords marks the specified positional argument
-// (first argument is 1) as completed by the provided words. At east one word
-// must be provided, spaces within words will be offered completion with
-// "word\ word".
-func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
- if argPosition < 1 {
- return fmt.Errorf("Invalid argument position (%d)", argPosition)
- }
- if len(words) == 0 {
- return fmt.Errorf("Trying to set empty word list for positional argument %d", argPosition)
- }
- annotation, err := c.zshCompGetArgsAnnotations()
- if err != nil {
- return err
- }
- if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
- return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
- }
- annotation[argPosition] = zshCompArgHint{
- Tipe: zshCompArgumentWordComp,
- Options: words,
- }
- return c.zshCompSetArgsAnnotations(annotation)
-}
-
-func zshCompExtractArgumentCompletionHintsForRendering(c *Command) ([]string, error) {
- var result []string
- annotation, err := c.zshCompGetArgsAnnotations()
- if err != nil {
- return nil, err
- }
- for k, v := range annotation {
- s, err := zshCompRenderZshCompArgHint(k, v)
- if err != nil {
- return nil, err
- }
- result = append(result, s)
- }
- if len(c.ValidArgs) > 0 {
- if _, positionOneExists := annotation[1]; !positionOneExists {
- s, err := zshCompRenderZshCompArgHint(1, zshCompArgHint{
- Tipe: zshCompArgumentWordComp,
- Options: c.ValidArgs,
- })
- if err != nil {
- return nil, err
- }
- result = append(result, s)
- }
- }
- sort.Strings(result)
- return result, nil
-}
-
-func zshCompRenderZshCompArgHint(i int, z zshCompArgHint) (string, error) {
- switch t := z.Tipe; t {
- case zshCompArgumentFilenameComp:
- var globs []string
- for _, g := range z.Options {
- globs = append(globs, fmt.Sprintf(`-g "%s"`, g))
- }
- return fmt.Sprintf(`'%d: :_files %s'`, i, strings.Join(globs, " ")), nil
- case zshCompArgumentWordComp:
- var words []string
- for _, w := range z.Options {
- words = append(words, fmt.Sprintf("%q", w))
- }
- return fmt.Sprintf(`'%d: :(%s)'`, i, strings.Join(words, " ")), nil
- default:
- return "", fmt.Errorf("Invalid zsh argument completion annotation: %s", t)
- }
-}
-
-func (c *Command) zshcompArgsAnnotationnIsDuplicatePosition(annotation zshCompArgsAnnotation, position int) bool {
- _, dup := annotation[position]
- return dup
-}
-
-func (c *Command) zshCompGetArgsAnnotations() (zshCompArgsAnnotation, error) {
- annotation := make(zshCompArgsAnnotation)
- annotationString, ok := c.Annotations[zshCompArgumentAnnotation]
- if !ok {
- return annotation, nil
- }
- err := json.Unmarshal([]byte(annotationString), &annotation)
- if err != nil {
- return annotation, fmt.Errorf("Error unmarshaling zsh argument annotation: %v", err)
- }
- return annotation, nil
-}
-
-func (c *Command) zshCompSetArgsAnnotations(annotation zshCompArgsAnnotation) error {
- jsn, err := json.Marshal(annotation)
- if err != nil {
- return fmt.Errorf("Error marshaling zsh argument annotation: %v", err)
- }
- if c.Annotations == nil {
- c.Annotations = make(map[string]string)
- }
- c.Annotations[zshCompArgumentAnnotation] = string(jsn)
- return nil
-}
-
-func zshCompGenFuncName(c *Command) string {
- if c.HasParent() {
- return zshCompGenFuncName(c.Parent()) + "_" + c.Name()
- }
- return "_" + c.Name()
-}
-
-func zshCompExtractFlag(c *Command) []*pflag.Flag {
- var flags []*pflag.Flag
- c.LocalFlags().VisitAll(func(f *pflag.Flag) {
- if !f.Hidden {
- flags = append(flags, f)
- }
- })
- c.InheritedFlags().VisitAll(func(f *pflag.Flag) {
- if !f.Hidden {
- flags = append(flags, f)
- }
- })
- return flags
-}
-
-// zshCompGenFlagEntryForArguments returns an entry that matches _arguments
-// zsh-completion parameters. It's too complicated to generate in a template.
-func zshCompGenFlagEntryForArguments(f *pflag.Flag) string {
- if f.Name == "" || f.Shorthand == "" {
- return zshCompGenFlagEntryForSingleOptionFlag(f)
- }
- return zshCompGenFlagEntryForMultiOptionFlag(f)
-}
-
-func zshCompGenFlagEntryForSingleOptionFlag(f *pflag.Flag) string {
- var option, multiMark, extras string
-
- if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
- multiMark = "*"
- }
-
- option = "--" + f.Name
- if option == "--" {
- option = "-" + f.Shorthand
- }
- extras = zshCompGenFlagEntryExtras(f)
-
- return fmt.Sprintf(`'%s%s[%s]%s'`, multiMark, option, zshCompQuoteFlagDescription(f.Usage), extras)
-}
-
-func zshCompGenFlagEntryForMultiOptionFlag(f *pflag.Flag) string {
- var options, parenMultiMark, curlyMultiMark, extras string
-
- if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
- parenMultiMark = "*"
- curlyMultiMark = "\\*"
- }
-
- options = fmt.Sprintf(`'(%s-%s %s--%s)'{%s-%s,%s--%s}`,
- parenMultiMark, f.Shorthand, parenMultiMark, f.Name, curlyMultiMark, f.Shorthand, curlyMultiMark, f.Name)
- extras = zshCompGenFlagEntryExtras(f)
-
- return fmt.Sprintf(`%s'[%s]%s'`, options, zshCompQuoteFlagDescription(f.Usage), extras)
-}
-
-func zshCompGenFlagEntryExtras(f *pflag.Flag) string {
- if f.NoOptDefVal != "" {
- return ""
- }
-
- extras := ":" // allow options for flag (even without assistance)
- for key, values := range f.Annotations {
- switch key {
- case zshCompDirname:
- extras = fmt.Sprintf(":filename:_files -g %q", values[0])
- case BashCompFilenameExt:
- extras = ":filename:_files"
- for _, pattern := range values {
- extras = extras + fmt.Sprintf(` -g "%s"`, pattern)
- }
- }
- }
-
- return extras
-}
-
-func zshCompFlagCouldBeSpecifiedMoreThenOnce(f *pflag.Flag) bool {
- return strings.Contains(f.Value.Type(), "Slice") ||
- strings.Contains(f.Value.Type(), "Array")
-}
-
-func zshCompQuoteFlagDescription(s string) string {
- return strings.Replace(s, "'", `'\''`, -1)
-}
diff --git a/vendor/github.com/spf13/cobra/zsh_completions.md b/vendor/github.com/spf13/cobra/zsh_completions.md
deleted file mode 100644
index df9c2eac..00000000
--- a/vendor/github.com/spf13/cobra/zsh_completions.md
+++ /dev/null
@@ -1,39 +0,0 @@
-## Generating Zsh Completion for your cobra.Command
-
-Cobra supports native Zsh completion generated from the root `cobra.Command`.
-The generated completion script should be put somewhere in your `$fpath` named
-`_<YOUR COMMAND>`.
-
-### What's Supported
-
-* Completion for all non-hidden subcommands using their `.Short` description.
-* Completion for all non-hidden flags using the following rules:
- * Filename completion works by marking the flag with `cmd.MarkFlagFilename...`
- family of commands.
- * The requirement for argument to the flag is decided by the `.NoOptDefVal`
- flag value - if it's empty then completion will expect an argument.
- * Flags of one of the various `*Array` and `*Slice` types supports multiple
- specifications (with or without argument depending on the specific type).
-* Completion of positional arguments using the following rules:
- * Argument position for all options below starts at `1`. If argument position
- `0` is requested it will raise an error.
- * Use `command.MarkZshCompPositionalArgumentFile` to complete filenames. Glob
- patterns (e.g. `"*.log"`) are optional - if not specified it will offer to
- complete all file types.
- * Use `command.MarkZshCompPositionalArgumentWords` to offer specific words for
- completion. At least one word is required.
- * It's possible to specify completion for some arguments and leave some
- unspecified (e.g. offer words for second argument but nothing for first
- argument). This will cause no completion for first argument but words
- completion for second argument.
- * If no argument completion was specified for 1st argument (but optionally was
- specified for 2nd) and the command has `ValidArgs` it will be used as
- completion options for 1st argument.
- * Argument completions only offered for commands with no subcommands.
-
-### What's not yet Supported
-
-* Custom completion scripts are not supported yet (We should probably create zsh
- specific one, doesn't make sense to re-use the bash one as the functions will
- be different).
-* Whatever other feature you're looking for and doesn't exist :)