Update godeps for addition of cobra dependency
codegangsta/cli is being removed since the "dist" tool which used it is no longer in the repo. Signed-off-by: Aaron Lehmann <aaron.lehmann@docker.com>
This commit is contained in:
parent
cbc9957e29
commit
540e3f1433
61 changed files with 7003 additions and 3372 deletions
35
Godeps/Godeps.json
generated
35
Godeps/Godeps.json
generated
|
@ -39,11 +39,6 @@
|
|||
"ImportPath": "github.com/bugsnag/panicwrap",
|
||||
"Rev": "e5f9854865b9778a45169fc249e99e338d4d6f27"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/codegangsta/cli",
|
||||
"Comment": "1.2.0-66-g6086d79",
|
||||
"Rev": "6086d7927ec35315964d9fea46df6c04e6d697c1"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/denverdino/aliyungo/oss",
|
||||
"Rev": "0e0f322d0a54b994dea9d32541050d177edf6aa3"
|
||||
|
@ -82,22 +77,38 @@
|
|||
"Rev": "e444e69cbd2e2e3e0749a2f3c717cec491552bbf"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/noahdesu/go-ceph/rados",
|
||||
"Comment": "v.0.3.0-29-gb15639c",
|
||||
"Rev": "b15639c44c05368348355229070361395d9152ee"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/stevvooe/resumable",
|
||||
"Rev": "51ad44105773cafcbe91927f70ac68e1bf78f8b4"
|
||||
"ImportPath": "github.com/inconshreveable/mousetrap",
|
||||
"Rev": "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/mitchellh/mapstructure",
|
||||
"Rev": "482a9fd5fa83e8c4e7817413b80f3eb8feec03ef"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/ncw/swift",
|
||||
"Rev": "22c8fa9fb5ba145b4d4e2cebb027e84b1a7b1296"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/noahdesu/go-ceph/rados",
|
||||
"Comment": "v.0.3.0-29-gb15639c",
|
||||
"Rev": "b15639c44c05368348355229070361395d9152ee"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/spf13/cobra",
|
||||
"Rev": "312092086bed4968099259622145a0c9ae280064"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/spf13/pflag",
|
||||
"Rev": "5644820622454e71517561946e3d94b9f9db6842"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/ncw/swift",
|
||||
"Rev": "ca8cbbde50d4e12dd8ad70b1bd66589ae98efc5c"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/stevvooe/resumable",
|
||||
"Rev": "51ad44105773cafcbe91927f70ac68e1bf78f8b4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/yvasiyarov/go-metrics",
|
||||
"Rev": "57bccd1ccd43f94bb17fdd8bf3007059b802f85e"
|
||||
|
|
6
Godeps/_workspace/src/github.com/codegangsta/cli/.travis.yml
generated
vendored
6
Godeps/_workspace/src/github.com/codegangsta/cli/.travis.yml
generated
vendored
|
@ -1,6 +0,0 @@
|
|||
language: go
|
||||
go: 1.1
|
||||
|
||||
script:
|
||||
- go vet ./...
|
||||
- go test -v ./...
|
21
Godeps/_workspace/src/github.com/codegangsta/cli/LICENSE
generated
vendored
21
Godeps/_workspace/src/github.com/codegangsta/cli/LICENSE
generated
vendored
|
@ -1,21 +0,0 @@
|
|||
Copyright (C) 2013 Jeremy Saenz
|
||||
All Rights Reserved.
|
||||
|
||||
MIT LICENSE
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
298
Godeps/_workspace/src/github.com/codegangsta/cli/README.md
generated
vendored
298
Godeps/_workspace/src/github.com/codegangsta/cli/README.md
generated
vendored
|
@ -1,298 +0,0 @@
|
|||
[![Build Status](https://travis-ci.org/codegangsta/cli.png?branch=master)](https://travis-ci.org/codegangsta/cli)
|
||||
|
||||
# cli.go
|
||||
cli.go is simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable command line applications in an expressive way.
|
||||
|
||||
You can view the API docs here:
|
||||
http://godoc.org/github.com/codegangsta/cli
|
||||
|
||||
## Overview
|
||||
Command line apps are usually so tiny that there is absolutely no reason why your code should *not* be self-documenting. Things like generating help text and parsing command flags/options should not hinder productivity when writing a command line app.
|
||||
|
||||
**This is where cli.go comes into play.** cli.go makes command line programming fun, organized, and expressive!
|
||||
|
||||
## Installation
|
||||
Make sure you have a working Go environment (go 1.1 is *required*). [See the install instructions](http://golang.org/doc/install.html).
|
||||
|
||||
To install `cli.go`, simply run:
|
||||
```
|
||||
$ go get github.com/codegangsta/cli
|
||||
```
|
||||
|
||||
Make sure your `PATH` includes to the `$GOPATH/bin` directory so your commands can be easily used:
|
||||
```
|
||||
export PATH=$PATH:$GOPATH/bin
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
One of the philosophies behind cli.go is that an API should be playful and full of discovery. So a cli.go app can be as little as one line of code in `main()`.
|
||||
|
||||
``` go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cli.NewApp().Run(os.Args)
|
||||
}
|
||||
```
|
||||
|
||||
This app will run and show help text, but is not very useful. Let's give an action to execute and some help documentation:
|
||||
|
||||
``` go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := cli.NewApp()
|
||||
app.Name = "boom"
|
||||
app.Usage = "make an explosive entrance"
|
||||
app.Action = func(c *cli.Context) {
|
||||
println("boom! I say!")
|
||||
}
|
||||
|
||||
app.Run(os.Args)
|
||||
}
|
||||
```
|
||||
|
||||
Running this already gives you a ton of functionality, plus support for things like subcommands and flags, which are covered below.
|
||||
|
||||
## Example
|
||||
|
||||
Being a programmer can be a lonely job. Thankfully by the power of automation that is not the case! Let's create a greeter app to fend off our demons of loneliness!
|
||||
|
||||
Start by creating a directory named `greet`, and within it, add a file, `greet.go` with the following code in it:
|
||||
|
||||
``` go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := cli.NewApp()
|
||||
app.Name = "greet"
|
||||
app.Usage = "fight the loneliness!"
|
||||
app.Action = func(c *cli.Context) {
|
||||
println("Hello friend!")
|
||||
}
|
||||
|
||||
app.Run(os.Args)
|
||||
}
|
||||
```
|
||||
|
||||
Install our command to the `$GOPATH/bin` directory:
|
||||
|
||||
```
|
||||
$ go install
|
||||
```
|
||||
|
||||
Finally run our new command:
|
||||
|
||||
```
|
||||
$ greet
|
||||
Hello friend!
|
||||
```
|
||||
|
||||
cli.go also generates some bitchass help text:
|
||||
```
|
||||
$ greet help
|
||||
NAME:
|
||||
greet - fight the loneliness!
|
||||
|
||||
USAGE:
|
||||
greet [global options] command [command options] [arguments...]
|
||||
|
||||
VERSION:
|
||||
0.0.0
|
||||
|
||||
COMMANDS:
|
||||
help, h Shows a list of commands or help for one command
|
||||
|
||||
GLOBAL OPTIONS
|
||||
--version Shows version information
|
||||
```
|
||||
|
||||
### Arguments
|
||||
You can lookup arguments by calling the `Args` function on `cli.Context`.
|
||||
|
||||
``` go
|
||||
...
|
||||
app.Action = func(c *cli.Context) {
|
||||
println("Hello", c.Args()[0])
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
### Flags
|
||||
Setting and querying flags is simple.
|
||||
``` go
|
||||
...
|
||||
app.Flags = []cli.Flag {
|
||||
cli.StringFlag{
|
||||
Name: "lang",
|
||||
Value: "english",
|
||||
Usage: "language for the greeting",
|
||||
},
|
||||
}
|
||||
app.Action = func(c *cli.Context) {
|
||||
name := "someone"
|
||||
if len(c.Args()) > 0 {
|
||||
name = c.Args()[0]
|
||||
}
|
||||
if c.String("lang") == "spanish" {
|
||||
println("Hola", name)
|
||||
} else {
|
||||
println("Hello", name)
|
||||
}
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
#### Alternate Names
|
||||
|
||||
You can set alternate (or short) names for flags by providing a comma-delimited list for the `Name`. e.g.
|
||||
|
||||
``` go
|
||||
app.Flags = []cli.Flag {
|
||||
cli.StringFlag{
|
||||
Name: "lang, l",
|
||||
Value: "english",
|
||||
Usage: "language for the greeting",
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
That flag can then be set with `--lang spanish` or `-l spanish`. Note that giving two different forms of the same flag in the same command invocation is an error.
|
||||
|
||||
#### Values from the Environment
|
||||
|
||||
You can also have the default value set from the environment via `EnvVar`. e.g.
|
||||
|
||||
``` go
|
||||
app.Flags = []cli.Flag {
|
||||
cli.StringFlag{
|
||||
Name: "lang, l",
|
||||
Value: "english",
|
||||
Usage: "language for the greeting",
|
||||
EnvVar: "APP_LANG",
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The `EnvVar` may also be given as a comma-delimited "cascade", where the first environment variable that resolves is used as the default.
|
||||
|
||||
``` go
|
||||
app.Flags = []cli.Flag {
|
||||
cli.StringFlag{
|
||||
Name: "lang, l",
|
||||
Value: "english",
|
||||
Usage: "language for the greeting",
|
||||
EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Subcommands
|
||||
|
||||
Subcommands can be defined for a more git-like command line app.
|
||||
```go
|
||||
...
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "add",
|
||||
ShortName: "a",
|
||||
Usage: "add a task to the list",
|
||||
Action: func(c *cli.Context) {
|
||||
println("added task: ", c.Args().First())
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "complete",
|
||||
ShortName: "c",
|
||||
Usage: "complete a task on the list",
|
||||
Action: func(c *cli.Context) {
|
||||
println("completed task: ", c.Args().First())
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "template",
|
||||
ShortName: "r",
|
||||
Usage: "options for task templates",
|
||||
Subcommands: []cli.Command{
|
||||
{
|
||||
Name: "add",
|
||||
Usage: "add a new template",
|
||||
Action: func(c *cli.Context) {
|
||||
println("new task template: ", c.Args().First())
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "remove",
|
||||
Usage: "remove an existing template",
|
||||
Action: func(c *cli.Context) {
|
||||
println("removed task template: ", c.Args().First())
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
### Bash Completion
|
||||
|
||||
You can enable completion commands by setting the `EnableBashCompletion`
|
||||
flag on the `App` object. By default, this setting will only auto-complete to
|
||||
show an app's subcommands, but you can write your own completion methods for
|
||||
the App or its subcommands.
|
||||
```go
|
||||
...
|
||||
var tasks = []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
|
||||
app := cli.NewApp()
|
||||
app.EnableBashCompletion = true
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "complete",
|
||||
ShortName: "c",
|
||||
Usage: "complete a task on the list",
|
||||
Action: func(c *cli.Context) {
|
||||
println("completed task: ", c.Args().First())
|
||||
},
|
||||
BashComplete: func(c *cli.Context) {
|
||||
// This will complete if no args are passed
|
||||
if len(c.Args()) > 0 {
|
||||
return
|
||||
}
|
||||
for _, t := range tasks {
|
||||
fmt.Println(t)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
#### To Enable
|
||||
|
||||
Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
|
||||
setting the `PROG` variable to the name of your program:
|
||||
|
||||
`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
|
||||
|
||||
|
||||
## Contribution Guidelines
|
||||
Feel free to put up a pull request to fix a bug or maybe add a feature. I will give it a code review and make sure that it does not break backwards compatibility. If I or any other collaborators agree that it is in line with the vision of the project, we will work with you to get the code into a mergeable state and merge it into the master branch.
|
||||
|
||||
If you have contributed something significant to the project, I will most likely add you as a collaborator. As a collaborator you are given the ability to merge others pull requests. It is very important that new code does not break existing code, so be careful about what code you do choose to merge. If you have any questions feel free to link @codegangsta to the issue in question and we can review it together.
|
||||
|
||||
If you feel like you have contributed to the project but have not yet been added as a collaborator, I probably forgot to add you. Hit @codegangsta up over email and we will get it figured out.
|
275
Godeps/_workspace/src/github.com/codegangsta/cli/app.go
generated
vendored
275
Godeps/_workspace/src/github.com/codegangsta/cli/app.go
generated
vendored
|
@ -1,275 +0,0 @@
|
|||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"text/tabwriter"
|
||||
"text/template"
|
||||
"time"
|
||||
)
|
||||
|
||||
// App is the main structure of a cli application. It is recomended that
|
||||
// and app be created with the cli.NewApp() function
|
||||
type App struct {
|
||||
// The name of the program. Defaults to os.Args[0]
|
||||
Name string
|
||||
// Description of the program.
|
||||
Usage string
|
||||
// Version of the program
|
||||
Version string
|
||||
// List of commands to execute
|
||||
Commands []Command
|
||||
// List of flags to parse
|
||||
Flags []Flag
|
||||
// Boolean to enable bash completion commands
|
||||
EnableBashCompletion bool
|
||||
// Boolean to hide built-in help command
|
||||
HideHelp bool
|
||||
// Boolean to hide built-in version flag
|
||||
HideVersion bool
|
||||
// An action to execute when the bash-completion flag is set
|
||||
BashComplete func(context *Context)
|
||||
// An action to execute before any subcommands are run, but after the context is ready
|
||||
// If a non-nil error is returned, no subcommands are run
|
||||
Before func(context *Context) error
|
||||
// The action to execute when no subcommands are specified
|
||||
Action func(context *Context)
|
||||
// Execute this function if the proper command cannot be found
|
||||
CommandNotFound func(context *Context, command string)
|
||||
// Compilation date
|
||||
Compiled time.Time
|
||||
// Author
|
||||
Author string
|
||||
// Author e-mail
|
||||
Email string
|
||||
// Writer writer to write output to
|
||||
Writer io.Writer
|
||||
}
|
||||
|
||||
// Tries to find out when this binary was compiled.
|
||||
// Returns the current time if it fails to find it.
|
||||
func compileTime() time.Time {
|
||||
info, err := os.Stat(os.Args[0])
|
||||
if err != nil {
|
||||
return time.Now()
|
||||
}
|
||||
return info.ModTime()
|
||||
}
|
||||
|
||||
// Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
|
||||
func NewApp() *App {
|
||||
return &App{
|
||||
Name: os.Args[0],
|
||||
Usage: "A new cli application",
|
||||
Version: "0.0.0",
|
||||
BashComplete: DefaultAppComplete,
|
||||
Action: helpCommand.Action,
|
||||
Compiled: compileTime(),
|
||||
Author: "Author",
|
||||
Email: "unknown@email",
|
||||
Writer: os.Stdout,
|
||||
}
|
||||
}
|
||||
|
||||
// Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
|
||||
func (a *App) Run(arguments []string) error {
|
||||
if HelpPrinter == nil {
|
||||
defer func() {
|
||||
HelpPrinter = nil
|
||||
}()
|
||||
|
||||
HelpPrinter = func(templ string, data interface{}) {
|
||||
w := tabwriter.NewWriter(a.Writer, 0, 8, 1, '\t', 0)
|
||||
t := template.Must(template.New("help").Parse(templ))
|
||||
err := t.Execute(w, data)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
w.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// append help to commands
|
||||
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
|
||||
a.Commands = append(a.Commands, helpCommand)
|
||||
if (HelpFlag != BoolFlag{}) {
|
||||
a.appendFlag(HelpFlag)
|
||||
}
|
||||
}
|
||||
|
||||
//append version/help flags
|
||||
if a.EnableBashCompletion {
|
||||
a.appendFlag(BashCompletionFlag)
|
||||
}
|
||||
|
||||
if !a.HideVersion {
|
||||
a.appendFlag(VersionFlag)
|
||||
}
|
||||
|
||||
// parse flags
|
||||
set := flagSet(a.Name, a.Flags)
|
||||
set.SetOutput(ioutil.Discard)
|
||||
err := set.Parse(arguments[1:])
|
||||
nerr := normalizeFlags(a.Flags, set)
|
||||
if nerr != nil {
|
||||
fmt.Fprintln(a.Writer, nerr)
|
||||
context := NewContext(a, set, set)
|
||||
ShowAppHelp(context)
|
||||
fmt.Fprintln(a.Writer)
|
||||
return nerr
|
||||
}
|
||||
context := NewContext(a, set, set)
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(a.Writer, "Incorrect Usage.\n\n")
|
||||
ShowAppHelp(context)
|
||||
fmt.Fprintln(a.Writer)
|
||||
return err
|
||||
}
|
||||
|
||||
if checkCompletions(context) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if checkHelp(context) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if checkVersion(context) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if a.Before != nil {
|
||||
err := a.Before(context)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
args := context.Args()
|
||||
if args.Present() {
|
||||
name := args.First()
|
||||
c := a.Command(name)
|
||||
if c != nil {
|
||||
return c.Run(context)
|
||||
}
|
||||
}
|
||||
|
||||
// Run default Action
|
||||
a.Action(context)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Another entry point to the cli app, takes care of passing arguments and error handling
|
||||
func (a *App) RunAndExitOnError() {
|
||||
if err := a.Run(os.Args); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
|
||||
func (a *App) RunAsSubcommand(ctx *Context) error {
|
||||
// append help to commands
|
||||
if len(a.Commands) > 0 {
|
||||
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
|
||||
a.Commands = append(a.Commands, helpCommand)
|
||||
if (HelpFlag != BoolFlag{}) {
|
||||
a.appendFlag(HelpFlag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// append flags
|
||||
if a.EnableBashCompletion {
|
||||
a.appendFlag(BashCompletionFlag)
|
||||
}
|
||||
|
||||
// parse flags
|
||||
set := flagSet(a.Name, a.Flags)
|
||||
set.SetOutput(ioutil.Discard)
|
||||
err := set.Parse(ctx.Args().Tail())
|
||||
nerr := normalizeFlags(a.Flags, set)
|
||||
context := NewContext(a, set, ctx.globalSet)
|
||||
|
||||
if nerr != nil {
|
||||
fmt.Fprintln(a.Writer, nerr)
|
||||
if len(a.Commands) > 0 {
|
||||
ShowSubcommandHelp(context)
|
||||
} else {
|
||||
ShowCommandHelp(ctx, context.Args().First())
|
||||
}
|
||||
fmt.Fprintln(a.Writer)
|
||||
return nerr
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(a.Writer, "Incorrect Usage.\n\n")
|
||||
ShowSubcommandHelp(context)
|
||||
return err
|
||||
}
|
||||
|
||||
if checkCompletions(context) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(a.Commands) > 0 {
|
||||
if checkSubcommandHelp(context) {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if checkCommandHelp(ctx, context.Args().First()) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if a.Before != nil {
|
||||
err := a.Before(context)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
args := context.Args()
|
||||
if args.Present() {
|
||||
name := args.First()
|
||||
c := a.Command(name)
|
||||
if c != nil {
|
||||
return c.Run(context)
|
||||
}
|
||||
}
|
||||
|
||||
// Run default Action
|
||||
a.Action(context)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Returns the named command on App. Returns nil if the command does not exist
|
||||
func (a *App) Command(name string) *Command {
|
||||
for _, c := range a.Commands {
|
||||
if c.HasName(name) {
|
||||
return &c
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) hasFlag(flag Flag) bool {
|
||||
for _, f := range a.Flags {
|
||||
if flag == f {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *App) appendFlag(flag Flag) {
|
||||
if !a.hasFlag(flag) {
|
||||
a.Flags = append(a.Flags, flag)
|
||||
}
|
||||
}
|
554
Godeps/_workspace/src/github.com/codegangsta/cli/app_test.go
generated
vendored
554
Godeps/_workspace/src/github.com/codegangsta/cli/app_test.go
generated
vendored
|
@ -1,554 +0,0 @@
|
|||
package cli_test
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func ExampleApp() {
|
||||
// set args for examples sake
|
||||
os.Args = []string{"greet", "--name", "Jeremy"}
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Name = "greet"
|
||||
app.Flags = []cli.Flag{
|
||||
cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
|
||||
}
|
||||
app.Action = func(c *cli.Context) {
|
||||
fmt.Printf("Hello %v\n", c.String("name"))
|
||||
}
|
||||
app.Run(os.Args)
|
||||
// Output:
|
||||
// Hello Jeremy
|
||||
}
|
||||
|
||||
func ExampleAppSubcommand() {
|
||||
// set args for examples sake
|
||||
os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
|
||||
app := cli.NewApp()
|
||||
app.Name = "say"
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "hello",
|
||||
ShortName: "hi",
|
||||
Usage: "use it to see a description",
|
||||
Description: "This is how we describe hello the function",
|
||||
Subcommands: []cli.Command{
|
||||
{
|
||||
Name: "english",
|
||||
ShortName: "en",
|
||||
Usage: "sends a greeting in english",
|
||||
Description: "greets someone in english",
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Value: "Bob",
|
||||
Usage: "Name of the person to greet",
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
fmt.Println("Hello,", c.String("name"))
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Run(os.Args)
|
||||
// Output:
|
||||
// Hello, Jeremy
|
||||
}
|
||||
|
||||
func ExampleAppHelp() {
|
||||
// set args for examples sake
|
||||
os.Args = []string{"greet", "h", "describeit"}
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Name = "greet"
|
||||
app.Flags = []cli.Flag{
|
||||
cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
|
||||
}
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "describeit",
|
||||
ShortName: "d",
|
||||
Usage: "use it to see a description",
|
||||
Description: "This is how we describe describeit the function",
|
||||
Action: func(c *cli.Context) {
|
||||
fmt.Printf("i like to describe things")
|
||||
},
|
||||
},
|
||||
}
|
||||
app.Run(os.Args)
|
||||
// Output:
|
||||
// NAME:
|
||||
// describeit - use it to see a description
|
||||
//
|
||||
// USAGE:
|
||||
// command describeit [arguments...]
|
||||
//
|
||||
// DESCRIPTION:
|
||||
// This is how we describe describeit the function
|
||||
}
|
||||
|
||||
func ExampleAppBashComplete() {
|
||||
// set args for examples sake
|
||||
os.Args = []string{"greet", "--generate-bash-completion"}
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Name = "greet"
|
||||
app.EnableBashCompletion = true
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "describeit",
|
||||
ShortName: "d",
|
||||
Usage: "use it to see a description",
|
||||
Description: "This is how we describe describeit the function",
|
||||
Action: func(c *cli.Context) {
|
||||
fmt.Printf("i like to describe things")
|
||||
},
|
||||
}, {
|
||||
Name: "next",
|
||||
Usage: "next example",
|
||||
Description: "more stuff to see when generating bash completion",
|
||||
Action: func(c *cli.Context) {
|
||||
fmt.Printf("the next example")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Run(os.Args)
|
||||
// Output:
|
||||
// describeit
|
||||
// d
|
||||
// next
|
||||
// help
|
||||
// h
|
||||
}
|
||||
|
||||
func TestApp_Run(t *testing.T) {
|
||||
s := ""
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Action = func(c *cli.Context) {
|
||||
s = s + c.Args().First()
|
||||
}
|
||||
|
||||
err := app.Run([]string{"command", "foo"})
|
||||
expect(t, err, nil)
|
||||
err = app.Run([]string{"command", "bar"})
|
||||
expect(t, err, nil)
|
||||
expect(t, s, "foobar")
|
||||
}
|
||||
|
||||
var commandAppTests = []struct {
|
||||
name string
|
||||
expected bool
|
||||
}{
|
||||
{"foobar", true},
|
||||
{"batbaz", true},
|
||||
{"b", true},
|
||||
{"f", true},
|
||||
{"bat", false},
|
||||
{"nothing", false},
|
||||
}
|
||||
|
||||
func TestApp_Command(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
fooCommand := cli.Command{Name: "foobar", ShortName: "f"}
|
||||
batCommand := cli.Command{Name: "batbaz", ShortName: "b"}
|
||||
app.Commands = []cli.Command{
|
||||
fooCommand,
|
||||
batCommand,
|
||||
}
|
||||
|
||||
for _, test := range commandAppTests {
|
||||
expect(t, app.Command(test.name) != nil, test.expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApp_CommandWithArgBeforeFlags(t *testing.T) {
|
||||
var parsedOption, firstArg string
|
||||
|
||||
app := cli.NewApp()
|
||||
command := cli.Command{
|
||||
Name: "cmd",
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{Name: "option", Value: "", Usage: "some option"},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
parsedOption = c.String("option")
|
||||
firstArg = c.Args().First()
|
||||
},
|
||||
}
|
||||
app.Commands = []cli.Command{command}
|
||||
|
||||
app.Run([]string{"", "cmd", "my-arg", "--option", "my-option"})
|
||||
|
||||
expect(t, parsedOption, "my-option")
|
||||
expect(t, firstArg, "my-arg")
|
||||
}
|
||||
|
||||
func TestApp_RunAsSubcommandParseFlags(t *testing.T) {
|
||||
var context *cli.Context
|
||||
|
||||
a := cli.NewApp()
|
||||
a.Commands = []cli.Command{
|
||||
{
|
||||
Name: "foo",
|
||||
Action: func(c *cli.Context) {
|
||||
context = c
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "lang",
|
||||
Value: "english",
|
||||
Usage: "language for the greeting",
|
||||
},
|
||||
},
|
||||
Before: func(_ *cli.Context) error { return nil },
|
||||
},
|
||||
}
|
||||
a.Run([]string{"", "foo", "--lang", "spanish", "abcd"})
|
||||
|
||||
expect(t, context.Args().Get(0), "abcd")
|
||||
expect(t, context.String("lang"), "spanish")
|
||||
}
|
||||
|
||||
func TestApp_CommandWithFlagBeforeTerminator(t *testing.T) {
|
||||
var parsedOption string
|
||||
var args []string
|
||||
|
||||
app := cli.NewApp()
|
||||
command := cli.Command{
|
||||
Name: "cmd",
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{Name: "option", Value: "", Usage: "some option"},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
parsedOption = c.String("option")
|
||||
args = c.Args()
|
||||
},
|
||||
}
|
||||
app.Commands = []cli.Command{command}
|
||||
|
||||
app.Run([]string{"", "cmd", "my-arg", "--option", "my-option", "--", "--notARealFlag"})
|
||||
|
||||
expect(t, parsedOption, "my-option")
|
||||
expect(t, args[0], "my-arg")
|
||||
expect(t, args[1], "--")
|
||||
expect(t, args[2], "--notARealFlag")
|
||||
}
|
||||
|
||||
func TestApp_CommandWithNoFlagBeforeTerminator(t *testing.T) {
|
||||
var args []string
|
||||
|
||||
app := cli.NewApp()
|
||||
command := cli.Command{
|
||||
Name: "cmd",
|
||||
Action: func(c *cli.Context) {
|
||||
args = c.Args()
|
||||
},
|
||||
}
|
||||
app.Commands = []cli.Command{command}
|
||||
|
||||
app.Run([]string{"", "cmd", "my-arg", "--", "notAFlagAtAll"})
|
||||
|
||||
expect(t, args[0], "my-arg")
|
||||
expect(t, args[1], "--")
|
||||
expect(t, args[2], "notAFlagAtAll")
|
||||
}
|
||||
|
||||
func TestApp_Float64Flag(t *testing.T) {
|
||||
var meters float64
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Flags = []cli.Flag{
|
||||
cli.Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"},
|
||||
}
|
||||
app.Action = func(c *cli.Context) {
|
||||
meters = c.Float64("height")
|
||||
}
|
||||
|
||||
app.Run([]string{"", "--height", "1.93"})
|
||||
expect(t, meters, 1.93)
|
||||
}
|
||||
|
||||
func TestApp_ParseSliceFlags(t *testing.T) {
|
||||
var parsedOption, firstArg string
|
||||
var parsedIntSlice []int
|
||||
var parsedStringSlice []string
|
||||
|
||||
app := cli.NewApp()
|
||||
command := cli.Command{
|
||||
Name: "cmd",
|
||||
Flags: []cli.Flag{
|
||||
cli.IntSliceFlag{Name: "p", Value: &cli.IntSlice{}, Usage: "set one or more ip addr"},
|
||||
cli.StringSliceFlag{Name: "ip", Value: &cli.StringSlice{}, Usage: "set one or more ports to open"},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
parsedIntSlice = c.IntSlice("p")
|
||||
parsedStringSlice = c.StringSlice("ip")
|
||||
parsedOption = c.String("option")
|
||||
firstArg = c.Args().First()
|
||||
},
|
||||
}
|
||||
app.Commands = []cli.Command{command}
|
||||
|
||||
app.Run([]string{"", "cmd", "my-arg", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"})
|
||||
|
||||
IntsEquals := func(a, b []int) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i, v := range a {
|
||||
if v != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
StrsEquals := func(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i, v := range a {
|
||||
if v != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
var expectedIntSlice = []int{22, 80}
|
||||
var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"}
|
||||
|
||||
if !IntsEquals(parsedIntSlice, expectedIntSlice) {
|
||||
t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice)
|
||||
}
|
||||
|
||||
if !StrsEquals(parsedStringSlice, expectedStringSlice) {
|
||||
t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApp_DefaultStdout(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
|
||||
if app.Writer != os.Stdout {
|
||||
t.Error("Default output writer not set.")
|
||||
}
|
||||
}
|
||||
|
||||
type mockWriter struct {
|
||||
written []byte
|
||||
}
|
||||
|
||||
func (fw *mockWriter) Write(p []byte) (n int, err error) {
|
||||
if fw.written == nil {
|
||||
fw.written = p
|
||||
} else {
|
||||
fw.written = append(fw.written, p...)
|
||||
}
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (fw *mockWriter) GetWritten() (b []byte) {
|
||||
return fw.written
|
||||
}
|
||||
|
||||
func TestApp_SetStdout(t *testing.T) {
|
||||
w := &mockWriter{}
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Name = "test"
|
||||
app.Writer = w
|
||||
|
||||
err := app.Run([]string{"help"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Run error: %s", err)
|
||||
}
|
||||
|
||||
if len(w.written) == 0 {
|
||||
t.Error("App did not write output to desired writer.")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApp_BeforeFunc(t *testing.T) {
|
||||
beforeRun, subcommandRun := false, false
|
||||
beforeError := fmt.Errorf("fail")
|
||||
var err error
|
||||
|
||||
app := cli.NewApp()
|
||||
|
||||
app.Before = func(c *cli.Context) error {
|
||||
beforeRun = true
|
||||
s := c.String("opt")
|
||||
if s == "fail" {
|
||||
return beforeError
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
app.Commands = []cli.Command{
|
||||
cli.Command{
|
||||
Name: "sub",
|
||||
Action: func(c *cli.Context) {
|
||||
subcommandRun = true
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.StringFlag{Name: "opt"},
|
||||
}
|
||||
|
||||
// run with the Before() func succeeding
|
||||
err = app.Run([]string{"command", "--opt", "succeed", "sub"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Run error: %s", err)
|
||||
}
|
||||
|
||||
if beforeRun == false {
|
||||
t.Errorf("Before() not executed when expected")
|
||||
}
|
||||
|
||||
if subcommandRun == false {
|
||||
t.Errorf("Subcommand not executed when expected")
|
||||
}
|
||||
|
||||
// reset
|
||||
beforeRun, subcommandRun = false, false
|
||||
|
||||
// run with the Before() func failing
|
||||
err = app.Run([]string{"command", "--opt", "fail", "sub"})
|
||||
|
||||
// should be the same error produced by the Before func
|
||||
if err != beforeError {
|
||||
t.Errorf("Run error expected, but not received")
|
||||
}
|
||||
|
||||
if beforeRun == false {
|
||||
t.Errorf("Before() not executed when expected")
|
||||
}
|
||||
|
||||
if subcommandRun == true {
|
||||
t.Errorf("Subcommand executed when NOT expected")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestAppNoHelpFlag(t *testing.T) {
|
||||
oldFlag := cli.HelpFlag
|
||||
defer func() {
|
||||
cli.HelpFlag = oldFlag
|
||||
}()
|
||||
|
||||
cli.HelpFlag = cli.BoolFlag{}
|
||||
|
||||
app := cli.NewApp()
|
||||
err := app.Run([]string{"test", "-h"})
|
||||
|
||||
if err != flag.ErrHelp {
|
||||
t.Errorf("expected error about missing help flag, but got: %s (%T)", err, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppHelpPrinter(t *testing.T) {
|
||||
oldPrinter := cli.HelpPrinter
|
||||
defer func() {
|
||||
cli.HelpPrinter = oldPrinter
|
||||
}()
|
||||
|
||||
var wasCalled = false
|
||||
cli.HelpPrinter = func(template string, data interface{}) {
|
||||
wasCalled = true
|
||||
}
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Run([]string{"-h"})
|
||||
|
||||
if wasCalled == false {
|
||||
t.Errorf("Help printer expected to be called, but was not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppVersionPrinter(t *testing.T) {
|
||||
oldPrinter := cli.VersionPrinter
|
||||
defer func() {
|
||||
cli.VersionPrinter = oldPrinter
|
||||
}()
|
||||
|
||||
var wasCalled = false
|
||||
cli.VersionPrinter = func(c *cli.Context) {
|
||||
wasCalled = true
|
||||
}
|
||||
|
||||
app := cli.NewApp()
|
||||
ctx := cli.NewContext(app, nil, nil)
|
||||
cli.ShowVersion(ctx)
|
||||
|
||||
if wasCalled == false {
|
||||
t.Errorf("Version printer expected to be called, but was not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppCommandNotFound(t *testing.T) {
|
||||
beforeRun, subcommandRun := false, false
|
||||
app := cli.NewApp()
|
||||
|
||||
app.CommandNotFound = func(c *cli.Context, command string) {
|
||||
beforeRun = true
|
||||
}
|
||||
|
||||
app.Commands = []cli.Command{
|
||||
cli.Command{
|
||||
Name: "bar",
|
||||
Action: func(c *cli.Context) {
|
||||
subcommandRun = true
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Run([]string{"command", "foo"})
|
||||
|
||||
expect(t, beforeRun, true)
|
||||
expect(t, subcommandRun, false)
|
||||
}
|
||||
|
||||
func TestGlobalFlagsInSubcommands(t *testing.T) {
|
||||
subcommandRun := false
|
||||
app := cli.NewApp()
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.BoolFlag{Name: "debug, d", Usage: "Enable debugging"},
|
||||
}
|
||||
|
||||
app.Commands = []cli.Command{
|
||||
cli.Command{
|
||||
Name: "foo",
|
||||
Subcommands: []cli.Command{
|
||||
{
|
||||
Name: "bar",
|
||||
Action: func(c *cli.Context) {
|
||||
if c.GlobalBool("debug") {
|
||||
subcommandRun = true
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Run([]string{"command", "-d", "foo", "bar"})
|
||||
|
||||
expect(t, subcommandRun, true)
|
||||
}
|
13
Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/bash_autocomplete
generated
vendored
13
Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/bash_autocomplete
generated
vendored
|
@ -1,13 +0,0 @@
|
|||
#! /bin/bash
|
||||
|
||||
_cli_bash_autocomplete() {
|
||||
local cur prev opts base
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
return 0
|
||||
}
|
||||
|
||||
complete -F _cli_bash_autocomplete $PROG
|
5
Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
generated
vendored
5
Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
generated
vendored
|
@ -1,5 +0,0 @@
|
|||
autoload -U compinit && compinit
|
||||
autoload -U bashcompinit && bashcompinit
|
||||
|
||||
script_dir=$(dirname $0)
|
||||
source ${script_dir}/bash_autocomplete
|
19
Godeps/_workspace/src/github.com/codegangsta/cli/cli.go
generated
vendored
19
Godeps/_workspace/src/github.com/codegangsta/cli/cli.go
generated
vendored
|
@ -1,19 +0,0 @@
|
|||
// Package cli provides a minimal framework for creating and organizing command line
|
||||
// Go applications. cli is designed to be easy to understand and write, the most simple
|
||||
// cli application can be written as follows:
|
||||
// func main() {
|
||||
// cli.NewApp().Run(os.Args)
|
||||
// }
|
||||
//
|
||||
// Of course this application does not do much, so let's make this an actual application:
|
||||
// func main() {
|
||||
// app := cli.NewApp()
|
||||
// app.Name = "greet"
|
||||
// app.Usage = "say a greeting"
|
||||
// app.Action = func(c *cli.Context) {
|
||||
// println("Greetings")
|
||||
// }
|
||||
//
|
||||
// app.Run(os.Args)
|
||||
// }
|
||||
package cli
|
100
Godeps/_workspace/src/github.com/codegangsta/cli/cli_test.go
generated
vendored
100
Godeps/_workspace/src/github.com/codegangsta/cli/cli_test.go
generated
vendored
|
@ -1,100 +0,0 @@
|
|||
package cli_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
app := cli.NewApp()
|
||||
app.Name = "todo"
|
||||
app.Usage = "task list on the command line"
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "add",
|
||||
ShortName: "a",
|
||||
Usage: "add a task to the list",
|
||||
Action: func(c *cli.Context) {
|
||||
println("added task: ", c.Args().First())
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "complete",
|
||||
ShortName: "c",
|
||||
Usage: "complete a task on the list",
|
||||
Action: func(c *cli.Context) {
|
||||
println("completed task: ", c.Args().First())
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Run(os.Args)
|
||||
}
|
||||
|
||||
func ExampleSubcommand() {
|
||||
app := cli.NewApp()
|
||||
app.Name = "say"
|
||||
app.Commands = []cli.Command{
|
||||
{
|
||||
Name: "hello",
|
||||
ShortName: "hi",
|
||||
Usage: "use it to see a description",
|
||||
Description: "This is how we describe hello the function",
|
||||
Subcommands: []cli.Command{
|
||||
{
|
||||
Name: "english",
|
||||
ShortName: "en",
|
||||
Usage: "sends a greeting in english",
|
||||
Description: "greets someone in english",
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Value: "Bob",
|
||||
Usage: "Name of the person to greet",
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
println("Hello, ", c.String("name"))
|
||||
},
|
||||
}, {
|
||||
Name: "spanish",
|
||||
ShortName: "sp",
|
||||
Usage: "sends a greeting in spanish",
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "surname",
|
||||
Value: "Jones",
|
||||
Usage: "Surname of the person to greet",
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
println("Hola, ", c.String("surname"))
|
||||
},
|
||||
}, {
|
||||
Name: "french",
|
||||
ShortName: "fr",
|
||||
Usage: "sends a greeting in french",
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "nickname",
|
||||
Value: "Stevie",
|
||||
Usage: "Nickname of the person to greet",
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) {
|
||||
println("Bonjour, ", c.String("nickname"))
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
Name: "bye",
|
||||
Usage: "says goodbye",
|
||||
Action: func(c *cli.Context) {
|
||||
println("bye")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app.Run(os.Args)
|
||||
}
|
156
Godeps/_workspace/src/github.com/codegangsta/cli/command.go
generated
vendored
156
Godeps/_workspace/src/github.com/codegangsta/cli/command.go
generated
vendored
|
@ -1,156 +0,0 @@
|
|||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Command is a subcommand for a cli.App.
|
||||
type Command struct {
|
||||
// The name of the command
|
||||
Name string
|
||||
// short name of the command. Typically one character
|
||||
ShortName string
|
||||
// A short description of the usage of this command
|
||||
Usage string
|
||||
// A longer explanation of how the command works
|
||||
Description string
|
||||
// The function to call when checking for bash command completions
|
||||
BashComplete func(context *Context)
|
||||
// An action to execute before any sub-subcommands are run, but after the context is ready
|
||||
// If a non-nil error is returned, no sub-subcommands are run
|
||||
Before func(context *Context) error
|
||||
// The function to call when this command is invoked
|
||||
Action func(context *Context)
|
||||
// List of child commands
|
||||
Subcommands []Command
|
||||
// List of flags to parse
|
||||
Flags []Flag
|
||||
// Treat all flags as normal arguments if true
|
||||
SkipFlagParsing bool
|
||||
// Boolean to hide built-in help command
|
||||
HideHelp bool
|
||||
}
|
||||
|
||||
// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
|
||||
func (c Command) Run(ctx *Context) error {
|
||||
|
||||
if len(c.Subcommands) > 0 || c.Before != nil {
|
||||
return c.startApp(ctx)
|
||||
}
|
||||
|
||||
if !c.HideHelp && (HelpFlag != BoolFlag{}) {
|
||||
// append help to flags
|
||||
c.Flags = append(
|
||||
c.Flags,
|
||||
HelpFlag,
|
||||
)
|
||||
}
|
||||
|
||||
if ctx.App.EnableBashCompletion {
|
||||
c.Flags = append(c.Flags, BashCompletionFlag)
|
||||
}
|
||||
|
||||
set := flagSet(c.Name, c.Flags)
|
||||
set.SetOutput(ioutil.Discard)
|
||||
|
||||
firstFlagIndex := -1
|
||||
terminatorIndex := -1
|
||||
for index, arg := range ctx.Args() {
|
||||
if arg == "--" {
|
||||
terminatorIndex = index
|
||||
break
|
||||
} else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
|
||||
firstFlagIndex = index
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
if firstFlagIndex > -1 && !c.SkipFlagParsing {
|
||||
args := ctx.Args()
|
||||
regularArgs := make([]string, len(args[1:firstFlagIndex]))
|
||||
copy(regularArgs, args[1:firstFlagIndex])
|
||||
|
||||
var flagArgs []string
|
||||
if terminatorIndex > -1 {
|
||||
flagArgs = args[firstFlagIndex:terminatorIndex]
|
||||
regularArgs = append(regularArgs, args[terminatorIndex:]...)
|
||||
} else {
|
||||
flagArgs = args[firstFlagIndex:]
|
||||
}
|
||||
|
||||
err = set.Parse(append(flagArgs, regularArgs...))
|
||||
} else {
|
||||
err = set.Parse(ctx.Args().Tail())
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprint(ctx.App.Writer, "Incorrect Usage.\n\n")
|
||||
ShowCommandHelp(ctx, c.Name)
|
||||
fmt.Fprintln(ctx.App.Writer)
|
||||
return err
|
||||
}
|
||||
|
||||
nerr := normalizeFlags(c.Flags, set)
|
||||
if nerr != nil {
|
||||
fmt.Fprintln(ctx.App.Writer, nerr)
|
||||
fmt.Fprintln(ctx.App.Writer)
|
||||
ShowCommandHelp(ctx, c.Name)
|
||||
fmt.Fprintln(ctx.App.Writer)
|
||||
return nerr
|
||||
}
|
||||
context := NewContext(ctx.App, set, ctx.globalSet)
|
||||
|
||||
if checkCommandCompletions(context, c.Name) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if checkCommandHelp(context, c.Name) {
|
||||
return nil
|
||||
}
|
||||
context.Command = c
|
||||
c.Action(context)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Returns true if Command.Name or Command.ShortName matches given name
|
||||
func (c Command) HasName(name string) bool {
|
||||
return c.Name == name || c.ShortName == name
|
||||
}
|
||||
|
||||
func (c Command) startApp(ctx *Context) error {
|
||||
app := NewApp()
|
||||
|
||||
// set the name and usage
|
||||
app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
|
||||
if c.Description != "" {
|
||||
app.Usage = c.Description
|
||||
} else {
|
||||
app.Usage = c.Usage
|
||||
}
|
||||
|
||||
// set CommandNotFound
|
||||
app.CommandNotFound = ctx.App.CommandNotFound
|
||||
|
||||
// set the flags and commands
|
||||
app.Commands = c.Subcommands
|
||||
app.Flags = c.Flags
|
||||
app.HideHelp = c.HideHelp
|
||||
|
||||
// bash completion
|
||||
app.EnableBashCompletion = ctx.App.EnableBashCompletion
|
||||
if c.BashComplete != nil {
|
||||
app.BashComplete = c.BashComplete
|
||||
}
|
||||
|
||||
// set the actions
|
||||
app.Before = c.Before
|
||||
if c.Action != nil {
|
||||
app.Action = c.Action
|
||||
} else {
|
||||
app.Action = helpSubcommand.Action
|
||||
}
|
||||
|
||||
return app.RunAsSubcommand(ctx)
|
||||
}
|
49
Godeps/_workspace/src/github.com/codegangsta/cli/command_test.go
generated
vendored
49
Godeps/_workspace/src/github.com/codegangsta/cli/command_test.go
generated
vendored
|
@ -1,49 +0,0 @@
|
|||
package cli_test
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"testing"
|
||||
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func TestCommandDoNotIgnoreFlags(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"blah", "blah", "-break"}
|
||||
set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, set)
|
||||
|
||||
command := cli.Command{
|
||||
Name: "test-cmd",
|
||||
ShortName: "tc",
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(_ *cli.Context) {},
|
||||
}
|
||||
err := command.Run(c)
|
||||
|
||||
expect(t, err.Error(), "flag provided but not defined: -break")
|
||||
}
|
||||
|
||||
func TestCommandIgnoreFlags(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"blah", "blah"}
|
||||
set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, set)
|
||||
|
||||
command := cli.Command{
|
||||
Name: "test-cmd",
|
||||
ShortName: "tc",
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(_ *cli.Context) {},
|
||||
SkipFlagParsing: true,
|
||||
}
|
||||
err := command.Run(c)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
339
Godeps/_workspace/src/github.com/codegangsta/cli/context.go
generated
vendored
339
Godeps/_workspace/src/github.com/codegangsta/cli/context.go
generated
vendored
|
@ -1,339 +0,0 @@
|
|||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Context is a type that is passed through to
|
||||
// each Handler action in a cli application. Context
|
||||
// can be used to retrieve context-specific Args and
|
||||
// parsed command-line options.
|
||||
type Context struct {
|
||||
App *App
|
||||
Command Command
|
||||
flagSet *flag.FlagSet
|
||||
globalSet *flag.FlagSet
|
||||
setFlags map[string]bool
|
||||
globalSetFlags map[string]bool
|
||||
}
|
||||
|
||||
// Creates a new context. For use in when invoking an App or Command action.
|
||||
func NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {
|
||||
return &Context{App: app, flagSet: set, globalSet: globalSet}
|
||||
}
|
||||
|
||||
// Looks up the value of a local int flag, returns 0 if no int flag exists
|
||||
func (c *Context) Int(name string) int {
|
||||
return lookupInt(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists
|
||||
func (c *Context) Duration(name string) time.Duration {
|
||||
return lookupDuration(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local float64 flag, returns 0 if no float64 flag exists
|
||||
func (c *Context) Float64(name string) float64 {
|
||||
return lookupFloat64(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local bool flag, returns false if no bool flag exists
|
||||
func (c *Context) Bool(name string) bool {
|
||||
return lookupBool(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local boolT flag, returns false if no bool flag exists
|
||||
func (c *Context) BoolT(name string) bool {
|
||||
return lookupBoolT(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local string flag, returns "" if no string flag exists
|
||||
func (c *Context) String(name string) string {
|
||||
return lookupString(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local string slice flag, returns nil if no string slice flag exists
|
||||
func (c *Context) StringSlice(name string) []string {
|
||||
return lookupStringSlice(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local int slice flag, returns nil if no int slice flag exists
|
||||
func (c *Context) IntSlice(name string) []int {
|
||||
return lookupIntSlice(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a local generic flag, returns nil if no generic flag exists
|
||||
func (c *Context) Generic(name string) interface{} {
|
||||
return lookupGeneric(name, c.flagSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global int flag, returns 0 if no int flag exists
|
||||
func (c *Context) GlobalInt(name string) int {
|
||||
return lookupInt(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists
|
||||
func (c *Context) GlobalDuration(name string) time.Duration {
|
||||
return lookupDuration(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global bool flag, returns false if no bool flag exists
|
||||
func (c *Context) GlobalBool(name string) bool {
|
||||
return lookupBool(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global string flag, returns "" if no string flag exists
|
||||
func (c *Context) GlobalString(name string) string {
|
||||
return lookupString(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global string slice flag, returns nil if no string slice flag exists
|
||||
func (c *Context) GlobalStringSlice(name string) []string {
|
||||
return lookupStringSlice(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global int slice flag, returns nil if no int slice flag exists
|
||||
func (c *Context) GlobalIntSlice(name string) []int {
|
||||
return lookupIntSlice(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Looks up the value of a global generic flag, returns nil if no generic flag exists
|
||||
func (c *Context) GlobalGeneric(name string) interface{} {
|
||||
return lookupGeneric(name, c.globalSet)
|
||||
}
|
||||
|
||||
// Determines if the flag was actually set
|
||||
func (c *Context) IsSet(name string) bool {
|
||||
if c.setFlags == nil {
|
||||
c.setFlags = make(map[string]bool)
|
||||
c.flagSet.Visit(func(f *flag.Flag) {
|
||||
c.setFlags[f.Name] = true
|
||||
})
|
||||
}
|
||||
return c.setFlags[name] == true
|
||||
}
|
||||
|
||||
// Determines if the global flag was actually set
|
||||
func (c *Context) GlobalIsSet(name string) bool {
|
||||
if c.globalSetFlags == nil {
|
||||
c.globalSetFlags = make(map[string]bool)
|
||||
c.globalSet.Visit(func(f *flag.Flag) {
|
||||
c.globalSetFlags[f.Name] = true
|
||||
})
|
||||
}
|
||||
return c.globalSetFlags[name] == true
|
||||
}
|
||||
|
||||
// Returns a slice of flag names used in this context.
|
||||
func (c *Context) FlagNames() (names []string) {
|
||||
for _, flag := range c.Command.Flags {
|
||||
name := strings.Split(flag.getName(), ",")[0]
|
||||
if name == "help" {
|
||||
continue
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Returns a slice of global flag names used by the app.
|
||||
func (c *Context) GlobalFlagNames() (names []string) {
|
||||
for _, flag := range c.App.Flags {
|
||||
name := strings.Split(flag.getName(), ",")[0]
|
||||
if name == "help" || name == "version" {
|
||||
continue
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Args []string
|
||||
|
||||
// Returns the command line arguments associated with the context.
|
||||
func (c *Context) Args() Args {
|
||||
args := Args(c.flagSet.Args())
|
||||
return args
|
||||
}
|
||||
|
||||
// Returns the nth argument, or else a blank string
|
||||
func (a Args) Get(n int) string {
|
||||
if len(a) > n {
|
||||
return a[n]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns the first argument, or else a blank string
|
||||
func (a Args) First() string {
|
||||
return a.Get(0)
|
||||
}
|
||||
|
||||
// Return the rest of the arguments (not the first one)
|
||||
// or else an empty string slice
|
||||
func (a Args) Tail() []string {
|
||||
if len(a) >= 2 {
|
||||
return []string(a)[1:]
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
|
||||
// Checks if there are any arguments present
|
||||
func (a Args) Present() bool {
|
||||
return len(a) != 0
|
||||
}
|
||||
|
||||
// Swaps arguments at the given indexes
|
||||
func (a Args) Swap(from, to int) error {
|
||||
if from >= len(a) || to >= len(a) {
|
||||
return errors.New("index out of range")
|
||||
}
|
||||
a[from], a[to] = a[to], a[from]
|
||||
return nil
|
||||
}
|
||||
|
||||
func lookupInt(name string, set *flag.FlagSet) int {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
val, err := strconv.Atoi(f.Value.String())
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func lookupDuration(name string, set *flag.FlagSet) time.Duration {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
val, err := time.ParseDuration(f.Value.String())
|
||||
if err == nil {
|
||||
return val
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func lookupFloat64(name string, set *flag.FlagSet) float64 {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
val, err := strconv.ParseFloat(f.Value.String(), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func lookupString(name string, set *flag.FlagSet) string {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
return f.Value.String()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func lookupStringSlice(name string, set *flag.FlagSet) []string {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
return (f.Value.(*StringSlice)).Value()
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func lookupIntSlice(name string, set *flag.FlagSet) []int {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
return (f.Value.(*IntSlice)).Value()
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func lookupGeneric(name string, set *flag.FlagSet) interface{} {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
return f.Value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lookupBool(name string, set *flag.FlagSet) bool {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
val, err := strconv.ParseBool(f.Value.String())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func lookupBoolT(name string, set *flag.FlagSet) bool {
|
||||
f := set.Lookup(name)
|
||||
if f != nil {
|
||||
val, err := strconv.ParseBool(f.Value.String())
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
|
||||
switch ff.Value.(type) {
|
||||
case *StringSlice:
|
||||
default:
|
||||
set.Set(name, ff.Value.String())
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
|
||||
visited := make(map[string]bool)
|
||||
set.Visit(func(f *flag.Flag) {
|
||||
visited[f.Name] = true
|
||||
})
|
||||
for _, f := range flags {
|
||||
parts := strings.Split(f.getName(), ",")
|
||||
if len(parts) == 1 {
|
||||
continue
|
||||
}
|
||||
var ff *flag.Flag
|
||||
for _, name := range parts {
|
||||
name = strings.Trim(name, " ")
|
||||
if visited[name] {
|
||||
if ff != nil {
|
||||
return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
|
||||
}
|
||||
ff = set.Lookup(name)
|
||||
}
|
||||
}
|
||||
if ff == nil {
|
||||
continue
|
||||
}
|
||||
for _, name := range parts {
|
||||
name = strings.Trim(name, " ")
|
||||
if !visited[name] {
|
||||
copyFlag(name, ff, set)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
99
Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go
generated
vendored
99
Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go
generated
vendored
|
@ -1,99 +0,0 @@
|
|||
package cli_test
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
func TestNewContext(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Int("myflag", 12, "doc")
|
||||
globalSet := flag.NewFlagSet("test", 0)
|
||||
globalSet.Int("myflag", 42, "doc")
|
||||
command := cli.Command{Name: "mycommand"}
|
||||
c := cli.NewContext(nil, set, globalSet)
|
||||
c.Command = command
|
||||
expect(t, c.Int("myflag"), 12)
|
||||
expect(t, c.GlobalInt("myflag"), 42)
|
||||
expect(t, c.Command.Name, "mycommand")
|
||||
}
|
||||
|
||||
func TestContext_Int(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Int("myflag", 12, "doc")
|
||||
c := cli.NewContext(nil, set, set)
|
||||
expect(t, c.Int("myflag"), 12)
|
||||
}
|
||||
|
||||
func TestContext_Duration(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Duration("myflag", time.Duration(12*time.Second), "doc")
|
||||
c := cli.NewContext(nil, set, set)
|
||||
expect(t, c.Duration("myflag"), time.Duration(12*time.Second))
|
||||
}
|
||||
|
||||
func TestContext_String(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.String("myflag", "hello world", "doc")
|
||||
c := cli.NewContext(nil, set, set)
|
||||
expect(t, c.String("myflag"), "hello world")
|
||||
}
|
||||
|
||||
func TestContext_Bool(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Bool("myflag", false, "doc")
|
||||
c := cli.NewContext(nil, set, set)
|
||||
expect(t, c.Bool("myflag"), false)
|
||||
}
|
||||
|
||||
func TestContext_BoolT(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Bool("myflag", true, "doc")
|
||||
c := cli.NewContext(nil, set, set)
|
||||
expect(t, c.BoolT("myflag"), true)
|
||||
}
|
||||
|
||||
func TestContext_Args(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Bool("myflag", false, "doc")
|
||||
c := cli.NewContext(nil, set, set)
|
||||
set.Parse([]string{"--myflag", "bat", "baz"})
|
||||
expect(t, len(c.Args()), 2)
|
||||
expect(t, c.Bool("myflag"), true)
|
||||
}
|
||||
|
||||
func TestContext_IsSet(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Bool("myflag", false, "doc")
|
||||
set.String("otherflag", "hello world", "doc")
|
||||
globalSet := flag.NewFlagSet("test", 0)
|
||||
globalSet.Bool("myflagGlobal", true, "doc")
|
||||
c := cli.NewContext(nil, set, globalSet)
|
||||
set.Parse([]string{"--myflag", "bat", "baz"})
|
||||
globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
|
||||
expect(t, c.IsSet("myflag"), true)
|
||||
expect(t, c.IsSet("otherflag"), false)
|
||||
expect(t, c.IsSet("bogusflag"), false)
|
||||
expect(t, c.IsSet("myflagGlobal"), false)
|
||||
}
|
||||
|
||||
func TestContext_GlobalIsSet(t *testing.T) {
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Bool("myflag", false, "doc")
|
||||
set.String("otherflag", "hello world", "doc")
|
||||
globalSet := flag.NewFlagSet("test", 0)
|
||||
globalSet.Bool("myflagGlobal", true, "doc")
|
||||
globalSet.Bool("myflagGlobalUnset", true, "doc")
|
||||
c := cli.NewContext(nil, set, globalSet)
|
||||
set.Parse([]string{"--myflag", "bat", "baz"})
|
||||
globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
|
||||
expect(t, c.GlobalIsSet("myflag"), false)
|
||||
expect(t, c.GlobalIsSet("otherflag"), false)
|
||||
expect(t, c.GlobalIsSet("bogusflag"), false)
|
||||
expect(t, c.GlobalIsSet("myflagGlobal"), true)
|
||||
expect(t, c.GlobalIsSet("myflagGlobalUnset"), false)
|
||||
expect(t, c.GlobalIsSet("bogusGlobal"), false)
|
||||
}
|
454
Godeps/_workspace/src/github.com/codegangsta/cli/flag.go
generated
vendored
454
Godeps/_workspace/src/github.com/codegangsta/cli/flag.go
generated
vendored
|
@ -1,454 +0,0 @@
|
|||
package cli
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This flag enables bash-completion for all commands and subcommands
|
||||
var BashCompletionFlag = BoolFlag{
|
||||
Name: "generate-bash-completion",
|
||||
}
|
||||
|
||||
// This flag prints the version for the application
|
||||
var VersionFlag = BoolFlag{
|
||||
Name: "version, v",
|
||||
Usage: "print the version",
|
||||
}
|
||||
|
||||
// This flag prints the help for all commands and subcommands
|
||||
// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
|
||||
// unless HideHelp is set to true)
|
||||
var HelpFlag = BoolFlag{
|
||||
Name: "help, h",
|
||||
Usage: "show help",
|
||||
}
|
||||
|
||||
// Flag is a common interface related to parsing flags in cli.
|
||||
// For more advanced flag parsing techniques, it is recomended that
|
||||
// this interface be implemented.
|
||||
type Flag interface {
|
||||
fmt.Stringer
|
||||
// Apply Flag settings to the given flag set
|
||||
Apply(*flag.FlagSet)
|
||||
getName() string
|
||||
}
|
||||
|
||||
func flagSet(name string, flags []Flag) *flag.FlagSet {
|
||||
set := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
|
||||
for _, f := range flags {
|
||||
f.Apply(set)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func eachName(longName string, fn func(string)) {
|
||||
parts := strings.Split(longName, ",")
|
||||
for _, name := range parts {
|
||||
name = strings.Trim(name, " ")
|
||||
fn(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Generic is a generic parseable type identified by a specific flag
|
||||
type Generic interface {
|
||||
Set(value string) error
|
||||
String() string
|
||||
}
|
||||
|
||||
// GenericFlag is the flag type for types implementing Generic
|
||||
type GenericFlag struct {
|
||||
Name string
|
||||
Value Generic
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
// String returns the string representation of the generic flag to display the
|
||||
// help text to the user (uses the String() method of the generic flag to show
|
||||
// the value)
|
||||
func (f GenericFlag) String() string {
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s%s \"%v\"\t%v", prefixFor(f.Name), f.Name, f.Value, f.Usage))
|
||||
}
|
||||
|
||||
// Apply takes the flagset and calls Set on the generic flag with the value
|
||||
// provided by the user for parsing by the flag
|
||||
func (f GenericFlag) Apply(set *flag.FlagSet) {
|
||||
val := f.Value
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
val.Set(envVal)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Var(f.Value, name, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f GenericFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type StringSlice []string
|
||||
|
||||
func (f *StringSlice) Set(value string) error {
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *StringSlice) String() string {
|
||||
return fmt.Sprintf("%s", *f)
|
||||
}
|
||||
|
||||
func (f *StringSlice) Value() []string {
|
||||
return *f
|
||||
}
|
||||
|
||||
type StringSliceFlag struct {
|
||||
Name string
|
||||
Value *StringSlice
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f StringSliceFlag) String() string {
|
||||
firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
|
||||
pref := prefixFor(firstName)
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
|
||||
}
|
||||
|
||||
func (f StringSliceFlag) Apply(set *flag.FlagSet) {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
newVal := &StringSlice{}
|
||||
for _, s := range strings.Split(envVal, ",") {
|
||||
s = strings.TrimSpace(s)
|
||||
newVal.Set(s)
|
||||
}
|
||||
f.Value = newVal
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Var(f.Value, name, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f StringSliceFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type IntSlice []int
|
||||
|
||||
func (f *IntSlice) Set(value string) error {
|
||||
|
||||
tmp, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
*f = append(*f, tmp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *IntSlice) String() string {
|
||||
return fmt.Sprintf("%d", *f)
|
||||
}
|
||||
|
||||
func (f *IntSlice) Value() []int {
|
||||
return *f
|
||||
}
|
||||
|
||||
type IntSliceFlag struct {
|
||||
Name string
|
||||
Value *IntSlice
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f IntSliceFlag) String() string {
|
||||
firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
|
||||
pref := prefixFor(firstName)
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
|
||||
}
|
||||
|
||||
func (f IntSliceFlag) Apply(set *flag.FlagSet) {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
newVal := &IntSlice{}
|
||||
for _, s := range strings.Split(envVal, ",") {
|
||||
s = strings.TrimSpace(s)
|
||||
err := newVal.Set(s)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
}
|
||||
}
|
||||
f.Value = newVal
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Var(f.Value, name, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f IntSliceFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type BoolFlag struct {
|
||||
Name string
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f BoolFlag) String() string {
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
|
||||
}
|
||||
|
||||
func (f BoolFlag) Apply(set *flag.FlagSet) {
|
||||
val := false
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
envValBool, err := strconv.ParseBool(envVal)
|
||||
if err == nil {
|
||||
val = envValBool
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Bool(name, val, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f BoolFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type BoolTFlag struct {
|
||||
Name string
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f BoolTFlag) String() string {
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
|
||||
}
|
||||
|
||||
func (f BoolTFlag) Apply(set *flag.FlagSet) {
|
||||
val := true
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
envValBool, err := strconv.ParseBool(envVal)
|
||||
if err == nil {
|
||||
val = envValBool
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Bool(name, val, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f BoolTFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type StringFlag struct {
|
||||
Name string
|
||||
Value string
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f StringFlag) String() string {
|
||||
var fmtString string
|
||||
fmtString = "%s %v\t%v"
|
||||
|
||||
if len(f.Value) > 0 {
|
||||
fmtString = "%s \"%v\"\t%v"
|
||||
} else {
|
||||
fmtString = "%s %v\t%v"
|
||||
}
|
||||
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))
|
||||
}
|
||||
|
||||
func (f StringFlag) Apply(set *flag.FlagSet) {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
f.Value = envVal
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.String(name, f.Value, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f StringFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type IntFlag struct {
|
||||
Name string
|
||||
Value int
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f IntFlag) String() string {
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
|
||||
}
|
||||
|
||||
func (f IntFlag) Apply(set *flag.FlagSet) {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
envValInt, err := strconv.ParseInt(envVal, 0, 64)
|
||||
if err == nil {
|
||||
f.Value = int(envValInt)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Int(name, f.Value, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f IntFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type DurationFlag struct {
|
||||
Name string
|
||||
Value time.Duration
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f DurationFlag) String() string {
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
|
||||
}
|
||||
|
||||
func (f DurationFlag) Apply(set *flag.FlagSet) {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
envValDuration, err := time.ParseDuration(envVal)
|
||||
if err == nil {
|
||||
f.Value = envValDuration
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Duration(name, f.Value, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f DurationFlag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
type Float64Flag struct {
|
||||
Name string
|
||||
Value float64
|
||||
Usage string
|
||||
EnvVar string
|
||||
}
|
||||
|
||||
func (f Float64Flag) String() string {
|
||||
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
|
||||
}
|
||||
|
||||
func (f Float64Flag) Apply(set *flag.FlagSet) {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal := os.Getenv(envVar); envVal != "" {
|
||||
envValFloat, err := strconv.ParseFloat(envVal, 10)
|
||||
if err == nil {
|
||||
f.Value = float64(envValFloat)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eachName(f.Name, func(name string) {
|
||||
set.Float64(name, f.Value, f.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f Float64Flag) getName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
func prefixFor(name string) (prefix string) {
|
||||
if len(name) == 1 {
|
||||
prefix = "-"
|
||||
} else {
|
||||
prefix = "--"
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func prefixedNames(fullName string) (prefixed string) {
|
||||
parts := strings.Split(fullName, ",")
|
||||
for i, name := range parts {
|
||||
name = strings.Trim(name, " ")
|
||||
prefixed += prefixFor(name) + name
|
||||
if i < len(parts)-1 {
|
||||
prefixed += ", "
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func withEnvHint(envVar, str string) string {
|
||||
envText := ""
|
||||
if envVar != "" {
|
||||
envText = fmt.Sprintf(" [$%s]", strings.Join(strings.Split(envVar, ","), ", $"))
|
||||
}
|
||||
return str + envText
|
||||
}
|
742
Godeps/_workspace/src/github.com/codegangsta/cli/flag_test.go
generated
vendored
742
Godeps/_workspace/src/github.com/codegangsta/cli/flag_test.go
generated
vendored
|
@ -1,742 +0,0 @@
|
|||
package cli_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/codegangsta/cli"
|
||||
)
|
||||
|
||||
var boolFlagTests = []struct {
|
||||
name string
|
||||
expected string
|
||||
}{
|
||||
{"help", "--help\t"},
|
||||
{"h", "-h\t"},
|
||||
}
|
||||
|
||||
func TestBoolFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range boolFlagTests {
|
||||
flag := cli.BoolFlag{Name: test.name}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%s does not match %s", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var stringFlagTests = []struct {
|
||||
name string
|
||||
value string
|
||||
expected string
|
||||
}{
|
||||
{"help", "", "--help \t"},
|
||||
{"h", "", "-h \t"},
|
||||
{"h", "", "-h \t"},
|
||||
{"test", "Something", "--test \"Something\"\t"},
|
||||
}
|
||||
|
||||
func TestStringFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range stringFlagTests {
|
||||
flag := cli.StringFlag{Name: test.name, Value: test.value}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%s does not match %s", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringFlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_FOO", "derp")
|
||||
for _, test := range stringFlagTests {
|
||||
flag := cli.StringFlag{Name: test.name, Value: test.value, EnvVar: "APP_FOO"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_FOO]") {
|
||||
t.Errorf("%s does not end with [$APP_FOO]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var stringSliceFlagTests = []struct {
|
||||
name string
|
||||
value *cli.StringSlice
|
||||
expected string
|
||||
}{
|
||||
{"help", func() *cli.StringSlice {
|
||||
s := &cli.StringSlice{}
|
||||
s.Set("")
|
||||
return s
|
||||
}(), "--help [--help option --help option]\t"},
|
||||
{"h", func() *cli.StringSlice {
|
||||
s := &cli.StringSlice{}
|
||||
s.Set("")
|
||||
return s
|
||||
}(), "-h [-h option -h option]\t"},
|
||||
{"h", func() *cli.StringSlice {
|
||||
s := &cli.StringSlice{}
|
||||
s.Set("")
|
||||
return s
|
||||
}(), "-h [-h option -h option]\t"},
|
||||
{"test", func() *cli.StringSlice {
|
||||
s := &cli.StringSlice{}
|
||||
s.Set("Something")
|
||||
return s
|
||||
}(), "--test [--test option --test option]\t"},
|
||||
}
|
||||
|
||||
func TestStringSliceFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range stringSliceFlagTests {
|
||||
flag := cli.StringSliceFlag{Name: test.name, Value: test.value}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%q does not match %q", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_QWWX", "11,4")
|
||||
for _, test := range stringSliceFlagTests {
|
||||
flag := cli.StringSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_QWWX"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_QWWX]") {
|
||||
t.Errorf("%q does not end with [$APP_QWWX]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var intFlagTests = []struct {
|
||||
name string
|
||||
expected string
|
||||
}{
|
||||
{"help", "--help \"0\"\t"},
|
||||
{"h", "-h \"0\"\t"},
|
||||
}
|
||||
|
||||
func TestIntFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range intFlagTests {
|
||||
flag := cli.IntFlag{Name: test.name}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%s does not match %s", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntFlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_BAR", "2")
|
||||
for _, test := range intFlagTests {
|
||||
flag := cli.IntFlag{Name: test.name, EnvVar: "APP_BAR"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_BAR]") {
|
||||
t.Errorf("%s does not end with [$APP_BAR]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var durationFlagTests = []struct {
|
||||
name string
|
||||
expected string
|
||||
}{
|
||||
{"help", "--help \"0\"\t"},
|
||||
{"h", "-h \"0\"\t"},
|
||||
}
|
||||
|
||||
func TestDurationFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range durationFlagTests {
|
||||
flag := cli.DurationFlag{Name: test.name}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%s does not match %s", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurationFlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_BAR", "2h3m6s")
|
||||
for _, test := range durationFlagTests {
|
||||
flag := cli.DurationFlag{Name: test.name, EnvVar: "APP_BAR"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_BAR]") {
|
||||
t.Errorf("%s does not end with [$APP_BAR]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var intSliceFlagTests = []struct {
|
||||
name string
|
||||
value *cli.IntSlice
|
||||
expected string
|
||||
}{
|
||||
{"help", &cli.IntSlice{}, "--help [--help option --help option]\t"},
|
||||
{"h", &cli.IntSlice{}, "-h [-h option -h option]\t"},
|
||||
{"h", &cli.IntSlice{}, "-h [-h option -h option]\t"},
|
||||
{"test", func() *cli.IntSlice {
|
||||
i := &cli.IntSlice{}
|
||||
i.Set("9")
|
||||
return i
|
||||
}(), "--test [--test option --test option]\t"},
|
||||
}
|
||||
|
||||
func TestIntSliceFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range intSliceFlagTests {
|
||||
flag := cli.IntSliceFlag{Name: test.name, Value: test.value}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%q does not match %q", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_SMURF", "42,3")
|
||||
for _, test := range intSliceFlagTests {
|
||||
flag := cli.IntSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_SMURF"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_SMURF]") {
|
||||
t.Errorf("%q does not end with [$APP_SMURF]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var float64FlagTests = []struct {
|
||||
name string
|
||||
expected string
|
||||
}{
|
||||
{"help", "--help \"0\"\t"},
|
||||
{"h", "-h \"0\"\t"},
|
||||
}
|
||||
|
||||
func TestFloat64FlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range float64FlagTests {
|
||||
flag := cli.Float64Flag{Name: test.name}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%s does not match %s", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloat64FlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_BAZ", "99.4")
|
||||
for _, test := range float64FlagTests {
|
||||
flag := cli.Float64Flag{Name: test.name, EnvVar: "APP_BAZ"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_BAZ]") {
|
||||
t.Errorf("%s does not end with [$APP_BAZ]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var genericFlagTests = []struct {
|
||||
name string
|
||||
value cli.Generic
|
||||
expected string
|
||||
}{
|
||||
{"test", &Parser{"abc", "def"}, "--test \"abc,def\"\ttest flag"},
|
||||
{"t", &Parser{"abc", "def"}, "-t \"abc,def\"\ttest flag"},
|
||||
}
|
||||
|
||||
func TestGenericFlagHelpOutput(t *testing.T) {
|
||||
|
||||
for _, test := range genericFlagTests {
|
||||
flag := cli.GenericFlag{Name: test.name, Value: test.value, Usage: "test flag"}
|
||||
output := flag.String()
|
||||
|
||||
if output != test.expected {
|
||||
t.Errorf("%q does not match %q", output, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_ZAP", "3")
|
||||
for _, test := range genericFlagTests {
|
||||
flag := cli.GenericFlag{Name: test.name, EnvVar: "APP_ZAP"}
|
||||
output := flag.String()
|
||||
|
||||
if !strings.HasSuffix(output, " [$APP_ZAP]") {
|
||||
t.Errorf("%s does not end with [$APP_ZAP]", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMultiString(t *testing.T) {
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{Name: "serve, s"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.String("serve") != "10" {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.String("s") != "10" {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run", "-s", "10"})
|
||||
}
|
||||
|
||||
func TestParseMultiStringFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_COUNT", "20")
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{Name: "count, c", EnvVar: "APP_COUNT"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.String("count") != "20" {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.String("c") != "20" {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiStringFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_COUNT", "20")
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{Name: "count, c", EnvVar: "COMPAT_COUNT,APP_COUNT"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.String("count") != "20" {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.String("c") != "20" {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiStringSlice(t *testing.T) {
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.StringSliceFlag{Name: "serve, s", Value: &cli.StringSlice{}},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.StringSlice("serve"), []string{"10", "20"}) {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.StringSlice("s"), []string{"10", "20"}) {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run", "-s", "10", "-s", "20"})
|
||||
}
|
||||
|
||||
func TestParseMultiStringSliceFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_INTERVALS", "20,30,40")
|
||||
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.StringSliceFlag{Name: "intervals, i", Value: &cli.StringSlice{}, EnvVar: "APP_INTERVALS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiStringSliceFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_INTERVALS", "20,30,40")
|
||||
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.StringSliceFlag{Name: "intervals, i", Value: &cli.StringSlice{}, EnvVar: "COMPAT_INTERVALS,APP_INTERVALS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiInt(t *testing.T) {
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.IntFlag{Name: "serve, s"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Int("serve") != 10 {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Int("s") != 10 {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run", "-s", "10"})
|
||||
}
|
||||
|
||||
func TestParseMultiIntFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_TIMEOUT_SECONDS", "10")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.IntFlag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Int("timeout") != 10 {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Int("t") != 10 {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiIntFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_TIMEOUT_SECONDS", "10")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.IntFlag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Int("timeout") != 10 {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Int("t") != 10 {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiIntSlice(t *testing.T) {
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.IntSliceFlag{Name: "serve, s", Value: &cli.IntSlice{}},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.IntSlice("serve"), []int{10, 20}) {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.IntSlice("s"), []int{10, 20}) {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run", "-s", "10", "-s", "20"})
|
||||
}
|
||||
|
||||
func TestParseMultiIntSliceFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_INTERVALS", "20,30,40")
|
||||
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.IntSliceFlag{Name: "intervals, i", Value: &cli.IntSlice{}, EnvVar: "APP_INTERVALS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiIntSliceFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_INTERVALS", "20,30,40")
|
||||
|
||||
(&cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.IntSliceFlag{Name: "intervals, i", Value: &cli.IntSlice{}, EnvVar: "COMPAT_INTERVALS,APP_INTERVALS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}).Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiFloat64(t *testing.T) {
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.Float64Flag{Name: "serve, s"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Float64("serve") != 10.2 {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Float64("s") != 10.2 {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run", "-s", "10.2"})
|
||||
}
|
||||
|
||||
func TestParseMultiFloat64FromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_TIMEOUT_SECONDS", "15.5")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.Float64Flag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Float64("timeout") != 15.5 {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Float64("t") != 15.5 {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiFloat64FromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_TIMEOUT_SECONDS", "15.5")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.Float64Flag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Float64("timeout") != 15.5 {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Float64("t") != 15.5 {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiBool(t *testing.T) {
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolFlag{Name: "serve, s"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Bool("serve") != true {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.Bool("s") != true {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run", "--serve"})
|
||||
}
|
||||
|
||||
func TestParseMultiBoolFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_DEBUG", "1")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Bool("debug") != true {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if ctx.Bool("d") != true {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiBoolFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_DEBUG", "1")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.Bool("debug") != true {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if ctx.Bool("d") != true {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiBoolT(t *testing.T) {
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolTFlag{Name: "serve, s"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.BoolT("serve") != true {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if ctx.BoolT("s") != true {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run", "--serve"})
|
||||
}
|
||||
|
||||
func TestParseMultiBoolTFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_DEBUG", "0")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolTFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.BoolT("debug") != false {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if ctx.BoolT("d") != false {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseMultiBoolTFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_DEBUG", "0")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolTFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if ctx.BoolT("debug") != false {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if ctx.BoolT("d") != false {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
type Parser [2]string
|
||||
|
||||
func (p *Parser) Set(value string) error {
|
||||
parts := strings.Split(value, ",")
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("invalid format")
|
||||
}
|
||||
|
||||
(*p)[0] = parts[0]
|
||||
(*p)[1] = parts[1]
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Parser) String() string {
|
||||
return fmt.Sprintf("%s,%s", p[0], p[1])
|
||||
}
|
||||
|
||||
func TestParseGeneric(t *testing.T) {
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.GenericFlag{Name: "serve, s", Value: &Parser{}},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"10", "20"}) {
|
||||
t.Errorf("main name not set")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"10", "20"}) {
|
||||
t.Errorf("short name not set")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run", "-s", "10,20"})
|
||||
}
|
||||
|
||||
func TestParseGenericFromEnv(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_SERVE", "20,30")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.GenericFlag{Name: "serve, s", Value: &Parser{}, EnvVar: "APP_SERVE"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"20", "30"}) {
|
||||
t.Errorf("main name not set from env")
|
||||
}
|
||||
if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"20", "30"}) {
|
||||
t.Errorf("short name not set from env")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
||||
|
||||
func TestParseGenericFromEnvCascade(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("APP_FOO", "99,2000")
|
||||
a := cli.App{
|
||||
Flags: []cli.Flag{
|
||||
cli.GenericFlag{Name: "foos", Value: &Parser{}, EnvVar: "COMPAT_FOO,APP_FOO"},
|
||||
},
|
||||
Action: func(ctx *cli.Context) {
|
||||
if !reflect.DeepEqual(ctx.Generic("foos"), &Parser{"99", "2000"}) {
|
||||
t.Errorf("value not set from env")
|
||||
}
|
||||
},
|
||||
}
|
||||
a.Run([]string{"run"})
|
||||
}
|
211
Godeps/_workspace/src/github.com/codegangsta/cli/help.go
generated
vendored
211
Godeps/_workspace/src/github.com/codegangsta/cli/help.go
generated
vendored
|
@ -1,211 +0,0 @@
|
|||
package cli
|
||||
|
||||
import "fmt"
|
||||
|
||||
// The text template for the Default help topic.
|
||||
// cli.go uses text/template to render templates. You can
|
||||
// render custom help text by setting this variable.
|
||||
var AppHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
|
||||
|
||||
VERSION:
|
||||
{{.Version}}{{if or .Author .Email}}
|
||||
|
||||
AUTHOR:{{if .Author}}
|
||||
{{.Author}}{{if .Email}} - <{{.Email}}>{{end}}{{else}}
|
||||
{{.Email}}{{end}}{{end}}
|
||||
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}{{if .Flags}}
|
||||
GLOBAL OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
`
|
||||
|
||||
// The text template for the command help topic.
|
||||
// cli.go uses text/template to render templates. You can
|
||||
// render custom help text by setting this variable.
|
||||
var CommandHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
command {{.Name}}{{if .Flags}} [command options]{{end}} [arguments...]{{if .Description}}
|
||||
|
||||
DESCRIPTION:
|
||||
{{.Description}}{{end}}{{if .Flags}}
|
||||
|
||||
OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}{{ end }}
|
||||
`
|
||||
|
||||
// The text template for the subcommand help topic.
|
||||
// cli.go uses text/template to render templates. You can
|
||||
// render custom help text by setting this variable.
|
||||
var SubcommandHelpTemplate = `NAME:
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.Name}} command{{if .Flags}} [command options]{{end}} [arguments...]
|
||||
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
|
||||
{{end}}{{if .Flags}}
|
||||
OPTIONS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}{{end}}
|
||||
`
|
||||
|
||||
var helpCommand = Command{
|
||||
Name: "help",
|
||||
ShortName: "h",
|
||||
Usage: "Shows a list of commands or help for one command",
|
||||
Action: func(c *Context) {
|
||||
args := c.Args()
|
||||
if args.Present() {
|
||||
ShowCommandHelp(c, args.First())
|
||||
} else {
|
||||
ShowAppHelp(c)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
var helpSubcommand = Command{
|
||||
Name: "help",
|
||||
ShortName: "h",
|
||||
Usage: "Shows a list of commands or help for one command",
|
||||
Action: func(c *Context) {
|
||||
args := c.Args()
|
||||
if args.Present() {
|
||||
ShowCommandHelp(c, args.First())
|
||||
} else {
|
||||
ShowSubcommandHelp(c)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// Prints help for the App
|
||||
type helpPrinter func(templ string, data interface{})
|
||||
|
||||
var HelpPrinter helpPrinter = nil
|
||||
|
||||
// Prints version for the App
|
||||
var VersionPrinter = printVersion
|
||||
|
||||
func ShowAppHelp(c *Context) {
|
||||
HelpPrinter(AppHelpTemplate, c.App)
|
||||
}
|
||||
|
||||
// Prints the list of subcommands as the default app completion method
|
||||
func DefaultAppComplete(c *Context) {
|
||||
for _, command := range c.App.Commands {
|
||||
fmt.Fprintln(c.App.Writer, command.Name)
|
||||
if command.ShortName != "" {
|
||||
fmt.Fprintln(c.App.Writer, command.ShortName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prints help for the given command
|
||||
func ShowCommandHelp(c *Context, command string) {
|
||||
for _, c := range c.App.Commands {
|
||||
if c.HasName(command) {
|
||||
HelpPrinter(CommandHelpTemplate, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if c.App.CommandNotFound != nil {
|
||||
c.App.CommandNotFound(c, command)
|
||||
} else {
|
||||
fmt.Fprintf(c.App.Writer, "No help topic for '%v'\n", command)
|
||||
}
|
||||
}
|
||||
|
||||
// Prints help for the given subcommand
|
||||
func ShowSubcommandHelp(c *Context) {
|
||||
ShowCommandHelp(c, c.Command.Name)
|
||||
}
|
||||
|
||||
// Prints the version number of the App
|
||||
func ShowVersion(c *Context) {
|
||||
VersionPrinter(c)
|
||||
}
|
||||
|
||||
func printVersion(c *Context) {
|
||||
fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
|
||||
}
|
||||
|
||||
// Prints the lists of commands within a given context
|
||||
func ShowCompletions(c *Context) {
|
||||
a := c.App
|
||||
if a != nil && a.BashComplete != nil {
|
||||
a.BashComplete(c)
|
||||
}
|
||||
}
|
||||
|
||||
// Prints the custom completions for a given command
|
||||
func ShowCommandCompletions(ctx *Context, command string) {
|
||||
c := ctx.App.Command(command)
|
||||
if c != nil && c.BashComplete != nil {
|
||||
c.BashComplete(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func checkVersion(c *Context) bool {
|
||||
if c.GlobalBool("version") {
|
||||
ShowVersion(c)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func checkHelp(c *Context) bool {
|
||||
if c.GlobalBool("h") || c.GlobalBool("help") {
|
||||
ShowAppHelp(c)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func checkCommandHelp(c *Context, name string) bool {
|
||||
if c.Bool("h") || c.Bool("help") {
|
||||
ShowCommandHelp(c, name)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func checkSubcommandHelp(c *Context) bool {
|
||||
if c.GlobalBool("h") || c.GlobalBool("help") {
|
||||
ShowSubcommandHelp(c)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func checkCompletions(c *Context) bool {
|
||||
if (c.GlobalBool(BashCompletionFlag.Name) || c.Bool(BashCompletionFlag.Name)) && c.App.EnableBashCompletion {
|
||||
ShowCompletions(c)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func checkCommandCompletions(c *Context, name string) bool {
|
||||
if c.Bool(BashCompletionFlag.Name) && c.App.EnableBashCompletion {
|
||||
ShowCommandCompletions(c, name)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
19
Godeps/_workspace/src/github.com/codegangsta/cli/helpers_test.go
generated
vendored
19
Godeps/_workspace/src/github.com/codegangsta/cli/helpers_test.go
generated
vendored
|
@ -1,19 +0,0 @@
|
|||
package cli_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/* Test Helpers */
|
||||
func expect(t *testing.T, a interface{}, b interface{}) {
|
||||
if a != b {
|
||||
t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
|
||||
}
|
||||
}
|
||||
|
||||
func refute(t *testing.T, a interface{}, b interface{}) {
|
||||
if a == b {
|
||||
t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
|
||||
}
|
||||
}
|
13
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
Normal file
13
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
Copyright 2014 Alan Shreve
|
||||
|
||||
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.
|
23
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/README.md
generated
vendored
Normal file
23
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/README.md
generated
vendored
Normal file
|
@ -0,0 +1,23 @@
|
|||
# mousetrap
|
||||
|
||||
mousetrap is a tiny library that answers a single question.
|
||||
|
||||
On a Windows machine, was the process invoked by someone double clicking on
|
||||
the executable file while browsing in explorer?
|
||||
|
||||
### Motivation
|
||||
|
||||
Windows developers unfamiliar with command line tools will often "double-click"
|
||||
the executable for a tool. Because most CLI tools print the help and then exit
|
||||
when invoked without arguments, this is often very frustrating for those users.
|
||||
|
||||
mousetrap provides a way to detect these invocations so that you can provide
|
||||
more helpful behavior and instructions on how to run the CLI tool. To see what
|
||||
this looks like, both from an organizational and a technical perspective, see
|
||||
https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
|
||||
|
||||
### The interface
|
||||
|
||||
The library exposes a single interface:
|
||||
|
||||
func StartedByExplorer() (bool)
|
15
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
Normal file
15
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
// +build !windows
|
||||
|
||||
package mousetrap
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user
|
||||
// double-clicking on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
//
|
||||
// On non-Windows platforms, it always returns false.
|
||||
func StartedByExplorer() bool {
|
||||
return false
|
||||
}
|
98
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
Normal file
98
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
Normal file
|
@ -0,0 +1,98 @@
|
|||
// +build windows
|
||||
// +build !go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// defined by the Win32 API
|
||||
th32cs_snapprocess uintptr = 0x2
|
||||
)
|
||||
|
||||
var (
|
||||
kernel = syscall.MustLoadDLL("kernel32.dll")
|
||||
CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
|
||||
Process32First = kernel.MustFindProc("Process32FirstW")
|
||||
Process32Next = kernel.MustFindProc("Process32NextW")
|
||||
)
|
||||
|
||||
// ProcessEntry32 structure defined by the Win32 API
|
||||
type processEntry32 struct {
|
||||
dwSize uint32
|
||||
cntUsage uint32
|
||||
th32ProcessID uint32
|
||||
th32DefaultHeapID int
|
||||
th32ModuleID uint32
|
||||
cntThreads uint32
|
||||
th32ParentProcessID uint32
|
||||
pcPriClassBase int32
|
||||
dwFlags uint32
|
||||
szExeFile [syscall.MAX_PATH]uint16
|
||||
}
|
||||
|
||||
func getProcessEntry(pid int) (pe *processEntry32, err error) {
|
||||
snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
|
||||
if snapshot == uintptr(syscall.InvalidHandle) {
|
||||
err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
|
||||
return
|
||||
}
|
||||
defer syscall.CloseHandle(syscall.Handle(snapshot))
|
||||
|
||||
var processEntry processEntry32
|
||||
processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
|
||||
ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32First: %v", e1)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
if processEntry.th32ProcessID == uint32(pid) {
|
||||
pe = &processEntry
|
||||
return
|
||||
}
|
||||
|
||||
ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32Next: %v", e1)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getppid() (pid int, err error) {
|
||||
pe, err := getProcessEntry(os.Getpid())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
pid = int(pe.th32ParentProcessID)
|
||||
return
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
ppid, err := getppid()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pe, err := getProcessEntry(ppid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
name := syscall.UTF16ToString(pe.szExeFile[:])
|
||||
return name == "explorer.exe"
|
||||
}
|
46
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
Normal file
46
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
Normal file
|
@ -0,0 +1,46 @@
|
|||
// +build windows
|
||||
// +build go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
||||
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(snapshot)
|
||||
var procEntry syscall.ProcessEntry32
|
||||
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
||||
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for {
|
||||
if procEntry.ProcessID == uint32(pid) {
|
||||
return &procEntry, nil
|
||||
}
|
||||
err = syscall.Process32Next(snapshot, &procEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
pe, err := getProcessEntry(os.Getppid())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
||||
}
|
24
Godeps/_workspace/src/github.com/spf13/cobra/.gitignore
generated
vendored
Normal file
24
Godeps/_workspace/src/github.com/spf13/cobra/.gitignore
generated
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
|
||||
cobra.test
|
8
Godeps/_workspace/src/github.com/spf13/cobra/.travis.yml
generated
vendored
Normal file
8
Godeps/_workspace/src/github.com/spf13/cobra/.travis.yml
generated
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
language: go
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4.2
|
||||
- tip
|
||||
script:
|
||||
- go test ./...
|
||||
- go build
|
174
Godeps/_workspace/src/github.com/spf13/cobra/LICENSE.txt
generated
vendored
Normal file
174
Godeps/_workspace/src/github.com/spf13/cobra/LICENSE.txt
generated
vendored
Normal file
|
@ -0,0 +1,174 @@
|
|||
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.
|
485
Godeps/_workspace/src/github.com/spf13/cobra/README.md
generated
vendored
Normal file
485
Godeps/_workspace/src/github.com/spf13/cobra/README.md
generated
vendored
Normal file
|
@ -0,0 +1,485 @@
|
|||
# Cobra
|
||||
|
||||
A Commander for modern go CLI interactions
|
||||
|
||||
[![Build Status](https://travis-ci.org/spf13/cobra.svg)](https://travis-ci.org/spf13/cobra)
|
||||
|
||||
## Overview
|
||||
|
||||
Cobra is a commander providing a simple interface to create powerful modern CLI
|
||||
interfaces similar to git & go tools. In addition to providing an interface, Cobra
|
||||
simultaneously provides a controller to organize your application code.
|
||||
|
||||
Inspired by go, go-Commander, gh and subcommand, Cobra improves on these by
|
||||
providing **fully posix compliant flags** (including short & long versions),
|
||||
**nesting commands**, and the ability to **define your own help and usage** for any or
|
||||
all commands.
|
||||
|
||||
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. The shortest unambiguous string will
|
||||
suffice. 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 & flags.
|
||||
|
||||
**Commands** represent actions and **Flags** are modifiers for those actions.
|
||||
|
||||
In the following example 'server' is a command and 'port' is a flag.
|
||||
|
||||
hugo server --port=1313
|
||||
|
||||
### 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:
|
||||
|
||||
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 an command. Cobra supports
|
||||
fully posix compliant flags as well as the go flag package.
|
||||
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/ogier/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 it's 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.
|
||||
|
||||
$ go get github.com/spf13/cobra
|
||||
|
||||
Next include cobra in your application.
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
### Create the root command
|
||||
|
||||
The root command represents your binary itself.
|
||||
|
||||
Cobra doesn't require any special constructors. Simply create your commands.
|
||||
|
||||
var HugoCmd = &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
|
||||
},
|
||||
}
|
||||
|
||||
### Create additional commands
|
||||
|
||||
Additional commands can be defined.
|
||||
|
||||
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
|
||||
In this example we are attaching it to the root, but commands can be attached at any level.
|
||||
|
||||
HugoCmd.AddCommand(versionCmd)
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
HugoCmd.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.
|
||||
|
||||
HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
||||
|
||||
### 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 by our own version.
|
||||
|
||||
mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
|
||||
mainlib.RootCmd.AddCommand(versionCmd)
|
||||
|
||||
### Once all commands and flags are defined, Execute the commands
|
||||
|
||||
Execute should be run on the root for clarity, though it can be called on any command.
|
||||
|
||||
HugoCmd.Execute()
|
||||
|
||||
## 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
|
||||
|
||||
import(
|
||||
"github.com/spf13/cobra"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
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://hugo.spf13.com)
|
||||
|
||||
## 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
|
||||
|
||||
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
|
||||
|
||||
Usage:
|
||||
hugo [flags]
|
||||
hugo [command]
|
||||
|
||||
Available Commands:
|
||||
server :: Hugo runs it's own a webserver to render the files
|
||||
version :: Print the version number of Hugo
|
||||
check :: Check content in the source directory
|
||||
benchmark :: Benchmark hugo by building a site a number of times
|
||||
help [command] :: Help about any command
|
||||
|
||||
Available Flags:
|
||||
-b, --base-url="": hostname (and path) to the root eg. http://spf13.com/
|
||||
-D, --build-drafts=false: include content marked as draft
|
||||
--config="": config file (default is path/config.yaml|json|toml)
|
||||
-d, --destination="": filesystem path to write files to
|
||||
-s, --source="": filesystem path to read files relative from
|
||||
--stepAnalysis=false: display memory and timing of different steps of the program
|
||||
--uglyurls=false: if true, use /filename.html instead of /filename/
|
||||
-v, --verbose=false: verbose output
|
||||
-w, --watch=false: watch filesystem for changes and recreate as needed
|
||||
|
||||
Use "hugo help [command]" for more information about that 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 you own template for the default command to use.
|
||||
|
||||
The default help command is
|
||||
|
||||
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.
|
||||
|
||||
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 it's output.
|
||||
|
||||
Usage:
|
||||
hugo [flags]
|
||||
hugo [command]
|
||||
|
||||
Available Commands:
|
||||
server Hugo runs it's own a webserver to render the files
|
||||
version Print the version number of Hugo
|
||||
check Check content in the source directory
|
||||
benchmark Benchmark hugo by building a site a number of times
|
||||
help [command] Help about any command
|
||||
|
||||
Available Flags:
|
||||
-b, --base-url="": hostname (and path) to the root eg. http://spf13.com/
|
||||
-D, --build-drafts=false: include content marked as draft
|
||||
--config="": config file (default is path/config.yaml|json|toml)
|
||||
-d, --destination="": filesystem path to write files to
|
||||
-s, --source="": filesystem path to read files relative from
|
||||
--stepAnalysis=false: display memory and timing of different steps of the program
|
||||
--uglyurls=false: if true, use /filename.html instead of /filename/
|
||||
-v, --verbose=false: verbose output
|
||||
-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
|
||||
|
||||
return func(c *Command) error {
|
||||
err := tmpl(c.Out(), c.UsageTemplate(), c)
|
||||
return err
|
||||
}
|
||||
|
||||
Like help the function and template are over ridable through public methods.
|
||||
|
||||
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`. `PersistendPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
- `Run`
|
||||
- `PostRun`
|
||||
- `PersistenPostRun`
|
||||
|
||||
And example of two commands which use all of these features is below. When the subcommand in 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 sub command",
|
||||
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()
|
||||
}
|
||||
```
|
||||
|
||||
## 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](md_docs.md)
|
||||
|
||||
## Generating bash completions for your command
|
||||
|
||||
Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [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
|
||||
|
||||
command.DebugFlags()
|
||||
|
||||
## Release Notes
|
||||
* **0.9.0** June 17, 2014
|
||||
* flags can appears anywhere in the args (provided they are unambiguous)
|
||||
* --help prints usage screen for app or command
|
||||
* Prefix matching for commands
|
||||
* Cleaner looking help and usage output
|
||||
* Extensive test suite
|
||||
* **0.8.0** Nov 5, 2013
|
||||
* Reworked interface to remove commander completely
|
||||
* Command now primary structure
|
||||
* No initialization needed
|
||||
* Usage & Help templates & functions definable at any level
|
||||
* Updated Readme
|
||||
* **0.7.0** Sept 24, 2013
|
||||
* Needs more eyes
|
||||
* Test suite
|
||||
* Support for automatic error messages
|
||||
* Support for help command
|
||||
* Support for printing to any io.Writer instead of os.Stderr
|
||||
* Support for persistent flags which cascade down tree
|
||||
* Ready for integration into Hugo
|
||||
* **0.1.0** Sept 3, 2013
|
||||
* Implement first draft
|
||||
|
||||
## ToDo
|
||||
* Launch proper documentation site
|
||||
|
||||
## 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)
|
||||
|
||||
## License
|
||||
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
|
||||
|
||||
|
||||
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
|
||||
|
357
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.go
generated
vendored
Normal file
357
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.go
generated
vendored
Normal file
|
@ -0,0 +1,357 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
)
|
||||
|
||||
func preamble(out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, `#!/bin/bash
|
||||
|
||||
|
||||
__debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
||||
__index_of_word()
|
||||
{
|
||||
local w word=$1
|
||||
shift
|
||||
index=0
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
index=$((index+1))
|
||||
done
|
||||
index=-1
|
||||
}
|
||||
|
||||
__contains_word()
|
||||
{
|
||||
local w word=$1; shift
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
__handle_reply()
|
||||
{
|
||||
__debug "${FUNCNAME}"
|
||||
case $cur in
|
||||
-*)
|
||||
compopt -o nospace
|
||||
local allflags
|
||||
if [ ${#must_have_one_flag[@]} -ne 0 ]; then
|
||||
allflags=("${must_have_one_flag[@]}")
|
||||
else
|
||||
allflags=("${flags[*]} ${two_word_flags[*]}")
|
||||
fi
|
||||
COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
|
||||
[[ $COMPREPLY == *= ]] || compopt +o nospace
|
||||
return 0;
|
||||
;;
|
||||
esac
|
||||
|
||||
# check if we are handling a flag with special work handling
|
||||
local index
|
||||
__index_of_word "${prev}" "${flags_with_completion[@]}"
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
${flags_completion[${index}]}
|
||||
return
|
||||
fi
|
||||
|
||||
# we are parsing a flag and don't have a special handler, no completion
|
||||
if [[ ${cur} != "${words[cword]}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
local completions
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_flag[@]}")
|
||||
elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_noun[@]}")
|
||||
else
|
||||
completions=("${commands[@]}")
|
||||
fi
|
||||
COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
}
|
||||
|
||||
# The arguments should be in the form "ext1|ext2|extn"
|
||||
__handle_filename_extension_flag()
|
||||
{
|
||||
local ext="$1"
|
||||
_filedir "@(${ext})"
|
||||
}
|
||||
|
||||
__handle_flag()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
# if a command required a flag, and we found it, unset must_have_one_flag()
|
||||
local flagname=${words[c]}
|
||||
# if the word contained an =
|
||||
if [[ ${words[c]} == *"="* ]]; then
|
||||
flagname=${flagname%%=*} # strip everything after the =
|
||||
flagname="${flagname}=" # but put the = back
|
||||
fi
|
||||
__debug "${FUNCNAME}: looking for ${flagname}"
|
||||
if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
|
||||
must_have_one_flag=()
|
||||
fi
|
||||
|
||||
# skip the argument to a two word flag
|
||||
if __contains_word "${words[c]}" "${two_word_flags[@]}"; then
|
||||
c=$((c+1))
|
||||
# if we are looking for a flags value, don't show commands
|
||||
if [[ $c -eq $cword ]]; then
|
||||
commands=()
|
||||
fi
|
||||
fi
|
||||
|
||||
# skip the flag itself
|
||||
c=$((c+1))
|
||||
|
||||
}
|
||||
|
||||
__handle_noun()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
|
||||
must_have_one_noun=()
|
||||
fi
|
||||
|
||||
nouns+=("${words[c]}")
|
||||
c=$((c+1))
|
||||
}
|
||||
|
||||
__handle_command()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
local next_command
|
||||
if [[ -n ${last_command} ]]; then
|
||||
next_command="_${last_command}_${words[c]}"
|
||||
else
|
||||
next_command="_${words[c]}"
|
||||
fi
|
||||
c=$((c+1))
|
||||
__debug "${FUNCNAME}: looking for ${next_command}"
|
||||
declare -F $next_command >/dev/null && $next_command
|
||||
}
|
||||
|
||||
__handle_word()
|
||||
{
|
||||
if [[ $c -ge $cword ]]; then
|
||||
__handle_reply
|
||||
return
|
||||
fi
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
if [[ "${words[c]}" == -* ]]; then
|
||||
__handle_flag
|
||||
elif __contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__handle_command
|
||||
else
|
||||
__handle_noun
|
||||
fi
|
||||
__handle_word
|
||||
}
|
||||
|
||||
`)
|
||||
}
|
||||
|
||||
func postscript(out *bytes.Buffer, name string) {
|
||||
fmt.Fprintf(out, "__start_%s()\n", name)
|
||||
fmt.Fprintf(out, `{
|
||||
local cur prev words cword
|
||||
_init_completion -s || return
|
||||
|
||||
local c=0
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%s")
|
||||
local must_have_one_flag=()
|
||||
local must_have_one_noun=()
|
||||
local last_command
|
||||
local nouns=()
|
||||
|
||||
__handle_word
|
||||
}
|
||||
|
||||
`, name)
|
||||
fmt.Fprintf(out, "complete -F __start_%s %s\n", name, name)
|
||||
fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n")
|
||||
}
|
||||
|
||||
func writeCommands(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, " commands=()\n")
|
||||
for _, c := range cmd.Commands() {
|
||||
if len(c.Deprecated) > 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(out, " commands+=(%q)\n", c.Name())
|
||||
}
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
|
||||
func writeFlagHandler(name string, annotations map[string][]string, out *bytes.Buffer) {
|
||||
for key, value := range annotations {
|
||||
switch key {
|
||||
case BashCompFilenameExt:
|
||||
fmt.Fprintf(out, " flags_with_completion+=(%q)\n", name)
|
||||
|
||||
ext := strings.Join(value, "|")
|
||||
ext = "__handle_filename_extension_flag " + ext
|
||||
fmt.Fprintf(out, " flags_completion+=(%q)\n", ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeShortFlag(flag *pflag.Flag, out *bytes.Buffer) {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
name := flag.Shorthand
|
||||
format := " "
|
||||
if !b {
|
||||
format += "two_word_"
|
||||
}
|
||||
format += "flags+=(\"-%s\")\n"
|
||||
fmt.Fprintf(out, format, name)
|
||||
writeFlagHandler("-"+name, flag.Annotations, out)
|
||||
}
|
||||
|
||||
func writeFlag(flag *pflag.Flag, out *bytes.Buffer) {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
name := flag.Name
|
||||
format := " flags+=(\"--%s"
|
||||
if !b {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
fmt.Fprintf(out, format, name)
|
||||
writeFlagHandler("--"+name, flag.Annotations, out)
|
||||
}
|
||||
|
||||
func writeFlags(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, ` flags=()
|
||||
two_word_flags=()
|
||||
flags_with_completion=()
|
||||
flags_completion=()
|
||||
|
||||
`)
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
writeFlag(flag, out)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
writeShortFlag(flag, out)
|
||||
}
|
||||
})
|
||||
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
|
||||
func writeRequiredFlag(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, " must_have_one_flag=()\n")
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
for key, _ := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
b := (flag.Value.Type() == "bool")
|
||||
if !b {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
fmt.Fprintf(out, format, flag.Name)
|
||||
|
||||
if len(flag.Shorthand) > 0 {
|
||||
fmt.Fprintf(out, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeRequiredNoun(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, " must_have_one_noun=()\n")
|
||||
sort.Sort(sort.StringSlice(cmd.ValidArgs))
|
||||
for _, value := range cmd.ValidArgs {
|
||||
fmt.Fprintf(out, " must_have_one_noun+=(%q)\n", value)
|
||||
}
|
||||
}
|
||||
|
||||
func gen(cmd *Command, out *bytes.Buffer) {
|
||||
for _, c := range cmd.Commands() {
|
||||
if len(c.Deprecated) > 0 {
|
||||
continue
|
||||
}
|
||||
gen(c, out)
|
||||
}
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.Replace(commandName, " ", "_", -1)
|
||||
fmt.Fprintf(out, "_%s()\n{\n", commandName)
|
||||
fmt.Fprintf(out, " last_command=%q\n", commandName)
|
||||
writeCommands(cmd, out)
|
||||
writeFlags(cmd, out)
|
||||
writeRequiredFlag(cmd, out)
|
||||
writeRequiredNoun(cmd, out)
|
||||
fmt.Fprintf(out, "}\n\n")
|
||||
}
|
||||
|
||||
func (cmd *Command) GenBashCompletion(out *bytes.Buffer) {
|
||||
preamble(out)
|
||||
if len(cmd.BashCompletionFunction) > 0 {
|
||||
fmt.Fprintf(out, "%s\n", cmd.BashCompletionFunction)
|
||||
}
|
||||
gen(cmd, out)
|
||||
postscript(out, cmd.Name())
|
||||
}
|
||||
|
||||
func (cmd *Command) GenBashCompletionFile(filename string) error {
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
cmd.GenBashCompletion(out)
|
||||
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
_, err = outFile.Write(out.Bytes())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cmd *Command) MarkFlagRequired(name string) {
|
||||
flag := cmd.Flags().Lookup(name)
|
||||
if flag == nil {
|
||||
return
|
||||
}
|
||||
if flag.Annotations == nil {
|
||||
flag.Annotations = make(map[string][]string)
|
||||
}
|
||||
annotation := make([]string, 1)
|
||||
annotation[0] = "true"
|
||||
flag.Annotations[BashCompOneRequiredFlag] = annotation
|
||||
}
|
149
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.md
generated
vendored
Normal file
149
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.md
generated
vendored
Normal file
|
@ -0,0 +1,149 @@
|
|||
# Generating Bash Completions For Your Own cobra.Command
|
||||
|
||||
Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl.GenBashCompletionFile("out.sh")
|
||||
}
|
||||
```
|
||||
|
||||
That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
|
||||
|
||||
## Creating your own custom functions
|
||||
|
||||
Some more actual code that works in kubernetes:
|
||||
|
||||
```bash
|
||||
const (
|
||||
bash_completion_func = `__kubectl_parse_get()
|
||||
{
|
||||
local kubectl_output out
|
||||
if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
|
||||
out=($(echo "${kubectl_output}" | awk '{print $1}'))
|
||||
COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_get_resource()
|
||||
{
|
||||
if [[ ${#nouns[@]} -eq 0 ]]; then
|
||||
return 1
|
||||
fi
|
||||
__kubectl_parse_get ${nouns[${#nouns[@]} -1]}
|
||||
if [[ $? -eq 0 ]]; then
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
__custom_func() {
|
||||
case ${last_command} in
|
||||
kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
|
||||
__kubectl_get_resource
|
||||
return
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
`)
|
||||
```
|
||||
|
||||
And then I set that in my command definition:
|
||||
|
||||
```go
|
||||
cmds := &cobra.Command{
|
||||
Use: "kubectl",
|
||||
Short: "kubectl controls the Kubernetes cluster manager",
|
||||
Long: `kubectl controls the Kubernetes cluster manager.
|
||||
|
||||
Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
|
||||
Run: runHelp,
|
||||
BashCompletionFunction: bash_completion_func,
|
||||
}
|
||||
```
|
||||
|
||||
The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__custom_func()` to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
|
||||
|
||||
## Have the completions code complete your 'nouns'
|
||||
|
||||
In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pods", "nodes", "services", "replicationControllers" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
Short: "Display one or many resources",
|
||||
Long: get_long,
|
||||
Example: get_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := RunGet(f, out, cmd, args)
|
||||
util.CheckErr(err)
|
||||
},
|
||||
ValidArgs: validArgs,
|
||||
}
|
||||
```
|
||||
|
||||
Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
|
||||
|
||||
```bash
|
||||
# kubectl get [tab][tab]
|
||||
nodes pods replicationControllers services
|
||||
```
|
||||
|
||||
## Mark flags as required
|
||||
|
||||
Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
|
||||
|
||||
```go
|
||||
cmd.MarkFlagRequired("pod")
|
||||
cmd.MarkFlagRequired("container")
|
||||
```
|
||||
|
||||
and you'll get something like
|
||||
|
||||
```bash
|
||||
# kubectl exec [tab][tab][tab]
|
||||
-c --container= -p --pod=
|
||||
```
|
||||
|
||||
# Specify valid filename extensions for flags that take a filename
|
||||
|
||||
In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
|
||||
|
||||
```go
|
||||
annotations := []string{"json", "yaml", "yml"}
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompFilenameExt] = annotations
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "filename",
|
||||
Shorthand: "f",
|
||||
Usage: usage,
|
||||
Value: value,
|
||||
DefValue: value.String(),
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
Now when you run a command with this filename flag you'll get something like
|
||||
|
||||
```bash
|
||||
# kubectl create -f
|
||||
test/ example/ rpmbuild/
|
||||
hello.yml test.json
|
||||
```
|
||||
|
||||
So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
|
82
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
Normal file
82
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
Normal file
|
@ -0,0 +1,82 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func checkOmit(t *testing.T, found, unexpected string) {
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
|
||||
}
|
||||
}
|
||||
|
||||
func check(t *testing.T, found, expected string) {
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
}
|
||||
|
||||
// World worst custom function, just keep telling you to enter hello!
|
||||
const (
|
||||
bash_completion_func = `__custom_func() {
|
||||
COMPREPLY=( "hello" )
|
||||
}
|
||||
`
|
||||
)
|
||||
|
||||
func TestBashCompletions(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated)
|
||||
|
||||
// custom completion function
|
||||
c.BashCompletionFunction = bash_completion_func
|
||||
|
||||
// required flag
|
||||
c.MarkFlagRequired("introot")
|
||||
|
||||
// valid nounds
|
||||
validArgs := []string{"pods", "nodes", "services", "replicationControllers"}
|
||||
c.ValidArgs = validArgs
|
||||
|
||||
// filename extentions
|
||||
annotations := make([]string, 3)
|
||||
annotations[0] = "json"
|
||||
annotations[1] = "yaml"
|
||||
annotations[2] = "yml"
|
||||
|
||||
annotation := make(map[string][]string)
|
||||
annotation[BashCompFilenameExt] = annotations
|
||||
|
||||
var flagval string
|
||||
c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")
|
||||
flag := c.Flags().Lookup("filename")
|
||||
flag.Annotations = annotation
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
c.GenBashCompletion(out)
|
||||
str := out.String()
|
||||
|
||||
check(t, str, "_cobra-test")
|
||||
check(t, str, "_cobra-test_echo")
|
||||
check(t, str, "_cobra-test_echo_times")
|
||||
check(t, str, "_cobra-test_print")
|
||||
|
||||
// check for required flags
|
||||
check(t, str, `must_have_one_flag+=("--introot=")`)
|
||||
// check for custom completion function
|
||||
check(t, str, `COMPREPLY=( "hello" )`)
|
||||
// check for required nouns
|
||||
check(t, str, `must_have_one_noun+=("pods")`)
|
||||
// check for filename extention flags
|
||||
check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)
|
||||
|
||||
checkOmit(t, str, cmdDeprecated.Name())
|
||||
}
|
112
Godeps/_workspace/src/github.com/spf13/cobra/cobra.go
generated
vendored
Normal file
112
Godeps/_workspace/src/github.com/spf13/cobra/cobra.go
generated
vendored
Normal file
|
@ -0,0 +1,112 @@
|
|||
// 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"
|
||||
)
|
||||
|
||||
var initializers []func()
|
||||
|
||||
// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
|
||||
// Set this to true to enable it
|
||||
var EnablePrefixMatching bool = false
|
||||
|
||||
// enables an information splash screen on Windows if the CLI is started from explorer.exe.
|
||||
var EnableWindowsMouseTrap bool = true
|
||||
|
||||
var MousetrapHelpText string = `This is a command line tool
|
||||
|
||||
You need to open cmd.exe and run it from there.
|
||||
`
|
||||
|
||||
//OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
func OnInitialize(y ...func()) {
|
||||
for _, x := range y {
|
||||
initializers = append(initializers, x)
|
||||
}
|
||||
}
|
||||
|
||||
//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
|
||||
}
|
||||
|
||||
//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
|
||||
}
|
||||
|
||||
//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(template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
})
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
}
|
942
Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go
generated
vendored
Normal file
942
Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go
generated
vendored
Normal file
|
@ -0,0 +1,942 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
var tp, te, tt, t1, tr []string
|
||||
var rootPersPre, echoPre, echoPersPre, timesPersPre []string
|
||||
var flagb1, flagb2, flagb3, flagbr, flagbp bool
|
||||
var flags1, flags2a, flags2b, flags3 string
|
||||
var flagi1, flagi2, flagi3, flagir int
|
||||
var globalFlag1 bool
|
||||
var flagEcho, rootcalled bool
|
||||
var versionUsed int
|
||||
|
||||
const strtwoParentHelp = "help message for parent flag strtwo"
|
||||
const strtwoChildHelp = "help message for child flag strtwo"
|
||||
|
||||
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]",
|
||||
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 it's 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 it's 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 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
|
||||
},
|
||||
}
|
||||
|
||||
func flagInit() {
|
||||
cmdEcho.ResetFlags()
|
||||
cmdPrint.ResetFlags()
|
||||
cmdTimes.ResetFlags()
|
||||
cmdRootNoRun.ResetFlags()
|
||||
cmdRootSameName.ResetFlags()
|
||||
cmdRootWithRun.ResetFlags()
|
||||
cmdSubNoRun.ResetFlags()
|
||||
cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
|
||||
cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
|
||||
cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
|
||||
cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
|
||||
cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
|
||||
cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
|
||||
cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
|
||||
cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
|
||||
cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
|
||||
cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
|
||||
cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
|
||||
cmdVersion1.ResetFlags()
|
||||
cmdVersion2.ResetFlags()
|
||||
}
|
||||
|
||||
func commandInit() {
|
||||
cmdEcho.ResetCommands()
|
||||
cmdPrint.ResetCommands()
|
||||
cmdTimes.ResetCommands()
|
||||
cmdRootNoRun.ResetCommands()
|
||||
cmdRootSameName.ResetCommands()
|
||||
cmdRootWithRun.ResetCommands()
|
||||
cmdSubNoRun.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(input string) resulter {
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
return fullTester(c, input)
|
||||
}
|
||||
|
||||
func noRRSetupTest(input string) resulter {
|
||||
c := initialize()
|
||||
|
||||
return fullTester(c, input)
|
||||
}
|
||||
|
||||
func rootOnlySetupTest(input string) resulter {
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
return simpleTester(c, input)
|
||||
}
|
||||
|
||||
func simpleTester(c *Command, input string) resulter {
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
c.SetArgs(strings.Split(input, " "))
|
||||
|
||||
err := c.Execute()
|
||||
output := buf.String()
|
||||
|
||||
return resulter{err, output, c}
|
||||
}
|
||||
|
||||
func fullTester(c *Command, input string) resulter {
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated)
|
||||
c.SetArgs(strings.Split(input, " "))
|
||||
|
||||
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 checkResultContains(t *testing.T, x resulter, check string) {
|
||||
if !strings.Contains(x.Output, check) {
|
||||
logErr(t, x.Output, check)
|
||||
}
|
||||
}
|
||||
|
||||
func checkResultOmits(t *testing.T, x resulter, check string) {
|
||||
if strings.Contains(x.Output, check) {
|
||||
logErr(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(strings.Split("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 TestFlagLong(t *testing.T) {
|
||||
noRRSetupTest("echo --intone=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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagShort(t *testing.T) {
|
||||
noRRSetupTest("echo -i13 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("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.Output, "unknown shorthand") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", r.Output)
|
||||
}
|
||||
|
||||
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.Output, "unknown shorthand flag") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", r.Output)
|
||||
}
|
||||
|
||||
// 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.Output, "invalid argument \"10E\" for i10E") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", r.Output)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
|
||||
checkResultContains(t, result, "unknown flag: --badflag")
|
||||
|
||||
if strings.Contains(result.Output, "unknown flag: --inttwo") {
|
||||
t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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.Out(), "%v", args)
|
||||
},
|
||||
}
|
||||
first.AddCommand(second)
|
||||
|
||||
result := simpleTester(cmd, "first second first third")
|
||||
|
||||
expectedOutput := fmt.Sprintf("%v", []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 it's 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 it's 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) {
|
||||
fullSetupTest("")
|
||||
|
||||
if rootcalled != true {
|
||||
t.Errorf("Root Function was not called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnableRootCommandNilInput(t *testing.T) {
|
||||
empty_arg := make([]string, 0)
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.SetArgs(empty_arg)
|
||||
|
||||
c.Execute()
|
||||
|
||||
if rootcalled != true {
|
||||
t.Errorf("Root Function was not called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnableRootCommandEmptyInput(t *testing.T) {
|
||||
args := make([]string, 3)
|
||||
args[0] = ""
|
||||
args[1] = "--introot=12"
|
||||
args[2] = ""
|
||||
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 != true {
|
||||
t.Errorf("Root Function was not called.\n\nOutput was:\n\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 != true {
|
||||
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) {
|
||||
args := make([]string, 0)
|
||||
c := initialize()
|
||||
|
||||
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 !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\"\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)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// short (int) with equals
|
||||
// It appears that pflags doesn't support this...
|
||||
// Commenting out until support can be added
|
||||
|
||||
//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.Output, "invalid argument \"10E\" for i10E") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", x.Output)
|
||||
}
|
||||
|
||||
//With quotes
|
||||
x = fullSetupTest("-s=\"walking\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
//With quotes and space
|
||||
x = fullSetupTest("-s=\"walking fast\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
//With inner quote
|
||||
x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
//With quotes and space
|
||||
x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", 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(strings.Split("print echosub lala", " "))
|
||||
rootCmd.Execute()
|
||||
|
||||
if rootPersPre == nil || 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")
|
||||
}
|
||||
}
|
1031
Godeps/_workspace/src/github.com/spf13/cobra/command.go
generated
vendored
Normal file
1031
Godeps/_workspace/src/github.com/spf13/cobra/command.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
90
Godeps/_workspace/src/github.com/spf13/cobra/command_test.go
generated
vendored
Normal file
90
Godeps/_workspace/src/github.com/spf13/cobra/command_test.go
generated
vendored
Normal file
|
@ -0,0 +1,90 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
138
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.go
generated
vendored
Normal file
138
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.go
generated
vendored
Normal file
|
@ -0,0 +1,138 @@
|
|||
//Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func printOptions(out *bytes.Buffer, cmd *Command, name string) {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(out)
|
||||
if flags.HasFlags() {
|
||||
fmt.Fprintf(out, "### Options\n\n```\n")
|
||||
flags.PrintDefaults()
|
||||
fmt.Fprintf(out, "```\n\n")
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(out)
|
||||
if parentFlags.HasFlags() {
|
||||
fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n")
|
||||
parentFlags.PrintDefaults()
|
||||
fmt.Fprintf(out, "```\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
type byName []*Command
|
||||
|
||||
func (s byName) Len() int { return len(s) }
|
||||
func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
|
||||
|
||||
func GenMarkdown(cmd *Command, out *bytes.Buffer) {
|
||||
GenMarkdownCustom(cmd, out, func(s string) string { return s })
|
||||
}
|
||||
|
||||
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "## %s\n\n", name)
|
||||
fmt.Fprintf(out, "%s\n\n", short)
|
||||
fmt.Fprintf(out, "### Synopsis\n\n")
|
||||
fmt.Fprintf(out, "\n%s\n\n", long)
|
||||
|
||||
if cmd.Runnable() {
|
||||
fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
fmt.Fprintf(out, "### Examples\n\n")
|
||||
fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)
|
||||
}
|
||||
|
||||
printOptions(out, cmd, name)
|
||||
|
||||
if len(cmd.Commands()) > 0 || cmd.HasParent() {
|
||||
fmt.Fprintf(out, "### SEE ALSO\n")
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
link := pname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)
|
||||
}
|
||||
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
|
||||
for _, child := range children {
|
||||
if len(child.Deprecated) > 0 {
|
||||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
link := cname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)
|
||||
}
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "###### Auto generated by spf13/cobra at %s\n", time.Now().UTC())
|
||||
}
|
||||
|
||||
func GenMarkdownTree(cmd *Command, dir string) {
|
||||
identity := func(s string) string { return s }
|
||||
emptyStr := func(s string) string { return "" }
|
||||
GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
|
||||
}
|
||||
|
||||
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {
|
||||
for _, c := range cmd.Commands() {
|
||||
GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler)
|
||||
}
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
GenMarkdownCustom(cmd, out, linkHandler)
|
||||
|
||||
filename := cmd.CommandPath()
|
||||
filename = dir + strings.Replace(filename, " ", "_", -1) + ".md"
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer outFile.Close()
|
||||
_, err = outFile.WriteString(filePrepender(filename))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
_, err = outFile.Write(out.Bytes())
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
81
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.md
generated
vendored
Normal file
81
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.md
generated
vendored
Normal file
|
@ -0,0 +1,81 @@
|
|||
# Generating Markdown Docs For Your Own cobra.Command
|
||||
|
||||
## Generate markdown docs for the entire command tree
|
||||
|
||||
This program can actually generate docs for the kubectl command in the kubernetes project
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
cobra.GenMarkdownTree(kubectl, "./")
|
||||
}
|
||||
```
|
||||
|
||||
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
|
||||
|
||||
## Generate markdown docs for a single command
|
||||
|
||||
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`
|
||||
|
||||
```go
|
||||
out := new(bytes.Buffer)
|
||||
cobra.GenMarkdown(cmd, out)
|
||||
```
|
||||
|
||||
This will write the markdown doc for ONLY "cmd" into the out, buffer.
|
||||
|
||||
## Customize the output
|
||||
|
||||
Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:
|
||||
|
||||
```go
|
||||
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
|
||||
|
||||
```go
|
||||
const fmTemplate = `---
|
||||
date: %s
|
||||
title: "%s"
|
||||
slug: %s
|
||||
url: %s
|
||||
---
|
||||
`
|
||||
|
||||
filePrepender := func(filename string) string {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
name := filepath.Base(filename)
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
url := "/commands/" + strings.ToLower(base) + "/"
|
||||
return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
|
||||
}
|
||||
```
|
||||
|
||||
The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
|
||||
|
||||
```go
|
||||
linkHandler := func(name string) string {
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
return "/commands/" + strings.ToLower(base) + "/"
|
||||
}
|
||||
```
|
||||
|
67
Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go
generated
vendored
Normal file
67
Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go
generated
vendored
Normal file
|
@ -0,0 +1,67 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func TestGenMdDoc(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
// We generate on s subcommand so we have both subcommands and parents
|
||||
GenMarkdown(cmdEcho, out)
|
||||
found := out.String()
|
||||
|
||||
// Our description
|
||||
expected := cmdEcho.Long
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// Better have our example
|
||||
expected = cmdEcho.Example
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// A local flag
|
||||
expected = "boolone"
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// persistent flag on parent
|
||||
expected = "rootflag"
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// We better output info about our parent
|
||||
expected = cmdRootWithRun.Short
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// And about subcommands
|
||||
expected = cmdEchoSub.Short
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
unexpected := cmdDeprecated.Short
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
|
||||
}
|
||||
}
|
8
Godeps/_workspace/src/github.com/spf13/pflag/.travis.yml
generated
vendored
Normal file
8
Godeps/_workspace/src/github.com/spf13/pflag/.travis.yml
generated
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
sudo: false
|
||||
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4
|
||||
- tip
|
28
Godeps/_workspace/src/github.com/spf13/pflag/LICENSE
generated
vendored
Normal file
28
Godeps/_workspace/src/github.com/spf13/pflag/LICENSE
generated
vendored
Normal file
|
@ -0,0 +1,28 @@
|
|||
Copyright (c) 2012 Alex Ogier. All rights reserved.
|
||||
Copyright (c) 2012 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
191
Godeps/_workspace/src/github.com/spf13/pflag/README.md
generated
vendored
Normal file
191
Godeps/_workspace/src/github.com/spf13/pflag/README.md
generated
vendored
Normal file
|
@ -0,0 +1,191 @@
|
|||
[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag)
|
||||
|
||||
## Description
|
||||
|
||||
pflag is a drop-in replacement for Go's flag package, implementing
|
||||
POSIX/GNU-style --flags.
|
||||
|
||||
pflag is compatible with the [GNU extensions to the POSIX recommendations
|
||||
for command-line options][1]. For a more precise description, see the
|
||||
"Command-line flag syntax" section below.
|
||||
|
||||
[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
|
||||
|
||||
pflag is available under the same style of BSD license as the Go language,
|
||||
which can be found in the LICENSE file.
|
||||
|
||||
## Installation
|
||||
|
||||
pflag is available using the standard `go get` command.
|
||||
|
||||
Install by running:
|
||||
|
||||
go get github.com/ogier/pflag
|
||||
|
||||
Run tests by running:
|
||||
|
||||
go test github.com/ogier/pflag
|
||||
|
||||
## Usage
|
||||
|
||||
pflag is a drop-in replacement of Go's native flag package. If you import
|
||||
pflag under the name "flag" then all code should continue to function
|
||||
with no changes.
|
||||
|
||||
``` go
|
||||
import flag "github.com/ogier/pflag"
|
||||
```
|
||||
|
||||
There is one exception to this: if you directly instantiate the Flag struct
|
||||
there is one more field "Shorthand" that you will need to set.
|
||||
Most code never instantiates this struct directly, and instead uses
|
||||
functions such as String(), BoolVar(), and Var(), and is therefore
|
||||
unaffected.
|
||||
|
||||
Define flags using flag.String(), Bool(), Int(), etc.
|
||||
|
||||
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
|
||||
|
||||
``` go
|
||||
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
|
||||
```
|
||||
|
||||
If you like, you can bind the flag to a variable using the Var() functions.
|
||||
|
||||
``` go
|
||||
var flagvar int
|
||||
func init() {
|
||||
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
|
||||
}
|
||||
```
|
||||
|
||||
Or you can create custom flags that satisfy the Value interface (with
|
||||
pointer receivers) and couple them to flag parsing by
|
||||
|
||||
``` go
|
||||
flag.Var(&flagVal, "name", "help message for flagname")
|
||||
```
|
||||
|
||||
For such flags, the default value is just the initial value of the variable.
|
||||
|
||||
After all flags are defined, call
|
||||
|
||||
``` go
|
||||
flag.Parse()
|
||||
```
|
||||
|
||||
to parse the command line into the defined flags.
|
||||
|
||||
Flags may then be used directly. If you're using the flags themselves,
|
||||
they are all pointers; if you bind to variables, they're values.
|
||||
|
||||
``` go
|
||||
fmt.Println("ip has value ", *ip)
|
||||
fmt.Println("flagvar has value ", flagvar)
|
||||
```
|
||||
|
||||
After parsing, the arguments after the flag are available as the
|
||||
slice flag.Args() or individually as flag.Arg(i).
|
||||
The arguments are indexed from 0 through flag.NArg()-1.
|
||||
|
||||
The pflag package also defines some new functions that are not in flag,
|
||||
that give one-letter shorthands for flags. You can use these by appending
|
||||
'P' to the name of any function that defines a flag.
|
||||
|
||||
``` go
|
||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
var flagvar bool
|
||||
func init() {
|
||||
flag.BoolVarP("boolname", "b", true, "help message")
|
||||
}
|
||||
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
|
||||
```
|
||||
|
||||
Shorthand letters can be used with single dashes on the command line.
|
||||
Boolean shorthand flags can be combined with other shorthand flags.
|
||||
|
||||
The default set of command-line flags is controlled by
|
||||
top-level functions. The FlagSet type allows one to define
|
||||
independent sets of flags, such as to implement subcommands
|
||||
in a command-line interface. The methods of FlagSet are
|
||||
analogous to the top-level functions for the command-line
|
||||
flag set.
|
||||
|
||||
## Command line flag syntax
|
||||
|
||||
```
|
||||
--flag // boolean flags only
|
||||
--flag=x
|
||||
```
|
||||
|
||||
Unlike the flag package, a single dash before an option means something
|
||||
different than a double dash. Single dashes signify a series of shorthand
|
||||
letters for flags. All but the last shorthand letter must be boolean flags.
|
||||
|
||||
```
|
||||
// boolean flags
|
||||
-f
|
||||
-abc
|
||||
|
||||
// non-boolean flags
|
||||
-n 1234
|
||||
-Ifile
|
||||
|
||||
// mixed
|
||||
-abcs "hello"
|
||||
-abcn1234
|
||||
```
|
||||
|
||||
Flag parsing stops after the terminator "--". Unlike the flag package,
|
||||
flags can be interspersed with arguments anywhere on the command line
|
||||
before this terminator.
|
||||
|
||||
Integer flags accept 1234, 0664, 0x1234 and may be negative.
|
||||
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
|
||||
TRUE, FALSE, True, False.
|
||||
Duration flags accept any input valid for time.ParseDuration.
|
||||
|
||||
## Mutating or "Normalizing" Flag names
|
||||
|
||||
It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
|
||||
|
||||
**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
|
||||
|
||||
```go
|
||||
func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
from := []string{"-", "_"}
|
||||
to := "."
|
||||
for _, sep := range from {
|
||||
name = strings.Replace(name, sep, to, -1)
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
}
|
||||
|
||||
myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
```
|
||||
|
||||
**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
|
||||
|
||||
```go
|
||||
func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
switch name {
|
||||
case "old-flag-name":
|
||||
name = "new-flag-name"
|
||||
break
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
}
|
||||
|
||||
myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
|
||||
```
|
||||
|
||||
## More info
|
||||
|
||||
You can see the full reference documentation of the pflag package
|
||||
[at godoc.org][3], or through go's standard documentation system by
|
||||
running `godoc -http=:6060` and browsing to
|
||||
[http://localhost:6060/pkg/github.com/ogier/pflag][2] after
|
||||
installation.
|
||||
|
||||
[2]: http://localhost:6060/pkg/github.com/ogier/pflag
|
||||
[3]: http://godoc.org/github.com/ogier/pflag
|
83
Godeps/_workspace/src/github.com/spf13/pflag/bool.go
generated
vendored
Normal file
83
Godeps/_workspace/src/github.com/spf13/pflag/bool.go
generated
vendored
Normal file
|
@ -0,0 +1,83 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// optional interface to indicate boolean flags that can be
|
||||
// supplied without "=value" text
|
||||
type boolFlag interface {
|
||||
Value
|
||||
IsBoolFlag() bool
|
||||
}
|
||||
|
||||
// -- bool Value
|
||||
type boolValue bool
|
||||
|
||||
func newBoolValue(val bool, p *bool) *boolValue {
|
||||
*p = val
|
||||
return (*boolValue)(p)
|
||||
}
|
||||
|
||||
func (b *boolValue) Set(s string) error {
|
||||
v, err := strconv.ParseBool(s)
|
||||
*b = boolValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *boolValue) Type() string {
|
||||
return "bool"
|
||||
}
|
||||
|
||||
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
|
||||
|
||||
func (b *boolValue) IsBoolFlag() bool { return true }
|
||||
|
||||
// BoolVar defines a bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a bool variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
|
||||
f.VarP(newBoolValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like BoolVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
|
||||
f.VarP(newBoolValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolVar defines a bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a bool variable in which to store the value of the flag.
|
||||
func BoolVar(p *bool, name string, value bool, usage string) {
|
||||
CommandLine.VarP(newBoolValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like BoolVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
|
||||
CommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Bool defines a bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a bool variable that stores the value of the flag.
|
||||
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
|
||||
p := new(bool)
|
||||
f.BoolVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Bool, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
|
||||
p := new(bool)
|
||||
f.BoolVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Bool defines a bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a bool variable that stores the value of the flag.
|
||||
func Bool(name string, value bool, usage string) *bool {
|
||||
return CommandLine.BoolP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Bool, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolP(name, shorthand string, value bool, usage string) *bool {
|
||||
return CommandLine.BoolP(name, shorthand, value, usage)
|
||||
}
|
164
Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go
generated
vendored
Normal file
164
Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go
generated
vendored
Normal file
|
@ -0,0 +1,164 @@
|
|||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// This value can be a boolean ("true", "false") or "maybe"
|
||||
type triStateValue int
|
||||
|
||||
const (
|
||||
triStateFalse triStateValue = 0
|
||||
triStateTrue triStateValue = 1
|
||||
triStateMaybe triStateValue = 2
|
||||
)
|
||||
|
||||
const strTriStateMaybe = "maybe"
|
||||
|
||||
func (v *triStateValue) IsBoolFlag() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (v *triStateValue) Get() interface{} {
|
||||
return triStateValue(*v)
|
||||
}
|
||||
|
||||
func (v *triStateValue) Set(s string) error {
|
||||
if s == strTriStateMaybe {
|
||||
*v = triStateMaybe
|
||||
return nil
|
||||
}
|
||||
boolVal, err := strconv.ParseBool(s)
|
||||
if boolVal {
|
||||
*v = triStateTrue
|
||||
} else {
|
||||
*v = triStateFalse
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (v *triStateValue) String() string {
|
||||
if *v == triStateMaybe {
|
||||
return strTriStateMaybe
|
||||
}
|
||||
return fmt.Sprintf("%v", bool(*v == triStateTrue))
|
||||
}
|
||||
|
||||
// The type of the flag as requred by the pflag.Value interface
|
||||
func (v *triStateValue) Type() string {
|
||||
return "version"
|
||||
}
|
||||
|
||||
func setUpFlagSet(tristate *triStateValue) *FlagSet {
|
||||
f := NewFlagSet("test", ContinueOnError)
|
||||
*tristate = triStateFalse
|
||||
f.VarP(tristate, "tristate", "t", "tristate value (true, maybe or false)")
|
||||
return f
|
||||
}
|
||||
|
||||
func TestExplicitTrue(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
err := f.Parse([]string{"--tristate=true"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateTrue {
|
||||
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImplicitTrue(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
err := f.Parse([]string{"--tristate"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateTrue {
|
||||
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortFlag(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
err := f.Parse([]string{"-t"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateTrue {
|
||||
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortFlagExtraArgument(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
// The"maybe"turns into an arg, since short boolean options will only do true/false
|
||||
err := f.Parse([]string{"-t", "maybe"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateTrue {
|
||||
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
|
||||
}
|
||||
args := f.Args()
|
||||
if len(args) != 1 || args[0] != "maybe" {
|
||||
t.Fatal("expected an extra 'maybe' argument to stick around")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitMaybe(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
err := f.Parse([]string{"--tristate=maybe"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateMaybe {
|
||||
t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitFalse(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
err := f.Parse([]string{"--tristate=false"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateFalse {
|
||||
t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImplicitFalse(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
err := f.Parse([]string{})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got", err)
|
||||
}
|
||||
if tristate != triStateFalse {
|
||||
t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidValue(t *testing.T) {
|
||||
var tristate triStateValue
|
||||
f := setUpFlagSet(&tristate)
|
||||
var buf bytes.Buffer
|
||||
f.SetOutput(&buf)
|
||||
err := f.Parse([]string{"--tristate=invalid"})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error but did not get any, tristate has value", tristate)
|
||||
}
|
||||
}
|
71
Godeps/_workspace/src/github.com/spf13/pflag/duration.go
generated
vendored
Normal file
71
Godeps/_workspace/src/github.com/spf13/pflag/duration.go
generated
vendored
Normal file
|
@ -0,0 +1,71 @@
|
|||
package pflag
|
||||
|
||||
import "time"
|
||||
|
||||
// -- time.Duration Value
|
||||
type durationValue time.Duration
|
||||
|
||||
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
|
||||
*p = val
|
||||
return (*durationValue)(p)
|
||||
}
|
||||
|
||||
func (d *durationValue) Set(s string) error {
|
||||
v, err := time.ParseDuration(s)
|
||||
*d = durationValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *durationValue) Type() string {
|
||||
return "duration"
|
||||
}
|
||||
|
||||
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
f.VarP(newDurationValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like DurationVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
|
||||
f.VarP(newDurationValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like DurationVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Duration, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
return CommandLine.DurationP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Duration, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
|
||||
return CommandLine.DurationP(name, shorthand, value, usage)
|
||||
}
|
77
Godeps/_workspace/src/github.com/spf13/pflag/example_test.go
generated
vendored
Normal file
77
Godeps/_workspace/src/github.com/spf13/pflag/example_test.go
generated
vendored
Normal file
|
@ -0,0 +1,77 @@
|
|||
// Copyright 2012 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// These examples demonstrate more intricate uses of the flag package.
|
||||
package pflag_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Example 1: A single string flag called "species" with default value "gopher".
|
||||
var species = flag.String("species", "gopher", "the species we are studying")
|
||||
|
||||
// Example 2: A flag with a shorthand letter.
|
||||
var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher")
|
||||
|
||||
// Example 3: A user-defined flag type, a slice of durations.
|
||||
type interval []time.Duration
|
||||
|
||||
// String is the method to format the flag's value, part of the flag.Value interface.
|
||||
// The String method's output will be used in diagnostics.
|
||||
func (i *interval) String() string {
|
||||
return fmt.Sprint(*i)
|
||||
}
|
||||
|
||||
func (i *interval) Type() string {
|
||||
return "interval"
|
||||
}
|
||||
|
||||
// Set is the method to set the flag value, part of the flag.Value interface.
|
||||
// Set's argument is a string to be parsed to set the flag.
|
||||
// It's a comma-separated list, so we split it.
|
||||
func (i *interval) Set(value string) error {
|
||||
// If we wanted to allow the flag to be set multiple times,
|
||||
// accumulating values, we would delete this if statement.
|
||||
// That would permit usages such as
|
||||
// -deltaT 10s -deltaT 15s
|
||||
// and other combinations.
|
||||
if len(*i) > 0 {
|
||||
return errors.New("interval flag already set")
|
||||
}
|
||||
for _, dt := range strings.Split(value, ",") {
|
||||
duration, err := time.ParseDuration(dt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*i = append(*i, duration)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Define a flag to accumulate durations. Because it has a special type,
|
||||
// we need to use the Var function and therefore create the flag during
|
||||
// init.
|
||||
|
||||
var intervalFlag interval
|
||||
|
||||
func init() {
|
||||
// Tie the command-line flag to the intervalFlag variable and
|
||||
// set a usage message.
|
||||
flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
|
||||
}
|
||||
|
||||
func Example() {
|
||||
// All the interesting pieces are with the variables declared above, but
|
||||
// to enable the flag package to see the flags defined there, one must
|
||||
// execute, typically at the start of main (not init!):
|
||||
// flag.Parse()
|
||||
// We don't run it here because this is not a main function and
|
||||
// the testing suite has already parsed the flags.
|
||||
}
|
29
Godeps/_workspace/src/github.com/spf13/pflag/export_test.go
generated
vendored
Normal file
29
Godeps/_workspace/src/github.com/spf13/pflag/export_test.go
generated
vendored
Normal file
|
@ -0,0 +1,29 @@
|
|||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Additional routines compiled into the package only during testing.
|
||||
|
||||
// ResetForTesting clears all flag state and sets the usage function as directed.
|
||||
// After calling ResetForTesting, parse errors in flag handling will not
|
||||
// exit the program.
|
||||
func ResetForTesting(usage func()) {
|
||||
CommandLine = &FlagSet{
|
||||
name: os.Args[0],
|
||||
errorHandling: ContinueOnError,
|
||||
output: ioutil.Discard,
|
||||
}
|
||||
Usage = usage
|
||||
}
|
||||
|
||||
// GetCommandLine returns the default FlagSet.
|
||||
func GetCommandLine() *FlagSet {
|
||||
return CommandLine
|
||||
}
|
695
Godeps/_workspace/src/github.com/spf13/pflag/flag.go
generated
vendored
Normal file
695
Godeps/_workspace/src/github.com/spf13/pflag/flag.go
generated
vendored
Normal file
|
@ -0,0 +1,695 @@
|
|||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
pflag is a drop-in replacement for Go's flag package, implementing
|
||||
POSIX/GNU-style --flags.
|
||||
|
||||
pflag is compatible with the GNU extensions to the POSIX recommendations
|
||||
for command-line options. See
|
||||
http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
|
||||
|
||||
Usage:
|
||||
|
||||
pflag is a drop-in replacement of Go's native flag package. If you import
|
||||
pflag under the name "flag" then all code should continue to function
|
||||
with no changes.
|
||||
|
||||
import flag "github.com/ogier/pflag"
|
||||
|
||||
There is one exception to this: if you directly instantiate the Flag struct
|
||||
there is one more field "Shorthand" that you will need to set.
|
||||
Most code never instantiates this struct directly, and instead uses
|
||||
functions such as String(), BoolVar(), and Var(), and is therefore
|
||||
unaffected.
|
||||
|
||||
Define flags using flag.String(), Bool(), Int(), etc.
|
||||
|
||||
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
|
||||
var ip = flag.Int("flagname", 1234, "help message for flagname")
|
||||
If you like, you can bind the flag to a variable using the Var() functions.
|
||||
var flagvar int
|
||||
func init() {
|
||||
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
|
||||
}
|
||||
Or you can create custom flags that satisfy the Value interface (with
|
||||
pointer receivers) and couple them to flag parsing by
|
||||
flag.Var(&flagVal, "name", "help message for flagname")
|
||||
For such flags, the default value is just the initial value of the variable.
|
||||
|
||||
After all flags are defined, call
|
||||
flag.Parse()
|
||||
to parse the command line into the defined flags.
|
||||
|
||||
Flags may then be used directly. If you're using the flags themselves,
|
||||
they are all pointers; if you bind to variables, they're values.
|
||||
fmt.Println("ip has value ", *ip)
|
||||
fmt.Println("flagvar has value ", flagvar)
|
||||
|
||||
After parsing, the arguments after the flag are available as the
|
||||
slice flag.Args() or individually as flag.Arg(i).
|
||||
The arguments are indexed from 0 through flag.NArg()-1.
|
||||
|
||||
The pflag package also defines some new functions that are not in flag,
|
||||
that give one-letter shorthands for flags. You can use these by appending
|
||||
'P' to the name of any function that defines a flag.
|
||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
var flagvar bool
|
||||
func init() {
|
||||
flag.BoolVarP("boolname", "b", true, "help message")
|
||||
}
|
||||
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
|
||||
Shorthand letters can be used with single dashes on the command line.
|
||||
Boolean shorthand flags can be combined with other shorthand flags.
|
||||
|
||||
Command line flag syntax:
|
||||
--flag // boolean flags only
|
||||
--flag=x
|
||||
|
||||
Unlike the flag package, a single dash before an option means something
|
||||
different than a double dash. Single dashes signify a series of shorthand
|
||||
letters for flags. All but the last shorthand letter must be boolean flags.
|
||||
// boolean flags
|
||||
-f
|
||||
-abc
|
||||
// non-boolean flags
|
||||
-n 1234
|
||||
-Ifile
|
||||
// mixed
|
||||
-abcs "hello"
|
||||
-abcn1234
|
||||
|
||||
Flag parsing stops after the terminator "--". Unlike the flag package,
|
||||
flags can be interspersed with arguments anywhere on the command line
|
||||
before this terminator.
|
||||
|
||||
Integer flags accept 1234, 0664, 0x1234 and may be negative.
|
||||
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
|
||||
TRUE, FALSE, True, False.
|
||||
Duration flags accept any input valid for time.ParseDuration.
|
||||
|
||||
The default set of command-line flags is controlled by
|
||||
top-level functions. The FlagSet type allows one to define
|
||||
independent sets of flags, such as to implement subcommands
|
||||
in a command-line interface. The methods of FlagSet are
|
||||
analogous to the top-level functions for the command-line
|
||||
flag set.
|
||||
*/
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
|
||||
var ErrHelp = errors.New("pflag: help requested")
|
||||
|
||||
// ErrorHandling defines how to handle flag parsing errors.
|
||||
type ErrorHandling int
|
||||
|
||||
const (
|
||||
ContinueOnError ErrorHandling = iota
|
||||
ExitOnError
|
||||
PanicOnError
|
||||
)
|
||||
|
||||
// NormalizedName is a flag name that has been normalized according to rules
|
||||
// for the FlagSet (e.g. making '-' and '_' equivalent).
|
||||
type NormalizedName string
|
||||
|
||||
// A FlagSet represents a set of defined flags.
|
||||
type FlagSet struct {
|
||||
// Usage is the function called when an error occurs while parsing flags.
|
||||
// The field is a function (not a method) that may be changed to point to
|
||||
// a custom error handler.
|
||||
Usage func()
|
||||
|
||||
name string
|
||||
parsed bool
|
||||
actual map[NormalizedName]*Flag
|
||||
formal map[NormalizedName]*Flag
|
||||
shorthands map[byte]*Flag
|
||||
args []string // arguments after flags
|
||||
exitOnError bool // does the program exit if there's an error?
|
||||
errorHandling ErrorHandling
|
||||
output io.Writer // nil means stderr; use out() accessor
|
||||
interspersed bool // allow interspersed option/non-option args
|
||||
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
|
||||
}
|
||||
|
||||
// A Flag represents the state of a flag.
|
||||
type Flag struct {
|
||||
Name string // name as it appears on command line
|
||||
Shorthand string // one-letter abbreviated flag
|
||||
Usage string // help message
|
||||
Value Value // value as set
|
||||
DefValue string // default value (as text); for usage message
|
||||
Changed bool // If the user set the value (or if left to default)
|
||||
Deprecated string // If this flag is deprecated, this string is the new or now thing to use
|
||||
Annotations map[string][]string // used by cobra.Command bash autocomple code
|
||||
}
|
||||
|
||||
// Value is the interface to the dynamic value stored in a flag.
|
||||
// (The default value is represented as a string.)
|
||||
type Value interface {
|
||||
String() string
|
||||
Set(string) error
|
||||
Type() string
|
||||
}
|
||||
|
||||
// sortFlags returns the flags as a slice in lexicographical sorted order.
|
||||
func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
|
||||
list := make(sort.StringSlice, len(flags))
|
||||
i := 0
|
||||
for k := range flags {
|
||||
list[i] = string(k)
|
||||
i++
|
||||
}
|
||||
list.Sort()
|
||||
result := make([]*Flag, len(list))
|
||||
for i, name := range list {
|
||||
result[i] = flags[NormalizedName(name)]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
|
||||
f.normalizeNameFunc = n
|
||||
for k, v := range f.formal {
|
||||
delete(f.formal, k)
|
||||
nname := f.normalizeFlagName(string(k))
|
||||
f.formal[nname] = v
|
||||
v.Name = string(nname)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
|
||||
if f.normalizeNameFunc != nil {
|
||||
return f.normalizeNameFunc
|
||||
}
|
||||
return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
|
||||
}
|
||||
|
||||
func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
|
||||
n := f.GetNormalizeFunc()
|
||||
return n(f, name)
|
||||
}
|
||||
|
||||
func (f *FlagSet) out() io.Writer {
|
||||
if f.output == nil {
|
||||
return os.Stderr
|
||||
}
|
||||
return f.output
|
||||
}
|
||||
|
||||
// SetOutput sets the destination for usage and error messages.
|
||||
// If output is nil, os.Stderr is used.
|
||||
func (f *FlagSet) SetOutput(output io.Writer) {
|
||||
f.output = output
|
||||
}
|
||||
|
||||
// VisitAll visits the flags in lexicographical order, calling fn for each.
|
||||
// It visits all flags, even those not set.
|
||||
func (f *FlagSet) VisitAll(fn func(*Flag)) {
|
||||
for _, flag := range sortFlags(f.formal) {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *FlagSet) HasFlags() bool {
|
||||
return len(f.formal) > 0
|
||||
}
|
||||
|
||||
// VisitAll visits the command-line flags in lexicographical order, calling
|
||||
// fn for each. It visits all flags, even those not set.
|
||||
func VisitAll(fn func(*Flag)) {
|
||||
CommandLine.VisitAll(fn)
|
||||
}
|
||||
|
||||
// Visit visits the flags in lexicographical order, calling fn for each.
|
||||
// It visits only those flags that have been set.
|
||||
func (f *FlagSet) Visit(fn func(*Flag)) {
|
||||
for _, flag := range sortFlags(f.actual) {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
// Visit visits the command-line flags in lexicographical order, calling fn
|
||||
// for each. It visits only those flags that have been set.
|
||||
func Visit(fn func(*Flag)) {
|
||||
CommandLine.Visit(fn)
|
||||
}
|
||||
|
||||
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
|
||||
func (f *FlagSet) Lookup(name string) *Flag {
|
||||
return f.lookup(f.normalizeFlagName(name))
|
||||
}
|
||||
|
||||
// lookup returns the Flag structure of the named flag, returning nil if none exists.
|
||||
func (f *FlagSet) lookup(name NormalizedName) *Flag {
|
||||
return f.formal[name]
|
||||
}
|
||||
|
||||
// Mark a flag deprecated in your program
|
||||
func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
|
||||
flag := f.Lookup(name)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("flag %q does not exist", name)
|
||||
}
|
||||
flag.Deprecated = usageMessage
|
||||
return nil
|
||||
}
|
||||
|
||||
// Lookup returns the Flag structure of the named command-line flag,
|
||||
// returning nil if none exists.
|
||||
func Lookup(name string) *Flag {
|
||||
return CommandLine.Lookup(name)
|
||||
}
|
||||
|
||||
// Set sets the value of the named flag.
|
||||
func (f *FlagSet) Set(name, value string) error {
|
||||
normalName := f.normalizeFlagName(name)
|
||||
flag, ok := f.formal[normalName]
|
||||
if !ok {
|
||||
return fmt.Errorf("no such flag -%v", name)
|
||||
}
|
||||
err := flag.Value.Set(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if f.actual == nil {
|
||||
f.actual = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.actual[normalName] = flag
|
||||
flag.Changed = true
|
||||
if len(flag.Deprecated) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set sets the value of the named command-line flag.
|
||||
func Set(name, value string) error {
|
||||
return CommandLine.Set(name, value)
|
||||
}
|
||||
|
||||
// PrintDefaults prints, to standard error unless configured
|
||||
// otherwise, the default values of all defined flags in the set.
|
||||
func (f *FlagSet) PrintDefaults() {
|
||||
f.VisitAll(func(flag *Flag) {
|
||||
if len(flag.Deprecated) > 0 {
|
||||
return
|
||||
}
|
||||
format := "--%s=%s: %s\n"
|
||||
if _, ok := flag.Value.(*stringValue); ok {
|
||||
// put quotes on the value
|
||||
format = "--%s=%q: %s\n"
|
||||
}
|
||||
if len(flag.Shorthand) > 0 {
|
||||
format = " -%s, " + format
|
||||
} else {
|
||||
format = " %s " + format
|
||||
}
|
||||
fmt.Fprintf(f.out(), format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f *FlagSet) FlagUsages() string {
|
||||
x := new(bytes.Buffer)
|
||||
|
||||
f.VisitAll(func(flag *Flag) {
|
||||
if len(flag.Deprecated) > 0 {
|
||||
return
|
||||
}
|
||||
format := "--%s=%s: %s\n"
|
||||
if _, ok := flag.Value.(*stringValue); ok {
|
||||
// put quotes on the value
|
||||
format = "--%s=%q: %s\n"
|
||||
}
|
||||
if len(flag.Shorthand) > 0 {
|
||||
format = " -%s, " + format
|
||||
} else {
|
||||
format = " %s " + format
|
||||
}
|
||||
fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
|
||||
})
|
||||
|
||||
return x.String()
|
||||
}
|
||||
|
||||
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
||||
func PrintDefaults() {
|
||||
CommandLine.PrintDefaults()
|
||||
}
|
||||
|
||||
// defaultUsage is the default function to print a usage message.
|
||||
func defaultUsage(f *FlagSet) {
|
||||
fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
|
||||
f.PrintDefaults()
|
||||
}
|
||||
|
||||
// NOTE: Usage is not just defaultUsage(CommandLine)
|
||||
// because it serves (via godoc flag Usage) as the example
|
||||
// for how to write your own usage function.
|
||||
|
||||
// Usage prints to standard error a usage message documenting all defined command-line flags.
|
||||
// The function is a variable that may be changed to point to a custom function.
|
||||
var Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
|
||||
PrintDefaults()
|
||||
}
|
||||
|
||||
// NFlag returns the number of flags that have been set.
|
||||
func (f *FlagSet) NFlag() int { return len(f.actual) }
|
||||
|
||||
// NFlag returns the number of command-line flags that have been set.
|
||||
func NFlag() int { return len(CommandLine.actual) }
|
||||
|
||||
// Arg returns the i'th argument. Arg(0) is the first remaining argument
|
||||
// after flags have been processed.
|
||||
func (f *FlagSet) Arg(i int) string {
|
||||
if i < 0 || i >= len(f.args) {
|
||||
return ""
|
||||
}
|
||||
return f.args[i]
|
||||
}
|
||||
|
||||
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
|
||||
// after flags have been processed.
|
||||
func Arg(i int) string {
|
||||
return CommandLine.Arg(i)
|
||||
}
|
||||
|
||||
// NArg is the number of arguments remaining after flags have been processed.
|
||||
func (f *FlagSet) NArg() int { return len(f.args) }
|
||||
|
||||
// NArg is the number of arguments remaining after flags have been processed.
|
||||
func NArg() int { return len(CommandLine.args) }
|
||||
|
||||
// Args returns the non-flag arguments.
|
||||
func (f *FlagSet) Args() []string { return f.args }
|
||||
|
||||
// Args returns the non-flag command-line arguments.
|
||||
func Args() []string { return CommandLine.args }
|
||||
|
||||
// Var defines a flag with the specified name and usage string. The type and
|
||||
// value of the flag are represented by the first argument, of type Value, which
|
||||
// typically holds a user-defined implementation of Value. For instance, the
|
||||
// caller could create a flag that turns a comma-separated string into a slice
|
||||
// of strings by giving the slice the methods of Value; in particular, Set would
|
||||
// decompose the comma-separated string into the slice.
|
||||
func (f *FlagSet) Var(value Value, name string, usage string) {
|
||||
f.VarP(value, name, "", usage)
|
||||
}
|
||||
|
||||
// Like Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
|
||||
// Remember the default value as a string; it won't change.
|
||||
flag := &Flag{
|
||||
Name: name,
|
||||
Shorthand: shorthand,
|
||||
Usage: usage,
|
||||
Value: value,
|
||||
DefValue: value.String(),
|
||||
}
|
||||
f.AddFlag(flag)
|
||||
}
|
||||
|
||||
func (f *FlagSet) AddFlag(flag *Flag) {
|
||||
// Call normalizeFlagName function only once
|
||||
var normalizedFlagName NormalizedName = f.normalizeFlagName(flag.Name)
|
||||
|
||||
_, alreadythere := f.formal[normalizedFlagName]
|
||||
if alreadythere {
|
||||
msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
|
||||
fmt.Fprintln(f.out(), msg)
|
||||
panic(msg) // Happens only if flags are declared with identical names
|
||||
}
|
||||
if f.formal == nil {
|
||||
f.formal = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
|
||||
flag.Name = string(normalizedFlagName)
|
||||
f.formal[normalizedFlagName] = flag
|
||||
|
||||
if len(flag.Shorthand) == 0 {
|
||||
return
|
||||
}
|
||||
if len(flag.Shorthand) > 1 {
|
||||
fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
|
||||
panic("shorthand is more than one character")
|
||||
}
|
||||
if f.shorthands == nil {
|
||||
f.shorthands = make(map[byte]*Flag)
|
||||
}
|
||||
c := flag.Shorthand[0]
|
||||
old, alreadythere := f.shorthands[c]
|
||||
if alreadythere {
|
||||
fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
|
||||
panic("shorthand redefinition")
|
||||
}
|
||||
f.shorthands[c] = flag
|
||||
}
|
||||
|
||||
// Var defines a flag with the specified name and usage string. The type and
|
||||
// value of the flag are represented by the first argument, of type Value, which
|
||||
// typically holds a user-defined implementation of Value. For instance, the
|
||||
// caller could create a flag that turns a comma-separated string into a slice
|
||||
// of strings by giving the slice the methods of Value; in particular, Set would
|
||||
// decompose the comma-separated string into the slice.
|
||||
func Var(value Value, name string, usage string) {
|
||||
CommandLine.VarP(value, name, "", usage)
|
||||
}
|
||||
|
||||
// Like Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func VarP(value Value, name, shorthand, usage string) {
|
||||
CommandLine.VarP(value, name, shorthand, usage)
|
||||
}
|
||||
|
||||
// failf prints to standard error a formatted error and usage message and
|
||||
// returns the error.
|
||||
func (f *FlagSet) failf(format string, a ...interface{}) error {
|
||||
err := fmt.Errorf(format, a...)
|
||||
fmt.Fprintln(f.out(), err)
|
||||
f.usage()
|
||||
return err
|
||||
}
|
||||
|
||||
// usage calls the Usage method for the flag set, or the usage function if
|
||||
// the flag set is CommandLine.
|
||||
func (f *FlagSet) usage() {
|
||||
if f == CommandLine {
|
||||
Usage()
|
||||
} else if f.Usage == nil {
|
||||
defaultUsage(f)
|
||||
} else {
|
||||
f.Usage()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
|
||||
if err := flag.Value.Set(value); err != nil {
|
||||
return f.failf("invalid argument %q for %s: %v", value, origArg, err)
|
||||
}
|
||||
// mark as visited for Visit()
|
||||
if f.actual == nil {
|
||||
f.actual = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.actual[f.normalizeFlagName(flag.Name)] = flag
|
||||
flag.Changed = true
|
||||
if len(flag.Deprecated) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
|
||||
a = args
|
||||
name := s[2:]
|
||||
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
|
||||
err = f.failf("bad flag syntax: %s", s)
|
||||
return
|
||||
}
|
||||
split := strings.SplitN(name, "=", 2)
|
||||
name = split[0]
|
||||
flag, alreadythere := f.formal[f.normalizeFlagName(name)]
|
||||
if !alreadythere {
|
||||
if name == "help" { // special case for nice help message.
|
||||
f.usage()
|
||||
return a, ErrHelp
|
||||
}
|
||||
err = f.failf("unknown flag: --%s", name)
|
||||
return
|
||||
}
|
||||
var value string
|
||||
if len(split) == 2 {
|
||||
// '--flag=arg'
|
||||
value = split[1]
|
||||
} else if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() {
|
||||
// '--flag' (where flag is a bool)
|
||||
value = "true"
|
||||
} else {
|
||||
// '--flag' (where flag was not a bool)
|
||||
err = f.failf("flag needs an argument: %s", s)
|
||||
return
|
||||
}
|
||||
err = f.setFlag(flag, value, s)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
|
||||
outArgs = args
|
||||
outShorts = shorthands[1:]
|
||||
c := shorthands[0]
|
||||
|
||||
flag, alreadythere := f.shorthands[c]
|
||||
if !alreadythere {
|
||||
if c == 'h' { // special case for nice help message.
|
||||
f.usage()
|
||||
err = ErrHelp
|
||||
return
|
||||
}
|
||||
//TODO continue on error
|
||||
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
var value string
|
||||
if len(shorthands) > 2 && shorthands[1] == '=' {
|
||||
value = shorthands[2:]
|
||||
outShorts = ""
|
||||
} else if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() {
|
||||
value = "true"
|
||||
} else if len(shorthands) > 1 {
|
||||
value = shorthands[1:]
|
||||
outShorts = ""
|
||||
} else if len(args) > 0 {
|
||||
value = args[0]
|
||||
outArgs = args[1:]
|
||||
} else {
|
||||
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
err = f.setFlag(flag, value, shorthands)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
|
||||
a = args
|
||||
shorthands := s[1:]
|
||||
|
||||
for len(shorthands) > 0 {
|
||||
shorthands, a, err = f.parseSingleShortArg(shorthands, args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseArgs(args []string) (err error) {
|
||||
for len(args) > 0 {
|
||||
s := args[0]
|
||||
args = args[1:]
|
||||
if len(s) == 0 || s[0] != '-' || len(s) == 1 {
|
||||
if !f.interspersed {
|
||||
f.args = append(f.args, s)
|
||||
f.args = append(f.args, args...)
|
||||
return nil
|
||||
}
|
||||
f.args = append(f.args, s)
|
||||
continue
|
||||
}
|
||||
|
||||
if s[1] == '-' {
|
||||
if len(s) == 2 { // "--" terminates the flags
|
||||
f.args = append(f.args, args...)
|
||||
break
|
||||
}
|
||||
args, err = f.parseLongArg(s, args)
|
||||
} else {
|
||||
args, err = f.parseShortArg(s, args)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Parse parses flag definitions from the argument list, which should not
|
||||
// include the command name. Must be called after all flags in the FlagSet
|
||||
// are defined and before flags are accessed by the program.
|
||||
// The return value will be ErrHelp if -help was set but not defined.
|
||||
func (f *FlagSet) Parse(arguments []string) error {
|
||||
f.parsed = true
|
||||
f.args = make([]string, 0, len(arguments))
|
||||
err := f.parseArgs(arguments)
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
return err
|
||||
case ExitOnError:
|
||||
os.Exit(2)
|
||||
case PanicOnError:
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parsed reports whether f.Parse has been called.
|
||||
func (f *FlagSet) Parsed() bool {
|
||||
return f.parsed
|
||||
}
|
||||
|
||||
// Parse parses the command-line flags from os.Args[1:]. Must be called
|
||||
// after all flags are defined and before flags are accessed by the program.
|
||||
func Parse() {
|
||||
// Ignore errors; CommandLine is set for ExitOnError.
|
||||
CommandLine.Parse(os.Args[1:])
|
||||
}
|
||||
|
||||
// Whether to support interspersed option/non-option arguments.
|
||||
func SetInterspersed(interspersed bool) {
|
||||
CommandLine.SetInterspersed(interspersed)
|
||||
}
|
||||
|
||||
// Parsed returns true if the command-line flags have been parsed.
|
||||
func Parsed() bool {
|
||||
return CommandLine.Parsed()
|
||||
}
|
||||
|
||||
// The default set of command-line flags, parsed from os.Args.
|
||||
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
|
||||
|
||||
// NewFlagSet returns a new, empty flag set with the specified name and
|
||||
// error handling property.
|
||||
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
|
||||
f := &FlagSet{
|
||||
name: name,
|
||||
errorHandling: errorHandling,
|
||||
interspersed: true,
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// Whether to support interspersed option/non-option arguments.
|
||||
func (f *FlagSet) SetInterspersed(interspersed bool) {
|
||||
f.interspersed = interspersed
|
||||
}
|
||||
|
||||
// Init sets the name and error handling property for a flag set.
|
||||
// By default, the zero FlagSet uses an empty name and the
|
||||
// ContinueOnError error handling policy.
|
||||
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
|
||||
f.name = name
|
||||
f.errorHandling = errorHandling
|
||||
}
|
658
Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go
generated
vendored
Normal file
658
Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go
generated
vendored
Normal file
|
@ -0,0 +1,658 @@
|
|||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
test_bool = Bool("test_bool", false, "bool value")
|
||||
test_int = Int("test_int", 0, "int value")
|
||||
test_int64 = Int64("test_int64", 0, "int64 value")
|
||||
test_uint = Uint("test_uint", 0, "uint value")
|
||||
test_uint64 = Uint64("test_uint64", 0, "uint64 value")
|
||||
test_string = String("test_string", "0", "string value")
|
||||
test_float64 = Float64("test_float64", 0, "float64 value")
|
||||
test_duration = Duration("test_duration", 0, "time.Duration value")
|
||||
normalizeFlagNameInvocations = 0
|
||||
)
|
||||
|
||||
func boolString(s string) string {
|
||||
if s == "0" {
|
||||
return "false"
|
||||
}
|
||||
return "true"
|
||||
}
|
||||
|
||||
func TestEverything(t *testing.T) {
|
||||
m := make(map[string]*Flag)
|
||||
desired := "0"
|
||||
visitor := func(f *Flag) {
|
||||
if len(f.Name) > 5 && f.Name[0:5] == "test_" {
|
||||
m[f.Name] = f
|
||||
ok := false
|
||||
switch {
|
||||
case f.Value.String() == desired:
|
||||
ok = true
|
||||
case f.Name == "test_bool" && f.Value.String() == boolString(desired):
|
||||
ok = true
|
||||
case f.Name == "test_duration" && f.Value.String() == desired+"s":
|
||||
ok = true
|
||||
}
|
||||
if !ok {
|
||||
t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
VisitAll(visitor)
|
||||
if len(m) != 8 {
|
||||
t.Error("VisitAll misses some flags")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
m = make(map[string]*Flag)
|
||||
Visit(visitor)
|
||||
if len(m) != 0 {
|
||||
t.Errorf("Visit sees unset flags")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
// Now set all flags
|
||||
Set("test_bool", "true")
|
||||
Set("test_int", "1")
|
||||
Set("test_int64", "1")
|
||||
Set("test_uint", "1")
|
||||
Set("test_uint64", "1")
|
||||
Set("test_string", "1")
|
||||
Set("test_float64", "1")
|
||||
Set("test_duration", "1s")
|
||||
desired = "1"
|
||||
Visit(visitor)
|
||||
if len(m) != 8 {
|
||||
t.Error("Visit fails after set")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
// Now test they're visited in sort order.
|
||||
var flagNames []string
|
||||
Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
|
||||
if !sort.StringsAreSorted(flagNames) {
|
||||
t.Errorf("flag names not sorted: %v", flagNames)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsage(t *testing.T) {
|
||||
called := false
|
||||
ResetForTesting(func() { called = true })
|
||||
if GetCommandLine().Parse([]string{"--x"}) == nil {
|
||||
t.Error("parse did not fail for unknown flag")
|
||||
}
|
||||
if !called {
|
||||
t.Error("did not call Usage for unknown flag")
|
||||
}
|
||||
}
|
||||
|
||||
func testParse(f *FlagSet, t *testing.T) {
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
boolFlag := f.Bool("bool", false, "bool value")
|
||||
bool2Flag := f.Bool("bool2", false, "bool2 value")
|
||||
bool3Flag := f.Bool("bool3", false, "bool3 value")
|
||||
intFlag := f.Int("int", 0, "int value")
|
||||
int8Flag := f.Int8("int8", 0, "int value")
|
||||
int32Flag := f.Int32("int32", 0, "int value")
|
||||
int64Flag := f.Int64("int64", 0, "int64 value")
|
||||
uintFlag := f.Uint("uint", 0, "uint value")
|
||||
uint8Flag := f.Uint8("uint8", 0, "uint value")
|
||||
uint16Flag := f.Uint16("uint16", 0, "uint value")
|
||||
uint32Flag := f.Uint32("uint32", 0, "uint value")
|
||||
uint64Flag := f.Uint64("uint64", 0, "uint64 value")
|
||||
stringFlag := f.String("string", "0", "string value")
|
||||
float32Flag := f.Float32("float32", 0, "float32 value")
|
||||
float64Flag := f.Float64("float64", 0, "float64 value")
|
||||
ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value")
|
||||
maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value")
|
||||
durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
|
||||
extra := "one-extra-argument"
|
||||
args := []string{
|
||||
"--bool",
|
||||
"--bool2=true",
|
||||
"--bool3=false",
|
||||
"--int=22",
|
||||
"--int8=-8",
|
||||
"--int32=-32",
|
||||
"--int64=0x23",
|
||||
"--uint=24",
|
||||
"--uint8=8",
|
||||
"--uint16=16",
|
||||
"--uint32=32",
|
||||
"--uint64=25",
|
||||
"--string=hello",
|
||||
"--float32=-172e12",
|
||||
"--float64=2718e28",
|
||||
"--ip=10.11.12.13",
|
||||
"--mask=255.255.255.0",
|
||||
"--duration=2m",
|
||||
extra,
|
||||
}
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *boolFlag != true {
|
||||
t.Error("bool flag should be true, is ", *boolFlag)
|
||||
}
|
||||
if *bool2Flag != true {
|
||||
t.Error("bool2 flag should be true, is ", *bool2Flag)
|
||||
}
|
||||
if *bool3Flag != false {
|
||||
t.Error("bool3 flag should be false, is ", *bool2Flag)
|
||||
}
|
||||
if *intFlag != 22 {
|
||||
t.Error("int flag should be 22, is ", *intFlag)
|
||||
}
|
||||
if *int8Flag != -8 {
|
||||
t.Error("int8 flag should be 0x23, is ", *int8Flag)
|
||||
}
|
||||
if *int32Flag != -32 {
|
||||
t.Error("int32 flag should be 0x23, is ", *int32Flag)
|
||||
}
|
||||
if *int64Flag != 0x23 {
|
||||
t.Error("int64 flag should be 0x23, is ", *int64Flag)
|
||||
}
|
||||
if *uintFlag != 24 {
|
||||
t.Error("uint flag should be 24, is ", *uintFlag)
|
||||
}
|
||||
if *uint8Flag != 8 {
|
||||
t.Error("uint8 flag should be 8, is ", *uint8Flag)
|
||||
}
|
||||
if *uint16Flag != 16 {
|
||||
t.Error("uint16 flag should be 16, is ", *uint16Flag)
|
||||
}
|
||||
if *uint32Flag != 32 {
|
||||
t.Error("uint32 flag should be 32, is ", *uint32Flag)
|
||||
}
|
||||
if *uint64Flag != 25 {
|
||||
t.Error("uint64 flag should be 25, is ", *uint64Flag)
|
||||
}
|
||||
if *stringFlag != "hello" {
|
||||
t.Error("string flag should be `hello`, is ", *stringFlag)
|
||||
}
|
||||
if *float32Flag != -172e12 {
|
||||
t.Error("float64 flag should be -172e12, is ", *float64Flag)
|
||||
}
|
||||
if *float64Flag != 2718e28 {
|
||||
t.Error("float64 flag should be 2718e28, is ", *float64Flag)
|
||||
}
|
||||
if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() {
|
||||
t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String())
|
||||
}
|
||||
if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) {
|
||||
t.Error("ip flag should be 10.11.12.13, is ", *ipFlag)
|
||||
}
|
||||
if *durationFlag != 2*time.Minute {
|
||||
t.Error("duration flag should be 2m, is ", *durationFlag)
|
||||
}
|
||||
if len(f.Args()) != 1 {
|
||||
t.Error("expected one argument, got", len(f.Args()))
|
||||
} else if f.Args()[0] != extra {
|
||||
t.Errorf("expected argument %q got %q", extra, f.Args()[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestShorthand(t *testing.T) {
|
||||
f := NewFlagSet("shorthand", ContinueOnError)
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
boolaFlag := f.BoolP("boola", "a", false, "bool value")
|
||||
boolbFlag := f.BoolP("boolb", "b", false, "bool2 value")
|
||||
boolcFlag := f.BoolP("boolc", "c", false, "bool3 value")
|
||||
booldFlag := f.BoolP("boold", "d", false, "bool4 value")
|
||||
stringaFlag := f.StringP("stringa", "s", "0", "string value")
|
||||
stringzFlag := f.StringP("stringz", "z", "0", "string value")
|
||||
extra := "interspersed-argument"
|
||||
notaflag := "--i-look-like-a-flag"
|
||||
args := []string{
|
||||
"-ab",
|
||||
extra,
|
||||
"-cs",
|
||||
"hello",
|
||||
"-z=something",
|
||||
"-d=true",
|
||||
"--",
|
||||
notaflag,
|
||||
}
|
||||
f.SetOutput(ioutil.Discard)
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Error("expected no error, got ", err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *boolaFlag != true {
|
||||
t.Error("boola flag should be true, is ", *boolaFlag)
|
||||
}
|
||||
if *boolbFlag != true {
|
||||
t.Error("boolb flag should be true, is ", *boolbFlag)
|
||||
}
|
||||
if *boolcFlag != true {
|
||||
t.Error("boolc flag should be true, is ", *boolcFlag)
|
||||
}
|
||||
if *booldFlag != true {
|
||||
t.Error("boold flag should be true, is ", *booldFlag)
|
||||
}
|
||||
if *stringaFlag != "hello" {
|
||||
t.Error("stringa flag should be `hello`, is ", *stringaFlag)
|
||||
}
|
||||
if *stringzFlag != "something" {
|
||||
t.Error("stringz flag should be `something`, is ", *stringzFlag)
|
||||
}
|
||||
if len(f.Args()) != 2 {
|
||||
t.Error("expected one argument, got", len(f.Args()))
|
||||
} else if f.Args()[0] != extra {
|
||||
t.Errorf("expected argument %q got %q", extra, f.Args()[0])
|
||||
} else if f.Args()[1] != notaflag {
|
||||
t.Errorf("expected argument %q got %q", notaflag, f.Args()[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
ResetForTesting(func() { t.Error("bad parse") })
|
||||
testParse(GetCommandLine(), t)
|
||||
}
|
||||
|
||||
func TestFlagSetParse(t *testing.T) {
|
||||
testParse(NewFlagSet("test", ContinueOnError), t)
|
||||
}
|
||||
|
||||
func replaceSeparators(name string, from []string, to string) string {
|
||||
result := name
|
||||
for _, sep := range from {
|
||||
result = strings.Replace(result, sep, to, -1)
|
||||
}
|
||||
// Type convert to indicate normalization has been done.
|
||||
return result
|
||||
}
|
||||
|
||||
func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName {
|
||||
seps := []string{"-", "_"}
|
||||
name = replaceSeparators(name, seps, ".")
|
||||
normalizeFlagNameInvocations++
|
||||
|
||||
return NormalizedName(name)
|
||||
}
|
||||
|
||||
func testWordSepNormalizedNames(args []string, t *testing.T) {
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
withDashFlag := f.Bool("with-dash-flag", false, "bool value")
|
||||
// Set this after some flags have been added and before others.
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
withUnderFlag := f.Bool("with_under_flag", false, "bool value")
|
||||
withBothFlag := f.Bool("with-both_flag", false, "bool value")
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *withDashFlag != true {
|
||||
t.Error("withDashFlag flag should be true, is ", *withDashFlag)
|
||||
}
|
||||
if *withUnderFlag != true {
|
||||
t.Error("withUnderFlag flag should be true, is ", *withUnderFlag)
|
||||
}
|
||||
if *withBothFlag != true {
|
||||
t.Error("withBothFlag flag should be true, is ", *withBothFlag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWordSepNormalizedNames(t *testing.T) {
|
||||
args := []string{
|
||||
"--with-dash-flag",
|
||||
"--with-under-flag",
|
||||
"--with-both-flag",
|
||||
}
|
||||
testWordSepNormalizedNames(args, t)
|
||||
|
||||
args = []string{
|
||||
"--with_dash_flag",
|
||||
"--with_under_flag",
|
||||
"--with_both_flag",
|
||||
}
|
||||
testWordSepNormalizedNames(args, t)
|
||||
|
||||
args = []string{
|
||||
"--with-dash_flag",
|
||||
"--with-under_flag",
|
||||
"--with-both_flag",
|
||||
}
|
||||
testWordSepNormalizedNames(args, t)
|
||||
}
|
||||
|
||||
func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName {
|
||||
seps := []string{"-", "_"}
|
||||
|
||||
oldName := replaceSeparators("old-valid_flag", seps, ".")
|
||||
newName := replaceSeparators("valid-flag", seps, ".")
|
||||
|
||||
name = replaceSeparators(name, seps, ".")
|
||||
switch name {
|
||||
case oldName:
|
||||
name = newName
|
||||
break
|
||||
}
|
||||
|
||||
return NormalizedName(name)
|
||||
}
|
||||
|
||||
func TestCustomNormalizedNames(t *testing.T) {
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
|
||||
validFlag := f.Bool("valid-flag", false, "bool value")
|
||||
f.SetNormalizeFunc(aliasAndWordSepFlagNames)
|
||||
someOtherFlag := f.Bool("some-other-flag", false, "bool value")
|
||||
|
||||
args := []string{"--old_valid_flag", "--some-other_flag"}
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if *validFlag != true {
|
||||
t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag)
|
||||
}
|
||||
if *someOtherFlag != true {
|
||||
t.Error("someOtherFlag should be true, is ", *someOtherFlag)
|
||||
}
|
||||
}
|
||||
|
||||
// Every flag we add, the name (displayed also in usage) should normalized
|
||||
func TestNormalizationFuncShouldChangeFlagName(t *testing.T) {
|
||||
// Test normalization after addition
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
|
||||
f.Bool("valid_flag", false, "bool value")
|
||||
if f.Lookup("valid_flag").Name != "valid_flag" {
|
||||
t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name)
|
||||
}
|
||||
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
if f.Lookup("valid_flag").Name != "valid.flag" {
|
||||
t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
|
||||
}
|
||||
|
||||
// Test normalization before addition
|
||||
f = NewFlagSet("normalized", ContinueOnError)
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
|
||||
f.Bool("valid_flag", false, "bool value")
|
||||
if f.Lookup("valid_flag").Name != "valid.flag" {
|
||||
t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Declare a user-defined flag type.
|
||||
type flagVar []string
|
||||
|
||||
func (f *flagVar) String() string {
|
||||
return fmt.Sprint([]string(*f))
|
||||
}
|
||||
|
||||
func (f *flagVar) Set(value string) error {
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *flagVar) Type() string {
|
||||
return "flagVar"
|
||||
}
|
||||
|
||||
func TestUserDefined(t *testing.T) {
|
||||
var flags FlagSet
|
||||
flags.Init("test", ContinueOnError)
|
||||
var v flagVar
|
||||
flags.VarP(&v, "v", "v", "usage")
|
||||
if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(v) != 3 {
|
||||
t.Fatal("expected 3 args; got ", len(v))
|
||||
}
|
||||
expect := "[1 2 3]"
|
||||
if v.String() != expect {
|
||||
t.Errorf("expected value %q got %q", expect, v.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetOutput(t *testing.T) {
|
||||
var flags FlagSet
|
||||
var buf bytes.Buffer
|
||||
flags.SetOutput(&buf)
|
||||
flags.Init("test", ContinueOnError)
|
||||
flags.Parse([]string{"--unknown"})
|
||||
if out := buf.String(); !strings.Contains(out, "--unknown") {
|
||||
t.Logf("expected output mentioning unknown; got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// This tests that one can reset the flags. This still works but not well, and is
|
||||
// superseded by FlagSet.
|
||||
func TestChangingArgs(t *testing.T) {
|
||||
ResetForTesting(func() { t.Fatal("bad parse") })
|
||||
oldArgs := os.Args
|
||||
defer func() { os.Args = oldArgs }()
|
||||
os.Args = []string{"cmd", "--before", "subcmd"}
|
||||
before := Bool("before", false, "")
|
||||
if err := GetCommandLine().Parse(os.Args[1:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := Arg(0)
|
||||
os.Args = []string{"subcmd", "--after", "args"}
|
||||
after := Bool("after", false, "")
|
||||
Parse()
|
||||
args := Args()
|
||||
|
||||
if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
|
||||
t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
|
||||
}
|
||||
}
|
||||
|
||||
// Test that -help invokes the usage message and returns ErrHelp.
|
||||
func TestHelp(t *testing.T) {
|
||||
var helpCalled = false
|
||||
fs := NewFlagSet("help test", ContinueOnError)
|
||||
fs.Usage = func() { helpCalled = true }
|
||||
var flag bool
|
||||
fs.BoolVar(&flag, "flag", false, "regular flag")
|
||||
// Regular flag invocation should work
|
||||
err := fs.Parse([]string{"--flag=true"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
if !flag {
|
||||
t.Error("flag was not set by --flag")
|
||||
}
|
||||
if helpCalled {
|
||||
t.Error("help called for regular flag")
|
||||
helpCalled = false // reset for next test
|
||||
}
|
||||
// Help flag should work as expected.
|
||||
err = fs.Parse([]string{"--help"})
|
||||
if err == nil {
|
||||
t.Fatal("error expected")
|
||||
}
|
||||
if err != ErrHelp {
|
||||
t.Fatal("expected ErrHelp; got ", err)
|
||||
}
|
||||
if !helpCalled {
|
||||
t.Fatal("help was not called")
|
||||
}
|
||||
// If we define a help flag, that should override.
|
||||
var help bool
|
||||
fs.BoolVar(&help, "help", false, "help flag")
|
||||
helpCalled = false
|
||||
err = fs.Parse([]string{"--help"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error for defined --help; got ", err)
|
||||
}
|
||||
if helpCalled {
|
||||
t.Fatal("help was called; should not have been for defined help flag")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoInterspersed(t *testing.T) {
|
||||
f := NewFlagSet("test", ContinueOnError)
|
||||
f.SetInterspersed(false)
|
||||
f.Bool("true", true, "always true")
|
||||
f.Bool("false", false, "always false")
|
||||
err := f.Parse([]string{"--true", "break", "--false"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
args := f.Args()
|
||||
if len(args) != 2 || args[0] != "break" || args[1] != "--false" {
|
||||
t.Fatal("expected interspersed options/non-options to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTermination(t *testing.T) {
|
||||
f := NewFlagSet("termination", ContinueOnError)
|
||||
boolFlag := f.BoolP("bool", "l", false, "bool value")
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
arg1 := "ls"
|
||||
arg2 := "-l"
|
||||
args := []string{
|
||||
"--",
|
||||
arg1,
|
||||
arg2,
|
||||
}
|
||||
f.SetOutput(ioutil.Discard)
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *boolFlag {
|
||||
t.Error("expected boolFlag=false, got true")
|
||||
}
|
||||
if len(f.Args()) != 2 {
|
||||
t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args())
|
||||
}
|
||||
if f.Args()[0] != arg1 {
|
||||
t.Errorf("expected argument %q got %q", arg1, f.Args()[0])
|
||||
}
|
||||
if f.Args()[1] != arg2 {
|
||||
t.Errorf("expected argument %q got %q", arg2, f.Args()[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagInDocs(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("badflag", true, "always true")
|
||||
f.MarkDeprecated("badflag", "use --good-flag instead")
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
f.SetOutput(out)
|
||||
f.PrintDefaults()
|
||||
|
||||
if strings.Contains(out.String(), "badflag") {
|
||||
t.Errorf("found deprecated flag in usage!")
|
||||
}
|
||||
}
|
||||
|
||||
func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) {
|
||||
oldStderr := os.Stderr
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stderr = w
|
||||
|
||||
err := f.Parse(args)
|
||||
|
||||
outC := make(chan string)
|
||||
// copy the output in a separate goroutine so printing can't block indefinitely
|
||||
go func() {
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
outC <- buf.String()
|
||||
}()
|
||||
|
||||
w.Close()
|
||||
os.Stderr = oldStderr
|
||||
out := <-outC
|
||||
|
||||
return out, err
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagUsage(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("badflag", true, "always true")
|
||||
usageMsg := "use --good-flag instead"
|
||||
f.MarkDeprecated("badflag", usageMsg)
|
||||
|
||||
args := []string{"--badflag"}
|
||||
out, err := parseReturnStderr(t, f, args)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(out, usageMsg) {
|
||||
t.Errorf("usageMsg not printed when using a deprecated flag!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagUsageNormalized(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("bad-double_flag", true, "always true")
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
usageMsg := "use --good-flag instead"
|
||||
f.MarkDeprecated("bad_double-flag", usageMsg)
|
||||
|
||||
args := []string{"--bad_double_flag"}
|
||||
out, err := parseReturnStderr(t, f, args)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(out, usageMsg) {
|
||||
t.Errorf("usageMsg not printed when using a deprecated flag!")
|
||||
}
|
||||
}
|
||||
|
||||
// Name normalization function should be called only once on flag addition
|
||||
func TestMultipleNormalizeFlagNameInvocations(t *testing.T) {
|
||||
normalizeFlagNameInvocations = 0
|
||||
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
f.Bool("with_under_flag", false, "bool value")
|
||||
|
||||
if normalizeFlagNameInvocations != 1 {
|
||||
t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations)
|
||||
}
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/float32.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/float32.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- float32 Value
|
||||
type float32Value float32
|
||||
|
||||
func newFloat32Value(val float32, p *float32) *float32Value {
|
||||
*p = val
|
||||
return (*float32Value)(p)
|
||||
}
|
||||
|
||||
func (f *float32Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 32)
|
||||
*f = float32Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float32Value) Type() string {
|
||||
return "float32"
|
||||
}
|
||||
|
||||
func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
|
||||
// Float32Var defines a float32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
|
||||
f.VarP(newFloat32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
|
||||
f.VarP(newFloat32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32Var defines a float32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32 variable in which to store the value of the flag.
|
||||
func Float32Var(p *float32, name string, value float32, usage string) {
|
||||
CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
|
||||
CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32 defines a float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
|
||||
p := new(float32)
|
||||
f.Float32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Float32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
|
||||
p := new(float32)
|
||||
f.Float32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float32 defines a float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float32 variable that stores the value of the flag.
|
||||
func Float32(name string, value float32, usage string) *float32 {
|
||||
return CommandLine.Float32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Float32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32P(name, shorthand string, value float32, usage string) *float32 {
|
||||
return CommandLine.Float32P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/float64.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/float64.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- float64 Value
|
||||
type float64Value float64
|
||||
|
||||
func newFloat64Value(val float64, p *float64) *float64Value {
|
||||
*p = val
|
||||
return (*float64Value)(p)
|
||||
}
|
||||
|
||||
func (f *float64Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
*f = float64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float64Value) Type() string {
|
||||
return "float64"
|
||||
}
|
||||
|
||||
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
|
||||
f.VarP(newFloat64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
|
||||
f.VarP(newFloat64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func Float64Var(p *float64, name string, value float64, usage string) {
|
||||
CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
|
||||
CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Float64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func Float64(name string, value float64, usage string) *float64 {
|
||||
return CommandLine.Float64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Float64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float64P(name, shorthand string, value float64, usage string) *float64 {
|
||||
return CommandLine.Float64P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int Value
|
||||
type intValue int
|
||||
|
||||
func newIntValue(val int, p *int) *intValue {
|
||||
*p = val
|
||||
return (*intValue)(p)
|
||||
}
|
||||
|
||||
func (i *intValue) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 64)
|
||||
*i = intValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *intValue) Type() string {
|
||||
return "int"
|
||||
}
|
||||
|
||||
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// IntVar defines an int flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
|
||||
f.VarP(newIntValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IntVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
|
||||
f.VarP(newIntValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IntVar defines an int flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
func IntVar(p *int, name string, value int, usage string) {
|
||||
CommandLine.VarP(newIntValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IntVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IntVarP(p *int, name, shorthand string, value int, usage string) {
|
||||
CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int defines an int flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int(name string, value int, usage string) *int {
|
||||
p := new(int)
|
||||
f.IntVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
|
||||
p := new(int)
|
||||
f.IntVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int defines an int flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
func Int(name string, value int, usage string) *int {
|
||||
return CommandLine.IntP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IntP(name, shorthand string, value int, usage string) *int {
|
||||
return CommandLine.IntP(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int32.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int32.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int32 Value
|
||||
type int32Value int32
|
||||
|
||||
func newInt32Value(val int32, p *int32) *int32Value {
|
||||
*p = val
|
||||
return (*int32Value)(p)
|
||||
}
|
||||
|
||||
func (i *int32Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 32)
|
||||
*i = int32Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int32Value) Type() string {
|
||||
return "int32"
|
||||
}
|
||||
|
||||
func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Int32Var defines an int32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
|
||||
f.VarP(newInt32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
|
||||
f.VarP(newInt32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int32Var defines an int32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int32 variable in which to store the value of the flag.
|
||||
func Int32Var(p *int32, name string, value int32, usage string) {
|
||||
CommandLine.VarP(newInt32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
|
||||
CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int32 defines an int32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
|
||||
p := new(int32)
|
||||
f.Int32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
|
||||
p := new(int32)
|
||||
f.Int32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int32 defines an int32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int32 variable that stores the value of the flag.
|
||||
func Int32(name string, value int32, usage string) *int32 {
|
||||
return CommandLine.Int32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int32P(name, shorthand string, value int32, usage string) *int32 {
|
||||
return CommandLine.Int32P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int64.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int64.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int64 Value
|
||||
type int64Value int64
|
||||
|
||||
func newInt64Value(val int64, p *int64) *int64Value {
|
||||
*p = val
|
||||
return (*int64Value)(p)
|
||||
}
|
||||
|
||||
func (i *int64Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 64)
|
||||
*i = int64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int64Value) Type() string {
|
||||
return "int64"
|
||||
}
|
||||
|
||||
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Int64Var defines an int64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
|
||||
f.VarP(newInt64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
|
||||
f.VarP(newInt64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int64Var defines an int64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int64 variable in which to store the value of the flag.
|
||||
func Int64Var(p *int64, name string, value int64, usage string) {
|
||||
CommandLine.VarP(newInt64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
|
||||
CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int64 defines an int64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
|
||||
p := new(int64)
|
||||
f.Int64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
|
||||
p := new(int64)
|
||||
f.Int64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int64 defines an int64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int64 variable that stores the value of the flag.
|
||||
func Int64(name string, value int64, usage string) *int64 {
|
||||
return CommandLine.Int64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int64P(name, shorthand string, value int64, usage string) *int64 {
|
||||
return CommandLine.Int64P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int8.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int8.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int8 Value
|
||||
type int8Value int8
|
||||
|
||||
func newInt8Value(val int8, p *int8) *int8Value {
|
||||
*p = val
|
||||
return (*int8Value)(p)
|
||||
}
|
||||
|
||||
func (i *int8Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 8)
|
||||
*i = int8Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int8Value) Type() string {
|
||||
return "int8"
|
||||
}
|
||||
|
||||
func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Int8Var defines an int8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int8 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
|
||||
f.VarP(newInt8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
|
||||
f.VarP(newInt8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int8Var defines an int8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int8 variable in which to store the value of the flag.
|
||||
func Int8Var(p *int8, name string, value int8, usage string) {
|
||||
CommandLine.VarP(newInt8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
|
||||
CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int8 defines an int8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int8 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
|
||||
p := new(int8)
|
||||
f.Int8VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
|
||||
p := new(int8)
|
||||
f.Int8VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int8 defines an int8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int8 variable that stores the value of the flag.
|
||||
func Int8(name string, value int8, usage string) *int8 {
|
||||
return CommandLine.Int8P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int8P(name, shorthand string, value int8, usage string) *int8 {
|
||||
return CommandLine.Int8P(name, shorthand, value, usage)
|
||||
}
|
76
Godeps/_workspace/src/github.com/spf13/pflag/ip.go
generated
vendored
Normal file
76
Godeps/_workspace/src/github.com/spf13/pflag/ip.go
generated
vendored
Normal file
|
@ -0,0 +1,76 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// -- net.IP value
|
||||
type ipValue net.IP
|
||||
|
||||
func newIPValue(val net.IP, p *net.IP) *ipValue {
|
||||
*p = val
|
||||
return (*ipValue)(p)
|
||||
}
|
||||
|
||||
func (i *ipValue) String() string { return net.IP(*i).String() }
|
||||
func (i *ipValue) Set(s string) error {
|
||||
ip := net.ParseIP(s)
|
||||
if ip == nil {
|
||||
return fmt.Errorf("failed to parse IP: %q", s)
|
||||
}
|
||||
*i = ipValue(ip)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *ipValue) Type() string {
|
||||
return "ip"
|
||||
}
|
||||
|
||||
// IPVar defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IP variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
|
||||
f.VarP(newIPValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
|
||||
f.VarP(newIPValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPVar defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IP variable in which to store the value of the flag.
|
||||
func IPVar(p *net.IP, name string, value net.IP, usage string) {
|
||||
CommandLine.VarP(newIPValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
|
||||
CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IP defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IP variable that stores the value of the flag.
|
||||
func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
|
||||
p := new(net.IP)
|
||||
f.IPVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like IP, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
|
||||
p := new(net.IP)
|
||||
f.IPVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// IP defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IP variable that stores the value of the flag.
|
||||
func IP(name string, value net.IP, usage string) *net.IP {
|
||||
return CommandLine.IPP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like IP, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
|
||||
return CommandLine.IPP(name, shorthand, value, usage)
|
||||
}
|
86
Godeps/_workspace/src/github.com/spf13/pflag/ipmask.go
generated
vendored
Normal file
86
Godeps/_workspace/src/github.com/spf13/pflag/ipmask.go
generated
vendored
Normal file
|
@ -0,0 +1,86 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// -- net.IPMask value
|
||||
type ipMaskValue net.IPMask
|
||||
|
||||
func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
|
||||
*p = val
|
||||
return (*ipMaskValue)(p)
|
||||
}
|
||||
|
||||
func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
|
||||
func (i *ipMaskValue) Set(s string) error {
|
||||
ip := ParseIPv4Mask(s)
|
||||
if ip == nil {
|
||||
return fmt.Errorf("failed to parse IP mask: %q", s)
|
||||
}
|
||||
*i = ipMaskValue(ip)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *ipMaskValue) Type() string {
|
||||
return "ipMask"
|
||||
}
|
||||
|
||||
// Parse IPv4 netmask written in IP form (e.g. 255.255.255.0).
|
||||
// This function should really belong to the net package.
|
||||
func ParseIPv4Mask(s string) net.IPMask {
|
||||
mask := net.ParseIP(s)
|
||||
if mask == nil {
|
||||
return nil
|
||||
}
|
||||
return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
|
||||
}
|
||||
|
||||
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IPMask variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
|
||||
f.VarP(newIPMaskValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
|
||||
f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IPMask variable in which to store the value of the flag.
|
||||
func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
|
||||
CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
|
||||
CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IPMask variable that stores the value of the flag.
|
||||
func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
|
||||
p := new(net.IPMask)
|
||||
f.IPMaskVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like IPMask, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
|
||||
p := new(net.IPMask)
|
||||
f.IPMaskVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IPMask variable that stores the value of the flag.
|
||||
func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
|
||||
return CommandLine.IPMaskP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like IP, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
|
||||
return CommandLine.IPMaskP(name, shorthand, value, usage)
|
||||
}
|
69
Godeps/_workspace/src/github.com/spf13/pflag/string.go
generated
vendored
Normal file
69
Godeps/_workspace/src/github.com/spf13/pflag/string.go
generated
vendored
Normal file
|
@ -0,0 +1,69 @@
|
|||
package pflag
|
||||
|
||||
import "fmt"
|
||||
|
||||
// -- string Value
|
||||
type stringValue string
|
||||
|
||||
func newStringValue(val string, p *string) *stringValue {
|
||||
*p = val
|
||||
return (*stringValue)(p)
|
||||
}
|
||||
|
||||
func (s *stringValue) Set(val string) error {
|
||||
*s = stringValue(val)
|
||||
return nil
|
||||
}
|
||||
func (s *stringValue) Type() string {
|
||||
return "string"
|
||||
}
|
||||
|
||||
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
|
||||
|
||||
// StringVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a string variable in which to store the value of the flag.
|
||||
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
|
||||
f.VarP(newStringValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like StringVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
|
||||
f.VarP(newStringValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// StringVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a string variable in which to store the value of the flag.
|
||||
func StringVar(p *string, name string, value string, usage string) {
|
||||
CommandLine.VarP(newStringValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like StringVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func StringVarP(p *string, name, shorthand string, value string, usage string) {
|
||||
CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// String defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a string variable that stores the value of the flag.
|
||||
func (f *FlagSet) String(name string, value string, usage string) *string {
|
||||
p := new(string)
|
||||
f.StringVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like String, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
|
||||
p := new(string)
|
||||
f.StringVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// String defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a string variable that stores the value of the flag.
|
||||
func String(name string, value string, usage string) *string {
|
||||
return CommandLine.StringP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like String, but accepts a shorthand letter that can be used after a single dash.
|
||||
func StringP(name, shorthand string, value string, usage string) *string {
|
||||
return CommandLine.StringP(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/uint.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/uint.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint Value
|
||||
type uintValue uint
|
||||
|
||||
func newUintValue(val uint, p *uint) *uintValue {
|
||||
*p = val
|
||||
return (*uintValue)(p)
|
||||
}
|
||||
|
||||
func (i *uintValue) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
*i = uintValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uintValue) Type() string {
|
||||
return "uint"
|
||||
}
|
||||
|
||||
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// UintVar defines a uint flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint variable in which to store the value of the flag.
|
||||
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
|
||||
f.VarP(newUintValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like UintVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
|
||||
f.VarP(newUintValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// UintVar defines a uint flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint variable in which to store the value of the flag.
|
||||
func UintVar(p *uint, name string, value uint, usage string) {
|
||||
CommandLine.VarP(newUintValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like UintVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
|
||||
CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint defines a uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
|
||||
p := new(uint)
|
||||
f.UintVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
|
||||
p := new(uint)
|
||||
f.UintVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint defines a uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint variable that stores the value of the flag.
|
||||
func Uint(name string, value uint, usage string) *uint {
|
||||
return CommandLine.UintP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintP(name, shorthand string, value uint, usage string) *uint {
|
||||
return CommandLine.UintP(name, shorthand, value, usage)
|
||||
}
|
72
Godeps/_workspace/src/github.com/spf13/pflag/uint16.go
generated
vendored
Normal file
72
Godeps/_workspace/src/github.com/spf13/pflag/uint16.go
generated
vendored
Normal file
|
@ -0,0 +1,72 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint16 value
|
||||
type uint16Value uint16
|
||||
|
||||
func newUint16Value(val uint16, p *uint16) *uint16Value {
|
||||
*p = val
|
||||
return (*uint16Value)(p)
|
||||
}
|
||||
func (i *uint16Value) String() string { return fmt.Sprintf("%d", *i) }
|
||||
func (i *uint16Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 16)
|
||||
*i = uint16Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint16Value) Type() string {
|
||||
return "uint16"
|
||||
}
|
||||
|
||||
// Uint16Var defines a uint flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
|
||||
f.VarP(newUint16Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
|
||||
f.VarP(newUint16Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint16Var defines a uint flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint variable in which to store the value of the flag.
|
||||
func Uint16Var(p *uint16, name string, value uint16, usage string) {
|
||||
CommandLine.VarP(newUint16Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
|
||||
CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint16 defines a uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 {
|
||||
p := new(uint16)
|
||||
f.Uint16VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint16, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
|
||||
p := new(uint16)
|
||||
f.Uint16VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint16 defines a uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint variable that stores the value of the flag.
|
||||
func Uint16(name string, value uint16, usage string) *uint16 {
|
||||
return CommandLine.Uint16P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint16, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
|
||||
return CommandLine.Uint16P(name, shorthand, value, usage)
|
||||
}
|
72
Godeps/_workspace/src/github.com/spf13/pflag/uint32.go
generated
vendored
Normal file
72
Godeps/_workspace/src/github.com/spf13/pflag/uint32.go
generated
vendored
Normal file
|
@ -0,0 +1,72 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint16 value
|
||||
type uint32Value uint32
|
||||
|
||||
func newUint32Value(val uint32, p *uint32) *uint32Value {
|
||||
*p = val
|
||||
return (*uint32Value)(p)
|
||||
}
|
||||
func (i *uint32Value) String() string { return fmt.Sprintf("%d", *i) }
|
||||
func (i *uint32Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 32)
|
||||
*i = uint32Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint32Value) Type() string {
|
||||
return "uint32"
|
||||
}
|
||||
|
||||
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
|
||||
f.VarP(newUint32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
|
||||
f.VarP(newUint32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint32 variable in which to store the value of the flag.
|
||||
func Uint32Var(p *uint32, name string, value uint32, usage string) {
|
||||
CommandLine.VarP(newUint32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
|
||||
CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
|
||||
p := new(uint32)
|
||||
f.Uint32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
|
||||
p := new(uint32)
|
||||
f.Uint32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint32 variable that stores the value of the flag.
|
||||
func Uint32(name string, value uint32, usage string) *uint32 {
|
||||
return CommandLine.Uint32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
|
||||
return CommandLine.Uint32P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/uint64.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/uint64.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint64 Value
|
||||
type uint64Value uint64
|
||||
|
||||
func newUint64Value(val uint64, p *uint64) *uint64Value {
|
||||
*p = val
|
||||
return (*uint64Value)(p)
|
||||
}
|
||||
|
||||
func (i *uint64Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
*i = uint64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint64Value) Type() string {
|
||||
return "uint64"
|
||||
}
|
||||
|
||||
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
|
||||
f.VarP(newUint64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
|
||||
f.VarP(newUint64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint64 variable in which to store the value of the flag.
|
||||
func Uint64Var(p *uint64, name string, value uint64, usage string) {
|
||||
CommandLine.VarP(newUint64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
|
||||
CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
|
||||
p := new(uint64)
|
||||
f.Uint64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
|
||||
p := new(uint64)
|
||||
f.Uint64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint64 variable that stores the value of the flag.
|
||||
func Uint64(name string, value uint64, usage string) *uint64 {
|
||||
return CommandLine.Uint64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
|
||||
return CommandLine.Uint64P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/uint8.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/uint8.go
generated
vendored
Normal file
|
@ -0,0 +1,74 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint8 Value
|
||||
type uint8Value uint8
|
||||
|
||||
func newUint8Value(val uint8, p *uint8) *uint8Value {
|
||||
*p = val
|
||||
return (*uint8Value)(p)
|
||||
}
|
||||
|
||||
func (i *uint8Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 8)
|
||||
*i = uint8Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint8Value) Type() string {
|
||||
return "uint8"
|
||||
}
|
||||
|
||||
func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint8 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
|
||||
f.VarP(newUint8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
|
||||
f.VarP(newUint8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint8 variable in which to store the value of the flag.
|
||||
func Uint8Var(p *uint8, name string, value uint8, usage string) {
|
||||
CommandLine.VarP(newUint8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
|
||||
CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint8 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
|
||||
p := new(uint8)
|
||||
f.Uint8VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
|
||||
p := new(uint8)
|
||||
f.Uint8VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint8 variable that stores the value of the flag.
|
||||
func Uint8(name string, value uint8, usage string) *uint8 {
|
||||
return CommandLine.Uint8P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
|
||||
return CommandLine.Uint8P(name, shorthand, value, usage)
|
||||
}
|
Loading…
Reference in a new issue