summaryrefslogtreecommitdiff
path: root/cmd/ponzu/vendor/github.com/spf13/cobra
diff options
context:
space:
mode:
Diffstat (limited to 'cmd/ponzu/vendor/github.com/spf13/cobra')
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/.mailmap3
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/LICENSE.txt174
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/README.md887
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/cobra.go181
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/cobra_test.go1173
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/command.go1289
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/command_notwin.go5
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/command_test.go300
-rw-r--r--cmd/ponzu/vendor/github.com/spf13/cobra/command_win.go26
9 files changed, 0 insertions, 4038 deletions
diff --git a/cmd/ponzu/vendor/github.com/spf13/cobra/.mailmap b/cmd/ponzu/vendor/github.com/spf13/cobra/.mailmap
deleted file mode 100644
index 94ec530..0000000
--- a/cmd/ponzu/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/cmd/ponzu/vendor/github.com/spf13/cobra/LICENSE.txt b/cmd/ponzu/vendor/github.com/spf13/cobra/LICENSE.txt
deleted file mode 100644
index 298f0e2..0000000
--- a/cmd/ponzu/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/cmd/ponzu/vendor/github.com/spf13/cobra/README.md b/cmd/ponzu/vendor/github.com/spf13/cobra/README.md
deleted file mode 100644
index 4563c21..0000000
--- a/cmd/ponzu/vendor/github.com/spf13/cobra/README.md
+++ /dev/null
@@ -1,887 +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 including:
-
-* [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/)
-* [GiantSwarm's swarm](https://github.com/giantswarm/cli)
-* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
-* [rclone](http://rclone.org/)
-
-
-[![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)
-
-![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)
-
-# 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 detailed help for `app help [command]`
-* 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
-
-Cobra has an exceptionally clean interface and simple design without needless
-constructors or initialization methods.
-
-Applications built with Cobra commands are designed to be as user-friendly as
-possible. Flags can be placed before or after the command (as long as a
-confusing space isn’t provided). Both short and long flags can be used. A
-command need not even be fully typed. Help is automatically generated and
-available for the application or for a specific command using either the help
-command or the `--help` flag.
-
-# 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.
-
-A Command has the following structure:
-
-```go
-type Command struct {
- Use string // The one-line usage message.
- Short string // The short description shown in the 'help' output.
- Long string // The long message shown in the 'help <this-command>' output.
- Run func(cmd *Command, args []string) // Run runs the 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.
-
-## Usage
-
-Cobra works by creating a set of commands and then organizing them into a tree.
-The tree defines the structure of the application.
-
-Once each command is defined with its corresponding flags, then the
-tree is assigned to the commander which is finally executed.
-
-# Installing
-Using Cobra is easy. First, use `go get` to install the latest version
-of the library. This command will install the `cobra` generator executible
-along with the library:
-
- go get -v 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, to initialize Cobra.
-
-```go
-package main
-
-import (
- "fmt"
- "os"
-
- "{pathToYourApp}/cmd"
-)
-
-func main() {
- if err := cmd.RootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-```
-
-## 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.
-
-In order to use the cobra command, compile it using the following command:
-
- go get github.com/spf13/cobra/cobra
-
-This will create the cobra executable under your `$GOPATH/bin` directory.
-
-### cobra init
-
-The `cobra init [yourApp]` command will create your initial application code
-for you. It is a very powerful application that will populate your program with
-the right structure so you can immediately enjoy all the benefits of Cobra. It
-will also automatically apply the license you specify to your application.
-
-Cobra init is pretty smart. You can provide it a full path, or simply a path
-similar to what is expected in the import.
-
-```
-cobra init github.com/spf13/newAppName
-```
-
-### cobra add
-
-Once an application is initialized Cobra can create additional commands for you.
-Let's say you created an app and you wanted the following commands for it:
-
-* app serve
-* app config
-* app config create
-
-In your project directory (where your main.go file is) you would run the following:
-
-```
-cobra add serve
-cobra add config
-cobra add create -p 'configCmd'
-```
-
-*Note: Use camelCase (not snake_case/snake-case) for command names.
-Otherwise, you will become unexpected errors.
-For example, `cobra add add-user` is incorrect, but `cobra add addUser` is valid.*
-
-Once you have run these three commands you would have an app structure that would look like:
-
-```
- ▾ app/
- ▾ cmd/
- serve.go
- config.go
- create.go
- main.go
-```
-
-at this point you can run `go run main.go` and it would run your app. `go run
-main.go serve`, `go run main.go config`, `go run main.go config create` along
-with `go run main.go help serve`, etc would all work.
-
-Obviously you haven't added your own code to these yet, the commands are ready
-for you to give them their tasks. Have fun.
-
-### Configuring the cobra generator
-
-The cobra generator will be easier to use if you provide a simple configuration
-file which will help you eliminate providing a bunch of repeated information in
-flags over and over.
-
-An example ~/.cobra.yaml file:
-
-```yaml
-author: Steve Francia <spf@spf13.com>
-license: MIT
-```
-
-You can specify no license by setting `license` to `none` or you can specify
-a custom license:
-
-```yaml
-license:
- header: This file is part of {{ .appName }}.
- text: |
- {{ .copyright }}
-
- This is my license. There are many like it, but this one is mine.
- My license is my best friend. It is my life. I must master it as I must
- master my life.
-```
-
-You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**,
-**AGPL**, **MIT**, **2-Clause BSD** or **3-Clause BSD**.
-
-## Manually implementing Cobra
-
-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 the root command
-
-The root command represents your binary itself.
-
-
-#### Manually 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
- },
-}
-```
-
-You will additionally define flags and handle configuration in your init() function.
-
-for example cmd/root.go:
-
-```go
-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")
-}
-```
-
-### 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 (
- "fmt"
- "os"
-
- "{pathToYourApp}/cmd"
-)
-
-func main() {
- if err := cmd.RootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-```
-
-
-### 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 (
- "github.com/spf13/cobra"
- "fmt"
-)
-
-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")
- },
-}
-```
-
-### Attach command to its parent
-
-
-If you notice in the above example we attach the command to its parent. In
-this case the parent is the rootCmd. In this example we are attaching it to the
-root, but commands can be attached at any level.
-
-```go
-RootCmd.AddCommand(versionCmd)
-```
-
-### Remove a command from its parent
-
-Removing a command is not a common action in simple programs, but it allows 3rd
-parties to customize an existing command tree.
-
-In this example, we remove the existing `VersionCmd` command of an existing
-root command, and we replace it with our own version:
-
-```go
-mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
-mainlib.RootCmd.AddCommand(versionCmd)
-```
-
-## 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
-RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
-```
-
-
-## 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.
- `,
- 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.
- `,
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Print: " + strings.Join(args, " "))
- },
- }
-
- var cmdTimes = &cobra.Command{
- Use: "times [# 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.`,
- 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/).
-
-## The 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.
-
- > hugo help
-
- hugo is the main command, used to build your Hugo site.
-
- Hugo is a Fast and Flexible Static Site Generator
- built with love by spf13 and friends in Go.
-
- Complete documentation is available at http://gohugo.io/.
-
- Usage:
- hugo [flags]
- hugo [command]
-
- Available Commands:
- server Hugo runs its own webserver to render the files
- version Print the version number of Hugo
- config Print the site configuration
- check Check content in the source directory
- benchmark Benchmark hugo by building a site a number of times.
- convert Convert your content to different formats
- new Create new content for your site
- list Listing out various types of content
- undraft Undraft changes the content's draft status from 'True' to 'False'
- genautocomplete Generate shell autocompletion script for Hugo
- gendoc Generate Markdown documentation for the Hugo CLI.
- genman Generate man page for Hugo
- import Import your site from others.
-
- Flags:
- -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
- -D, --buildDrafts[=false]: include content marked as draft
- -F, --buildFuture[=false]: include content with publishdate in the future
- --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
- --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
- --config="": config file (default is path/config.yaml|json|toml)
- -d, --destination="": filesystem path to write files to
- --disableRSS[=false]: Do not build RSS files
- --disableSitemap[=false]: Do not build Sitemap file
- --editor="": edit new content with this editor, if provided
- --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
- --log[=false]: Enable Logging
- --logFile="": Log File path (if set, logging enabled automatically)
- --noTimes[=false]: Don't sync modification time of files
- --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
- --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
- -s, --source="": filesystem path to read files relative from
- --stepAnalysis[=false]: display memory and timing of different steps of the program
- -t, --theme="": theme to use (located in /themes/THEMENAME/)
- --uglyURLs[=false]: if true, use /filename.html instead of /filename/
- -v, --verbose[=false]: verbose output
- --verboseLog[=false]: verbose logging
- -w, --watch[=false]: watch filesystem for changes and recreate as needed
-
- Use "hugo [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.
-
-The default help command is
-
-```go
-func (c *Command) initHelp() {
- 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: c.HelpFunc(),
- }
- }
- c.AddCommand(c.helpCommand)
-}
-```
-
-You can provide your own command, function or template through the following methods:
-
-```go
-command.SetHelpCommand(cmd *Command)
-
-command.SetHelpFunc(f func(*Command, []string))
-
-command.SetHelpTemplate(s string)
-```
-
-The latter two will also apply to any children commands.
-
-## Usage
-
-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.
-
- Usage:
- hugo [flags]
- hugo [command]
-
- Available Commands:
- server Hugo runs its own webserver to render the files
- version Print the version number of Hugo
- config Print the site configuration
- check Check content in the source directory
- benchmark Benchmark hugo by building a site a number of times.
- convert Convert your content to different formats
- new Create new content for your site
- list Listing out various types of content
- undraft Undraft changes the content's draft status from 'True' to 'False'
- genautocomplete Generate shell autocompletion script for Hugo
- gendoc Generate Markdown documentation for the Hugo CLI.
- genman Generate man page for Hugo
- import Import your site from others.
-
- Flags:
- -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
- -D, --buildDrafts[=false]: include content marked as draft
- -F, --buildFuture[=false]: include content with publishdate in the future
- --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
- --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
- --config="": config file (default is path/config.yaml|json|toml)
- -d, --destination="": filesystem path to write files to
- --disableRSS[=false]: Do not build RSS files
- --disableSitemap[=false]: Do not build Sitemap file
- --editor="": edit new content with this editor, if provided
- --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
- --log[=false]: Enable Logging
- --logFile="": Log File path (if set, logging enabled automatically)
- --noTimes[=false]: Don't sync modification time of files
- --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
- --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
- -s, --source="": filesystem path to read files relative from
- --stepAnalysis[=false]: display memory and timing of different steps of the program
- -t, --theme="": theme to use (located in /themes/THEMENAME/)
- --uglyURLs[=false]: if true, use /filename.html instead of /filename/
- -v, --verbose[=false]: verbose output
- --verboseLog[=false]: verbose logging
- -w, --watch[=false]: watch filesystem for changes and recreate as needed
-
-### Defining your own usage
-You can provide your own usage function or template for Cobra to use.
-
-The default usage function is:
-
-```go
-return func(c *Command) error {
- err := tmpl(c.Out(), c.UsageTemplate(), c)
- return err
-}
-```
-
-Like help, the function and template are overridable through public methods:
-
-```go
-command.SetUsageFunc(f func(*Command) error)
-
-command.SetUsageTemplate(s string)
-```
-
-## PreRun or 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.Print("\n")
- rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
- _ = rootCmd.Execute()
-}
-```
-
-
-## Alternative Error Handling
-
-Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top,
-providing a way to handle the errors in one location. The current list of functions that return an error is:
-
-* PersistentPreRunE
-* PreRunE
-* RunE
-* PostRunE
-* PersistentPostRunE
-
-If you would like to silence the default `error` and `usage` output in favor of your own, you can set `SilenceUsage`
-and `SilenceErrors` to `true` on the command. A child command respects these flags if they are set on the parent
-command.
-
-**Example Usage using RunE:**
-
-```go
-package main
-
-import (
- "errors"
- "log"
-
- "github.com/spf13/cobra"
-)
-
-func main() {
- 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`,
- RunE: func(cmd *cobra.Command, args []string) error {
- // Do Stuff Here
- return errors.New("some random error")
- },
- }
-
- if err := rootCmd.Execute(); err != nil {
- log.Fatal(err)
- }
-}
-```
-
-## 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 Markdown-formatted documentation for your command
-
-Cobra can generate a Markdown-formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](doc/md_docs.md).
-
-## Generating man pages for your command
-
-Cobra can generate a man page based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Man Docs](doc/man_docs.md).
-
-## Generating bash completions for your command
-
-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).
-
-## Debugging
-
-Cobra provides a ‘DebugFlags’ method on a command which, when called, will print
-out everything Cobra knows about the flags for each command.
-
-### Example
-
-```go
-command.DebugFlags()
-```
-
-## Extensions
-
-Libraries for extending Cobra:
-
-* [cmdns](https://github.com/gosuri/cmdns): Enables name spacing a command's immediate children. It provides an alternative way to structure subcommands, similar to `heroku apps:create` and `ovrclk clusters:launch`.
-
-## Contributing
-
-1. Fork it
-2. Create your feature branch (`git checkout -b my-new-feature`)
-3. Commit your changes (`git commit -am 'Add some feature'`)
-4. Push to the branch (`git push origin my-new-feature`)
-5. Create new Pull Request
-
-## Contributors
-
-Names in no particular order:
-
-* [spf13](https://github.com/spf13),
-[eparis](https://github.com/eparis),
-[bep](https://github.com/bep), and many more!
-
-## 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/cmd/ponzu/vendor/github.com/spf13/cobra/cobra.go b/cmd/ponzu/vendor/github.com/spf13/cobra/cobra.go
deleted file mode 100644
index 2726d19..0000000
--- a/cmd/ponzu/vendor/github.com/spf13/cobra/cobra.go
+++ /dev/null
@@ -1,181 +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"
- "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
-
-// 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 takes a series of func() arguments and appends them to a slice of func().
-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)]
-}
diff --git a/cmd/ponzu/vendor/github.com/spf13/cobra/cobra_test.go b/cmd/ponzu/vendor/github.com/spf13/cobra/cobra_test.go
deleted file mode 100644
index 576c97d..0000000
--- a/cmd/ponzu/vendor/github.com/spf13/cobra/cobra_test.go
+++ /dev/null
@@ -1,1173 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "reflect"
- "runtime"
- "strings"
- "testing"
- "text/template"
-
- "github.com/spf13/pflag"
-)
-
-var tp, te, tt, tr []string
-var rootPersPre, echoPre, echoPersPre, timesPersPre []string
-var flagb1, flagb2, flagb3, flagbr, flagbp bool
-var flags1, flags2a, flags2b, flags3, outs string
-var flagi1, flagi2, flagi3, flagi4, flagir int
-var rootcalled bool
-var versionUsed int
-
-const strtwoParentHelp = "help message for parent flag strtwo"
-const strtwoChildHelp = "help message for child flag strtwo"
-
-var cmdHidden = &Command{
- Use: "hide [secret string to print]",
- Short: "Print anything to screen (if command is known)",
- Long: `an absolutely utterly useless command for testing.`,
- Run: func(cmd *Command, args []string) {
- outs = "hidden"
- },
- Hidden: true,
-}
-
-var cmdPrint = &Command{
- Use: "print [string to print]",
- Short: "Print anything to the screen",
- Long: `an absolutely utterly useless command for testing.`,
- Run: func(cmd *Command, args []string) {
- tp = args
- },
-}
-
-var cmdEcho = &Command{
- Use: "echo [string to echo]",
- Aliases: []string{"say"},
- Short: "Echo anything to the screen",
- Long: `an utterly useless command for testing.`,
- Example: "Just run cobra-test echo",
- PersistentPreRun: func(cmd *Command, args []string) {
- echoPersPre = args
- },
- PreRun: func(cmd *Command, args []string) {
- echoPre = args
- },
- Run: func(cmd *Command, args []string) {
- te = args
- },
-}
-
-var cmdEchoSub = &Command{
- Use: "echosub [string to print]",
- Short: "second sub command for echo",
- Long: `an absolutely utterly useless command for testing gendocs!.`,
- Run: func(cmd *Command, args []string) {
- },
-}
-
-var cmdDeprecated = &Command{
- Use: "deprecated [can't do anything here]",
- Short: "A command which is deprecated",
- Long: `an absolutely utterly useless command for testing deprecation!.`,
- Deprecated: "Please use echo instead",
- Run: func(cmd *Command, args []string) {
- },
-}
-
-var cmdTimes = &Command{
- Use: "times [# times] [string to echo]",
- SuggestFor: []string{"counts"},
- Short: "Echo anything to the screen more times",
- Long: `a slightly useless command for testing.`,
- PersistentPreRun: func(cmd *Command, args []string) {
- timesPersPre = args
- },
- Run: func(cmd *Command, args []string) {
- tt = args
- },
-}
-
-var cmdRootNoRun = &Command{
- Use: "cobra-test",
- Short: "The root can run its own function",
- Long: "The root description for help",
- PersistentPreRun: func(cmd *Command, args []string) {
- rootPersPre = args
- },
-}
-
-var cmdRootSameName = &Command{
- Use: "print",
- Short: "Root with the same name as a subcommand",
- Long: "The root description for help",
-}
-
-var cmdRootWithRun = &Command{
- Use: "cobra-test",
- Short: "The root can run its own function",
- Long: "The root description for help",
- Run: func(cmd *Command, args []string) {
- tr = args
- rootcalled = true
- },
-}
-
-var cmdSubNoRun = &Command{
- Use: "subnorun",
- Short: "A subcommand without a Run function",
- Long: "A long output about a subcommand without a Run function",
-}
-
-var cmdCustomFlags = &Command{
- Use: "customflags [flags] -- REMOTE_COMMAND",
- Short: "A command that expects flags in a custom location",
- Long: "A long output about a command that expects flags in a custom location",
- Run: func(cmd *Command, args []string) {
- },
-}
-
-var cmdVersion1 = &Command{
- Use: "version",
- Short: "Print the version number",
- Long: `First version of the version command`,
- Run: func(cmd *Command, args []string) {
- versionUsed = 1
- },
-}
-
-var cmdVersion2 = &Command{
- Use: "version",
- Short: "Print the version number",
- Long: `Second version of the version command`,
- Run: func(cmd *Command, args []string) {
- versionUsed = 2
- },
-}
-
-var cmdColon = &Command{
- Use: "cmd:colon",
- Run: func(cmd *Command, args []string) {
- },
-}
-
-func flagInit() {
- cmdEcho.ResetFlags()
- cmdPrint.ResetFlags()
- cmdTimes.ResetFlags()
- cmdRootNoRun.ResetFlags()
- cmdRootSameName.ResetFlags()
- cmdRootWithRun.ResetFlags()
- cmdSubNoRun.ResetFlags()
- cmdCustomFlags.ResetFlags()
- cmdVersion1.ResetFlags()
- cmdVersion2.ResetFlags()
-
- cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
- cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour")
- cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
- cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
- cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
- cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
- cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
- cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
- cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
- cmdTimes.Flags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
- cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
- cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
- cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
-}
-
-func commandInit() {
- cmdEcho.ResetCommands()
- cmdPrint.ResetCommands()
- cmdTimes.ResetCommands()
- cmdRootNoRun.ResetCommands()
- cmdRootSameName.ResetCommands()
- cmdRootWithRun.ResetCommands()
- cmdSubNoRun.ResetCommands()
- cmdCustomFlags.ResetCommands()
-}
-
-func initialize() *Command {
- tt, tp, te = nil, nil, nil
- rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
-
- var c = cmdRootNoRun
- flagInit()
- commandInit()
- return c
-}
-
-func initializeWithSameName() *Command {
- tt, tp, te = nil, nil, nil
- rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
- var c = cmdRootSameName
- flagInit()
- commandInit()
- return c
-}
-
-func initializeWithRootCmd() *Command {
- cmdRootWithRun.ResetCommands()
- tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false
- flagInit()
- cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
- cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
- commandInit()
- return cmdRootWithRun
-}
-
-type resulter struct {
- Error error
- Output string
- Command *Command
-}
-
-func fullSetupTest(args ...string) resulter {
- c := initializeWithRootCmd()
-
- return fullTester(c, args...)
-}
-
-func noRRSetupTestSilenced(args ...string) resulter {
- c := initialize()
- c.SilenceErrors = true
- c.SilenceUsage = true
- return fullTester(c, args...)
-}
-
-func noRRSetupTest(args ...string) resulter {
- c := initialize()
-
- return fullTester(c, args...)
-}
-
-func rootOnlySetupTest(args ...string) resulter {
- c := initializeWithRootCmd()
-
- return simpleTester(c, args...)
-}
-
-func simpleTester(c *Command, args ...string) resulter {
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- c.SetArgs(args)
-
- err := c.Execute()
- output := buf.String()
-
- return resulter{err, output, c}
-}
-
-func simpleTesterC(c *Command, args ...string) resulter {
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- c.SetArgs(args)
-
- cmd, err := c.ExecuteC()
- output := buf.String()
-
- return resulter{err, output, cmd}
-}
-
-func fullTester(c *Command, args ...string) resulter {
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated)
- c.SetArgs(args)
-
- err := c.Execute()
- output := buf.String()
-
- return resulter{err, output, c}
-}
-
-func logErr(t *testing.T, found, expected string) {
- out := new(bytes.Buffer)
-
- _, _, line, ok := runtime.Caller(2)
- if ok {
- fmt.Fprintf(out, "Line: %d ", line)
- }
- fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
- t.Errorf(out.String())
-}
-
-func checkStringContains(t *testing.T, found, expected string) {
- if !strings.Contains(found, expected) {
- logErr(t, found, expected)
- }
-}
-
-func checkResultContains(t *testing.T, x resulter, check string) {
- checkStringContains(t, x.Output, check)
-}
-
-func checkStringOmits(t *testing.T, found, expected string) {
- if strings.Contains(found, expected) {
- logErr(t, found, expected)
- }
-}
-
-func checkResultOmits(t *testing.T, x resulter, check string) {
- checkStringOmits(t, x.Output, check)
-}
-
-func checkOutputContains(t *testing.T, c *Command, check string) {
- buf := new(bytes.Buffer)
- c.SetOutput(buf)
- c.Execute()
-
- if !strings.Contains(buf.String(), check) {
- logErr(t, buf.String(), check)
- }
-}
-
-func TestSingleCommand(t *testing.T) {
- noRRSetupTest("print", "one", "two")
-
- if te != nil || tt != nil {
- t.Error("Wrong command called")
- }
- if tp == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tp, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestChildCommand(t *testing.T) {
- noRRSetupTest("echo", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestCommandAlias(t *testing.T) {
- noRRSetupTest("say", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestPrefixMatching(t *testing.T) {
- EnablePrefixMatching = true
- noRRSetupTest("ech", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-
- EnablePrefixMatching = false
-}
-
-func TestNoPrefixMatching(t *testing.T) {
- EnablePrefixMatching = false
-
- noRRSetupTest("ech", "times", "one", "two")
-
- if !(tt == nil && te == nil && tp == nil) {
- t.Error("Wrong command called")
- }
-}
-
-func TestAliasPrefixMatching(t *testing.T) {
- EnablePrefixMatching = true
- noRRSetupTest("sa", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
- EnablePrefixMatching = false
-}
-
-func TestChildSameName(t *testing.T) {
- c := initializeWithSameName()
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs([]string{"print", "one", "two"})
- c.Execute()
-
- if te != nil || tt != nil {
- t.Error("Wrong command called")
- }
- if tp == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tp, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestGrandChildSameName(t *testing.T) {
- c := initializeWithSameName()
- cmdTimes.AddCommand(cmdPrint)
- c.AddCommand(cmdTimes)
- c.SetArgs([]string{"times", "print", "one", "two"})
- c.Execute()
-
- if te != nil || tt != nil {
- t.Error("Wrong command called")
- }
- if tp == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tp, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestUsage(t *testing.T) {
- x := fullSetupTest("help")
- checkResultContains(t, x, cmdRootWithRun.Use+" [flags]")
- x = fullSetupTest("help", "customflags")
- checkResultContains(t, x, cmdCustomFlags.Use)
- checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")
-}
-
-func TestFlagLong(t *testing.T) {
- noRRSetupTest("echo", "--intone=13", "something", "--", "here")
-
- if cmdEcho.ArgsLenAtDash() != 1 {
- t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())
- }
- if strings.Join(te, " ") != "something here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flagi1 != 13 {
- t.Errorf("int flag didn't get correct value, had %d", flagi1)
- }
- if flagi2 != 234 {
- t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
- }
-}
-
-func TestFlagShort(t *testing.T) {
- noRRSetupTest("echo", "-i13", "--", "something", "here")
-
- if cmdEcho.ArgsLenAtDash() != 0 {
- t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())
- }
- if strings.Join(te, " ") != "something here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flagi1 != 13 {
- t.Errorf("int flag didn't get correct value, had %d", flagi1)
- }
- if flagi2 != 234 {
- t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
- }
-
- noRRSetupTest("echo", "-i", "13", "something", "here")
-
- if strings.Join(te, " ") != "something here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flagi1 != 13 {
- t.Errorf("int flag didn't get correct value, had %d", flagi1)
- }
- if flagi2 != 234 {
- t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
- }
-
- noRRSetupTest("print", "-i99", "one", "two")
-
- if strings.Join(tp, " ") != "one two" {
- t.Errorf("flags didn't leave proper args remaining..%s given", tp)
- }
- if flagi3 != 99 {
- t.Errorf("int flag didn't get correct value, had %d", flagi3)
- }
- if flagi1 != 123 {
- t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2)
- }
-}
-
-func TestChildCommandFlags(t *testing.T) {
- noRRSetupTest("echo", "times", "-j", "99", "one", "two")
-
- if strings.Join(tt, " ") != "one two" {
- t.Errorf("flags didn't leave proper args remaining..%s given", tt)
- }
-
- // Testing with flag that shouldn't be persistent
- r := noRRSetupTest("echo", "times", "-j", "99", "-i77", "one", "two")
-
- if r.Error == nil {
- t.Errorf("invalid flag should generate error")
- }
-
- if !strings.Contains(r.Error.Error(), "unknown shorthand") {
- t.Errorf("Wrong error message displayed, \n %s", r.Error)
- }
-
- if flagi2 != 99 {
- t.Errorf("flag value should be 99, %d given", flagi2)
- }
-
- if flagi1 != 123 {
- t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)
- }
-
- // Testing with flag only existing on child
- r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")
-
- if r.Error == nil {
- t.Errorf("invalid flag should generate error")
- }
- if !strings.Contains(r.Error.Error(), "unknown shorthand flag") {
- t.Errorf("Wrong error message displayed, \n %s", r.Error)
- }
-
- // Testing with persistent flag overwritten by child
- noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")
-
- if flags2b != "child" {
- t.Errorf("flag value should be child, %s given", flags2b)
- }
-
- if flags2a != "two" {
- t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)
- }
-
- // Testing flag with invalid input
- r = noRRSetupTest("echo", "-i10E")
-
- if r.Error == nil {
- t.Errorf("invalid input should generate error")
- }
- if !strings.Contains(r.Error.Error(), "invalid syntax") {
- t.Errorf("Wrong error message displayed, \n %s", r.Error)
- }
-}
-
-func TestTrailingCommandFlags(t *testing.T) {
- x := fullSetupTest("echo", "two", "-x")
-
- if x.Error == nil {
- t.Errorf("invalid flag should generate error")
- }
-}
-
-func TestInvalidSubcommandFlags(t *testing.T) {
- cmd := initializeWithRootCmd()
- cmd.AddCommand(cmdTimes)
-
- result := simpleTester(cmd, "times", "--inttwo=2", "--badflag=bar")
- // given that we are not checking here result.Error we check for
- // stock usage message
- checkResultContains(t, result, "cobra-test times [# times]")
- if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") {
- t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")
- }
-
-}
-
-func TestSubcommandExecuteC(t *testing.T) {
- cmd := initializeWithRootCmd()
- double := &Command{
- Use: "double message",
- Run: func(c *Command, args []string) {
- msg := strings.Join(args, " ")
- c.Println(msg, msg)
- },
- }
-
- echo := &Command{
- Use: "echo message",
- Run: func(c *Command, args []string) {
- msg := strings.Join(args, " ")
- c.Println(msg)
- },
- }
-
- cmd.AddCommand(double, echo)
-
- result := simpleTesterC(cmd, "double", "hello", "world")
- checkResultContains(t, result, "hello world hello world")
-
- if result.Command.Name() != "double" {
- t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())
- }
-
- result = simpleTesterC(cmd, "echo", "msg", "to", "be", "echoed")
- checkResultContains(t, result, "msg to be echoed")
-
- if result.Command.Name() != "echo" {
- t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())
- }
-}
-
-func TestSubcommandArgEvaluation(t *testing.T) {
- cmd := initializeWithRootCmd()
-
- first := &Command{
- Use: "first",
- Run: func(cmd *Command, args []string) {
- },
- }
- cmd.AddCommand(first)
-
- second := &Command{
- Use: "second",
- Run: func(cmd *Command, args []string) {
- fmt.Fprintf(cmd.OutOrStdout(), "%v", args)
- },
- }
- first.AddCommand(second)
-
- result := simpleTester(cmd, "first", "second", "first", "third")
-
- expectedOutput := fmt.Sprint([]string{"first third"})
- if result.Output != expectedOutput {
- t.Errorf("exptected %v, got %v", expectedOutput, result.Output)
- }
-}
-
-func TestPersistentFlags(t *testing.T) {
- fullSetupTest("echo", "-s", "something", "-p", "more", "here")
-
- // persistentFlag should act like normal flag on its own command
- if strings.Join(te, " ") != "more here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flags1 != "something" {
- t.Errorf("string flag didn't get correct value, had %v", flags1)
- }
- if !flagbp {
- t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
- }
-
- // persistentFlag should act like normal flag on its own command
- fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "test", "here")
-
- if strings.Join(tt, " ") != "test here" {
- t.Errorf("flags didn't leave proper args remaining. %s given", tt)
- }
-
- if flags1 != "again" {
- t.Errorf("string flag didn't get correct value, had %v", flags1)
- }
-
- if !flagb2 {
- t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2)
- }
- if !flagbp {
- t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
- }
-}
-
-func TestHelpCommand(t *testing.T) {
- x := fullSetupTest("help")
- checkResultContains(t, x, cmdRootWithRun.Long)
-
- x = fullSetupTest("help", "echo")
- checkResultContains(t, x, cmdEcho.Long)
-
- x = fullSetupTest("help", "echo", "times")
- checkResultContains(t, x, cmdTimes.Long)
-}
-
-func TestChildCommandHelp(t *testing.T) {
- c := noRRSetupTest("print", "--help")
- checkResultContains(t, c, strtwoParentHelp)
- r := noRRSetupTest("echo", "times", "--help")
- checkResultContains(t, r, strtwoChildHelp)
-}
-
-func TestNonRunChildHelp(t *testing.T) {
- x := noRRSetupTest("subnorun")
- checkResultContains(t, x, cmdSubNoRun.Long)
-}
-
-func TestRunnableRootCommand(t *testing.T) {
- x := fullSetupTest("")
-
- if !rootcalled {
- t.Errorf("Root Function was not called\n out:%v", x.Error)
- }
-}
-
-func TestVisitParents(t *testing.T) {
- c := &Command{Use: "app"}
- sub := &Command{Use: "sub"}
- dsub := &Command{Use: "dsub"}
- sub.AddCommand(dsub)
- c.AddCommand(sub)
- total := 0
- add := func(x *Command) {
- total++
- }
- sub.VisitParents(add)
- if total != 1 {
- t.Errorf("Should have visited 1 parent but visited %d", total)
- }
-
- total = 0
- dsub.VisitParents(add)
- if total != 2 {
- t.Errorf("Should have visited 2 parent but visited %d", total)
- }
-
- total = 0
- c.VisitParents(add)
- if total != 0 {
- t.Errorf("Should have not visited any parent but visited %d", total)
- }
-}
-
-func TestRunnableRootCommandNilInput(t *testing.T) {
- c := initializeWithRootCmd()
-
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs([]string{})
-
- err := c.Execute()
- if err != nil {
- t.Errorf("Execute() failed with %v", err)
- }
-
- if !rootcalled {
- t.Errorf("Root Function was not called")
- }
-}
-
-func TestRunnableRootCommandEmptyInput(t *testing.T) {
- args := []string{"", "--introot=12", ""}
- c := initializeWithRootCmd()
-
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs(args)
-
- c.Execute()
-
- if !rootcalled {
- t.Errorf("Root Function was not called.\nOutput was:\n%s\n", buf)
- }
-}
-
-func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
- fullSetupTest("echo", "invalid-sub")
-
- if te[0] != "invalid-sub" {
- t.Errorf("Subcommand didn't work...")
- }
-}
-
-func TestRootFlags(t *testing.T) {
- fullSetupTest("-i", "17", "-b")
-
- if !flagbr {
- t.Errorf("flag value should be true, %v given", flagbr)
- }
-
- if flagir != 17 {
- t.Errorf("flag value should be 17, %d given", flagir)
- }
-}
-
-func TestRootHelp(t *testing.T) {
- x := fullSetupTest("--help")
-
- checkResultContains(t, x, "Available Commands:")
- checkResultContains(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-
- if strings.Contains(x.Output, cmdEcho.Use) {
- t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
- }
-
- x = fullSetupTest("echo", "--help")
-
- if strings.Contains(x.Output, cmdTimes.Use) {
- t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
- }
-
- checkResultContains(t, x, "Available Commands:")
- checkResultContains(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-
-}
-
-func TestFlagAccess(t *testing.T) {
- initialize()
-
- local := cmdTimes.LocalFlags()
- inherited := cmdTimes.InheritedFlags()
-
- for _, f := range []string{"inttwo", "strtwo", "booltwo"} {
- if local.Lookup(f) == nil {
- t.Errorf("LocalFlags expected to contain %s, Got: nil", f)
- }
- }
- if inherited.Lookup("strone") == nil {
- t.Errorf("InheritedFlags expected to contain strone, Got: nil")
- }
- if inherited.Lookup("strtwo") != nil {
- t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")
- }
-}
-
-func TestNoNRunnableRootCommandNilInput(t *testing.T) {
- c := initialize()
-
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs([]string{})
-
- c.Execute()
-
- if !strings.Contains(buf.String(), cmdRootNoRun.Long) {
- t.Errorf("Expected to get help output, Got: \n %s", buf)
- }
-}
-
-func TestRootNoCommandHelp(t *testing.T) {
- x := rootOnlySetupTest("--help")
-
- checkResultOmits(t, x, "Available Commands:")
- checkResultOmits(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-
- x = rootOnlySetupTest("echo", "--help")
-
- checkResultOmits(t, x, "Available Commands:")
- checkResultOmits(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-}
-
-func TestRootUnknownCommand(t *testing.T) {
- r := noRRSetupTest("bogus")
- s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"
-
- if r.Output != s {
- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
- }
-
- r = noRRSetupTest("--strtwo=a", "bogus")
- if r.Output != s {
- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
- }
-}
-
-func TestRootUnknownCommandSilenced(t *testing.T) {
- r := noRRSetupTestSilenced("bogus")
-
- if r.Output != "" {
- t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)
- }
-
- r = noRRSetupTestSilenced("--strtwo=a", "bogus")
- if r.Output != "" {
- t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", r.Output)
- }
-}
-
-func TestRootSuggestions(t *testing.T) {
- outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n"
- outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"
-
- cmd := initializeWithRootCmd()
- cmd.AddCommand(cmdTimes)
-
- tests := map[string]string{
- "time": "times",
- "tiems": "times",
- "tims": "times",
- "timeS": "times",
- "rimes": "times",
- "ti": "times",
- "t": "times",
- "timely": "times",
- "ri": "",
- "timezone": "",
- "foo": "",
- "counts": "times",
- }
-
- for typo, suggestion := range tests {
- for _, suggestionsDisabled := range []bool{false, true} {
- cmd.DisableSuggestions = suggestionsDisabled
- result := simpleTester(cmd, typo)
- expected := ""
- if len(suggestion) == 0 || suggestionsDisabled {
- expected = fmt.Sprintf(outputWithoutSuggestions, typo)
- } else {
- expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion)
- }
- if result.Output != expected {
- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)
- }
- }
- }
-}
-
-func TestFlagsBeforeCommand(t *testing.T) {
- // short without space
- x := fullSetupTest("-i10", "echo")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
- }
-
- x = noRRSetupTest("echo", "-i=10")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
- }
-
- // long with equals
- x = noRRSetupTest("--intone=123", "echo", "one", "two")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
- }
-
- // With parsing error properly reported
- x = fullSetupTest("-i10E", "echo")
- if !strings.Contains(x.Error.Error(), "invalid syntax") {
- t.Errorf("Wrong error message displayed, \n %s", x.Error)
- }
-}
-
-func TestRemoveCommand(t *testing.T) {
- versionUsed = 0
- c := initializeWithRootCmd()
- c.AddCommand(cmdVersion1)
- c.RemoveCommand(cmdVersion1)
- x := fullTester(c, "version")
- if x.Error == nil {
- t.Errorf("Removed command should not have been called\n")
- return
- }
-}
-
-func TestCommandWithoutSubcommands(t *testing.T) {
- c := initializeWithRootCmd()
-
- x := simpleTester(c, "")
- if x.Error != nil {
- t.Errorf("Calling command without subcommands should not have error: %v", x.Error)
- return
- }
-}
-
-func TestCommandWithoutSubcommandsWithArg(t *testing.T) {
- c := initializeWithRootCmd()
- expectedArgs := []string{"arg"}
-
- x := simpleTester(c, "arg")
- if x.Error != nil {
- t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error)
- return
- }
- if !reflect.DeepEqual(expectedArgs, tr) {
- t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr)
- return
- }
-}
-
-func TestReplaceCommandWithRemove(t *testing.T) {
- versionUsed = 0
- c := initializeWithRootCmd()
- c.AddCommand(cmdVersion1)
- c.RemoveCommand(cmdVersion1)
- c.AddCommand(cmdVersion2)
- x := fullTester(c, "version")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
- return
- }
- if versionUsed == 1 {
- t.Errorf("Removed command shouldn't be called\n")
- }
- if versionUsed != 2 {
- t.Errorf("Replacing command should have been called but didn't\n")
- }
-}
-
-func TestDeprecatedSub(t *testing.T) {
- c := fullSetupTest("deprecated")
-
- checkResultContains(t, c, cmdDeprecated.Deprecated)
-}
-
-func TestPreRun(t *testing.T) {
- noRRSetupTest("echo", "one", "two")
- if echoPre == nil || echoPersPre == nil {
- t.Error("PreRun or PersistentPreRun not called")
- }
- if rootPersPre != nil || timesPersPre != nil {
- t.Error("Wrong *Pre functions called!")
- }
-
- noRRSetupTest("echo", "times", "one", "two")
- if timesPersPre == nil {
- t.Error("PreRun or PersistentPreRun not called")
- }
- if echoPre != nil || echoPersPre != nil || rootPersPre != nil {
- t.Error("Wrong *Pre functions called!")
- }
-
- noRRSetupTest("print", "one", "two")
- if rootPersPre == nil {
- t.Error("Parent PersistentPreRun not called but should not have been")
- }
- if echoPre != nil || echoPersPre != nil || timesPersPre != nil {
- t.Error("Wrong *Pre functions called!")
- }
-}
-
-// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last
-func TestPeristentPreRunPropagation(t *testing.T) {
- rootCmd := initialize()
-
- // First add the cmdEchoSub to cmdPrint
- cmdPrint.AddCommand(cmdEchoSub)
- // Now add cmdPrint to rootCmd
- rootCmd.AddCommand(cmdPrint)
-
- rootCmd.SetArgs([]string{"print", "echosub", "lala"})
- rootCmd.Execute()
-
- if len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
- t.Error("RootCmd PersistentPreRun not called but should have been")
- }
-}
-
-func TestGlobalNormFuncPropagation(t *testing.T) {
- normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(name)
- }
-
- rootCmd := initialize()
- rootCmd.SetGlobalNormalizationFunc(normFunc)
- if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) {
- t.Error("rootCmd seems to have a wrong normalization function")
- }
-
- // First add the cmdEchoSub to cmdPrint
- cmdPrint.AddCommand(cmdEchoSub)
- if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil {
- t.Error("cmdPrint and cmdEchoSub should had no normalization functions")
- }
-
- // Now add cmdPrint to rootCmd
- rootCmd.AddCommand(cmdPrint)
- if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() ||
- reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
- t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")
- }
-}
-
-func TestFlagOnPflagCommandLine(t *testing.T) {
- flagName := "flagOnCommandLine"
- pflag.String(flagName, "", "about my flag")
- r := fullSetupTest("--help")
-
- checkResultContains(t, r, flagName)
-
- // Reset pflag.CommandLine flagset.
- pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
-}
-
-func TestAddTemplateFunctions(t *testing.T) {
- AddTemplateFunc("t", func() bool { return true })
- AddTemplateFuncs(template.FuncMap{
- "f": func() bool { return false },
- "h": func() string { return "Hello," },
- "w": func() string { return "world." }})
-
- const usage = "Hello, world."
-
- c := &Command{}
- c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
-
- if us := c.UsageString(); us != usage {
- t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us)
- }
-}
-
-func TestUsageIsNotPrintedTwice(t *testing.T) {
- var cmd = &Command{Use: "root"}
- var sub = &Command{Use: "sub"}
- cmd.AddCommand(sub)
-
- r := simpleTester(cmd, "")
- if strings.Count(r.Output, "Usage:") != 1 {
- t.Error("Usage output is not printed exactly once")
- }
-}
-
-func BenchmarkInheritedFlags(b *testing.B) {
- initialize()
- cmdEcho.AddCommand(cmdTimes)
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- cmdTimes.InheritedFlags()
- }
-}
-
-func BenchmarkLocalFlags(b *testing.B) {
- initialize()
- cmdEcho.AddCommand(cmdTimes)
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- cmdTimes.LocalFlags()
- }
-}
diff --git a/cmd/ponzu/vendor/github.com/spf13/cobra/command.go b/cmd/ponzu/vendor/github.com/spf13/cobra/command.go
deleted file mode 100644
index 01d9683..0000000
--- a/cmd/ponzu/vendor/github.com/spf13/cobra/command.go
+++ /dev/null
@@ -1,1289 +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"
-)
-
-// 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
-
- // 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
-
- // 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
-
- // 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
-
- // name is the command name, usually the executable's name.
- name string
- // 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
-
- // 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
-
- // output is an output writer defined by user.
- output io.Writer
- // 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
-}
-
-// 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.
-func (c *Command) SetOutput(output io.Writer) {
- c.output = output
-}
-
-// 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
-}
-
-// 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)
-}
-
-func (c *Command) getOut(def io.Writer) io.Writer {
- if c.output != nil {
- return c.output
- }
- if c.HasParent() {
- return c.parent.getOut(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 return usage string.
-func (c *Command) UsageString() string {
- tmpOutput := c.output
- bb := new(bytes.Buffer)
- c.SetOutput(bb)
- c.Usage()
- c.output = tmpOutput
- 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}}`
-}
-
-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 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
-}
-
-// 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) {
- if c == nil {
- return nil, nil, fmt.Errorf("Called find() on a nil Command")
- }
-
- 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]
- matches := make([]*Command, 0)
- for _, cmd := range c.commands {
- if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match
- return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
- }
- if EnablePrefixMatching {
- if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match
- matches = append(matches, cmd)
- }
- for _, x := range cmd.Aliases {
- if strings.HasPrefix(x, nextSubCmd) {
- matches = append(matches, cmd)
- }
- }
- }
- }
-
- // only accept a single prefix match - multiple matches would be ambiguous
- if len(matches) == 1 {
- return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))
- }
-
- return c, innerArgs
- }
-
- commandFound, a := innerfind(c, args)
- argsWOflags := stripFlags(a, commandFound)
-
- // no subcommand, always take args
- if !commandFound.HasSubCommands() {
- return commandFound, a, nil
- }
-
- // root command with subcommands, do subcommand checking
- if commandFound == c && len(argsWOflags) > 0 {
- suggestionsString := ""
- if !c.DisableSuggestions {
- if c.SuggestionsMinimumDistance <= 0 {
- c.SuggestionsMinimumDistance = 2
- }
- if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {
- suggestionsString += "\n\nDid you mean this?\n"
- for _, s := range suggestions {
- suggestionsString += fmt.Sprintf("\t%v\n", s)
- }
- }
- }
- return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)
- }
-
- return commandFound, a, 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 f.Args at the moment when a -- was
-// found during arg parsing. This allows your program to know which args were
-// before the -- and which came after. (Description from
-// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).
-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 flag as the last point possible to allow for user
- // overriding
- c.InitDefaultHelpFlag()
-
- 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 || !c.Runnable() {
- return flag.ErrHelp
- }
-
- c.preRun()
-
- argWoFlags := c.Flags().Args()
- if c.DisableFlagParsing {
- argWoFlags = a
- }
-
- 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 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 Call execute to use 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.initHelpCmd()
-
- var args []string
-
- // 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:]
- } else {
- args = c.args
- }
-
- 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
- }
- 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
- }
- return cmd, 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)
- }
-}
-
-func (c *Command) initHelpCmd() {
- if c.helpCommand == nil {
- if !c.HasSubCommands() {
- return
- }
-
- 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.`,
- PersistentPreRun: func(cmd *Command, args []string) {},
- PersistentPostRun: func(cmd *Command, args []string) {},
-
- 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 used for testing.
-func (c *Command) ResetCommands() {
- 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...))
-}
-
-// 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.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 {
- if c.name == "" {
- name := c.Use
- i := strings.Index(name, " ")
- if i >= 0 {
- name = name[:i]
- }
- c.name = name
- }
- return c.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
-}
-
-// NameAndAliases returns string containing 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 comamnds, 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 doesn't exists.
-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
-
- 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 parents 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()
- 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 is used in testing.
-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)
-}
-
-// 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) (err error) {
- if c.DisableFlagParsing {
- return nil
- }
- c.mergePersistentFlags()
- err = c.Flags().Parse(args)
- return
-}
-
-// 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
- }
-
- c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
-
- c.VisitParents(func(parent *Command) {
- c.parentsPflags.AddFlagSet(parent.PersistentFlags())
- })
-}
diff --git a/cmd/ponzu/vendor/github.com/spf13/cobra/command_notwin.go b/cmd/ponzu/vendor/github.com/spf13/cobra/command_notwin.go
deleted file mode 100644
index 6159c1c..0000000
--- a/cmd/ponzu/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/cmd/ponzu/vendor/github.com/spf13/cobra/command_test.go b/cmd/ponzu/vendor/github.com/spf13/cobra/command_test.go
deleted file mode 100644
index 978bacc..0000000
--- a/cmd/ponzu/vendor/github.com/spf13/cobra/command_test.go
+++ /dev/null
@@ -1,300 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "reflect"
- "strings"
- "testing"
-
- "github.com/spf13/pflag"
-)
-
-// test to ensure hidden commands run as intended
-func TestHiddenCommandExecutes(t *testing.T) {
-
- // ensure that outs does not already equal what the command will be setting it
- // to, if it did this test would not actually be testing anything...
- if outs == "hidden" {
- t.Errorf("outs should NOT EQUAL hidden")
- }
-
- cmdHidden.Execute()
-
- // upon running the command, the value of outs should now be 'hidden'
- if outs != "hidden" {
- t.Errorf("Hidden command failed to run!")
- }
-}
-
-// test to ensure hidden commands do not show up in usage/help text
-func TestHiddenCommandIsHidden(t *testing.T) {
- if cmdHidden.IsAvailableCommand() {
- t.Errorf("Hidden command found!")
- }
-}
-
-func TestStripFlags(t *testing.T) {
- tests := []struct {
- input []string
- output []string
- }{
- {
- []string{"foo", "bar"},
- []string{"foo", "bar"},
- },
- {
- []string{"foo", "--bar", "-b"},
- []string{"foo"},
- },
- {
- []string{"-b", "foo", "--bar", "bar"},
- []string{},
- },
- {
- []string{"-i10", "echo"},
- []string{"echo"},
- },
- {
- []string{"-i=10", "echo"},
- []string{"echo"},
- },
- {
- []string{"--int=100", "echo"},
- []string{"echo"},
- },
- {
- []string{"-ib", "echo", "-bfoo", "baz"},
- []string{"echo", "baz"},
- },
- {
- []string{"-i=baz", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"--int=baz", "-bbar", "-i", "foo", "blah"},
- []string{"blah"},
- },
- {
- []string{"--cat", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"-c", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"--persist", "bar"},
- []string{"bar"},
- },
- {
- []string{"-p", "bar"},
- []string{"bar"},
- },
- }
-
- cmdPrint := &Command{
- Use: "print [string to print]",
- Short: "Print anything to the screen",
- Long: `an utterly useless command for testing.`,
- Run: func(cmd *Command, args []string) {
- tp = args
- },
- }
-
- var flagi int
- var flagstr string
- var flagbool bool
- cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")
- cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")
- cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")
- cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")
-
- for _, test := range tests {
- output := stripFlags(test.input, cmdPrint)
- if !reflect.DeepEqual(test.output, output) {
- t.Errorf("expected: %v, got: %v", test.output, output)
- }
- }
-}
-
-func TestDisableFlagParsing(t *testing.T) {
- as := []string{"-v", "-race", "-file", "foo.go"}
- targs := []string{}
- cmdPrint := &Command{
- DisableFlagParsing: true,
- Run: func(cmd *Command, args []string) {
- targs = args
- },
- }
- osargs := []string{"cmd"}
- os.Args = append(osargs, as...)
- err := cmdPrint.Execute()
- if err != nil {
- t.Error(err)
- }
- if !reflect.DeepEqual(as, targs) {
- t.Errorf("expected: %v, got: %v", as, targs)
- }
-}
-
-func TestInitHelpFlagMergesFlags(t *testing.T) {
- usage := "custom flag"
- baseCmd := Command{Use: "testcmd"}
- baseCmd.PersistentFlags().Bool("help", false, usage)
- cmd := Command{Use: "do"}
- baseCmd.AddCommand(&cmd)
-
- cmd.InitDefaultHelpFlag()
- actual := cmd.Flags().Lookup("help").Usage
- if actual != usage {
- t.Fatalf("Expected the help flag from the base command with usage '%s', but got the default with usage '%s'", usage, actual)
- }
-}
-
-func TestCommandsAreSorted(t *testing.T) {
- EnableCommandSorting = true
-
- originalNames := []string{"middle", "zlast", "afirst"}
- expectedNames := []string{"afirst", "middle", "zlast"}
-
- var tmpCommand = &Command{Use: "tmp"}
-
- for _, name := range originalNames {
- tmpCommand.AddCommand(&Command{Use: name})
- }
-
- for i, c := range tmpCommand.Commands() {
- if expectedNames[i] != c.Name() {
- t.Errorf("expected: %s, got: %s", expectedNames[i], c.Name())
- }
- }
-
- EnableCommandSorting = true
-}
-
-func TestEnableCommandSortingIsDisabled(t *testing.T) {
- EnableCommandSorting = false
-
- originalNames := []string{"middle", "zlast", "afirst"}
-
- var tmpCommand = &Command{Use: "tmp"}
-
- for _, name := range originalNames {
- tmpCommand.AddCommand(&Command{Use: name})
- }
-
- for i, c := range tmpCommand.Commands() {
- if originalNames[i] != c.Name() {
- t.Errorf("expected: %s, got: %s", originalNames[i], c.Name())
- }
- }
-
- EnableCommandSorting = true
-}
-
-func TestSetOutput(t *testing.T) {
- cmd := &Command{}
- cmd.SetOutput(nil)
- if out := cmd.OutOrStdout(); out != os.Stdout {
- t.Fatalf("expected setting output to nil to revert back to stdout, got %v", out)
- }
-}
-
-func TestFlagErrorFunc(t *testing.T) {
- cmd := &Command{
- Use: "print",
- RunE: func(cmd *Command, args []string) error {
- return nil
- },
- }
- expectedFmt := "This is expected: %s"
-
- cmd.SetFlagErrorFunc(func(c *Command, err error) error {
- return fmt.Errorf(expectedFmt, err)
- })
- cmd.SetArgs([]string{"--bogus-flag"})
- cmd.SetOutput(new(bytes.Buffer))
-
- err := cmd.Execute()
-
- expected := fmt.Sprintf(expectedFmt, "unknown flag: --bogus-flag")
- if err.Error() != expected {
- t.Errorf("expected %v, got %v", expected, err.Error())
- }
-}
-
-// TestSortedFlags checks,
-// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
-// Related to https://github.com/spf13/cobra/issues/404.
-func TestSortedFlags(t *testing.T) {
- cmd := &Command{}
- cmd.Flags().SortFlags = false
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- cmd.Flags().Bool(name, false, "")
- }
-
- i := 0
- cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
- if i == len(names) {
- return
- }
- if isStringInStringSlice(f.Name, names) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- }
- })
-}
-
-// contains checks, if s is in ss.
-func isStringInStringSlice(s string, ss []string) bool {
- for _, v := range ss {
- if v == s {
- return true
- }
- }
- return false
-}
-
-// TestHelpFlagInHelp checks,
-// if '--help' flag is shown in help for child (executing `parent help child`),
-// that has no other flags.
-// Related to https://github.com/spf13/cobra/issues/302.
-func TestHelpFlagInHelp(t *testing.T) {
- output := new(bytes.Buffer)
- parent := &Command{Use: "parent", Run: func(*Command, []string) {}}
- parent.SetOutput(output)
-
- child := &Command{Use: "child", Run: func(*Command, []string) {}}
- parent.AddCommand(child)
-
- parent.SetArgs([]string{"help", "child"})
- err := parent.Execute()
- if err != nil {
- t.Fatal(err)
- }
-
- if !strings.Contains(output.String(), "[flags]") {
- t.Errorf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())
- }
-}
-
-// TestMergeCommandLineToFlags checks,
-// if pflag.CommandLine is correctly merged to c.Flags() after first call
-// of c.mergePersistentFlags.
-// Related to https://github.com/spf13/cobra/issues/443.
-func TestMergeCommandLineToFlags(t *testing.T) {
- pflag.Bool("boolflag", false, "")
- c := &Command{Use: "c", Run: func(*Command, []string) {}}
- c.mergePersistentFlags()
- if c.Flags().Lookup("boolflag") == nil {
- t.Fatal("Expecting to have flag from CommandLine in c.Flags()")
- }
-
- // Reset pflag.CommandLine flagset.
- pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
-}
diff --git a/cmd/ponzu/vendor/github.com/spf13/cobra/command_win.go b/cmd/ponzu/vendor/github.com/spf13/cobra/command_win.go
deleted file mode 100644
index 4b0eaa1..0000000
--- a/cmd/ponzu/vendor/github.com/spf13/cobra/command_win.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// +build windows
-
-package cobra
-
-import (
- "os"
- "time"
-
- "github.com/inconshreveable/mousetrap"
-)
-
-var preExecHookFn = preExecHook
-
-// enables an information splash screen on Windows if the CLI is started from explorer.exe.
-var MousetrapHelpText string = `This is a command line tool
-
-You need to open cmd.exe and run it from there.
-`
-
-func preExecHook(c *Command) {
- if mousetrap.StartedByExplorer() {
- c.Print(MousetrapHelpText)
- time.Sleep(5 * time.Second)
- os.Exit(1)
- }
-}