mow.cli: github.com/jawher/mow.cli Index | Examples | Files | Directories

package cli

import "github.com/jawher/mow.cli"

Package cli provides a framework to build command line applications in Go with most of the burden of arguments parsing and validation placed on the framework instead of the user.

Basics

To create a new application, initialize an app with cli.App. Specify a name and a brief description for the application:

cp := cli.App("cp", "Copy files around")

To attach code to execute when the app is launched, assign a function to the Action field:

cp.Action = func() {
    fmt.Printf("Hello world\n")
}

To assign a version to the application, use Version method and specify the flags that will be used to invoke the version command:

cp.Version("v version", "cp 1.2.3")

Finally, in the main func, call Run passing in the arguments for parsing:

cp.Run(os.Args)

Options

To add one or more command line options (also known as flags), use one of the short-form StringOpt, StringsOpt, IntOpt, IntsOpt, Float64Opt, Floats64Opt, or BoolOpt methods on App (or Cmd if adding flags to a command or a subcommand). For example, to add a boolean flag to the cp command that specifies recursive mode, use the following:

recursive := cp.BoolOpt("R recursive", false, "recursively copy the src to dst")

or:

cp.BoolOptPtr(&cfg.recursive, "R recursive", false, "recursively copy the src to dst")

The first version returns a new pointer to a bool value which will be populated when the app is run, whereas the second version will populate a pointer to an existing variable you specify.

The option name(s) is a space separated list of names (without the dashes). The one letter names can then be called with a single dash (short option, -R), the others with two dashes (long options, --recursive).

You also specify the default value for the option if it is not supplied by the user.

The last parameter is the description to be shown in help messages.

There is also a second set of methods on App called String, Strings, Int, Ints, and Bool, which accept a long-form struct of the type: cli.StringOpt, cli.StringsOpt, cli.IntOpt, cli.IntsOpt, cli.Float64Opt, cli.Floats64Opt, cli.BoolOpt. The struct describes the option and allows the use of additional features not available in the short-form methods described above:

recursive = cp.Bool(cli.BoolOpt{
    Name:       "R recursive",
    Value:      false,
    Desc:       "copy src files recursively",
    EnvVar:     "VAR_RECURSIVE",
    SetByUser:  &recursiveSetByUser,
})

Or:

recursive = cp.BoolPtr(&recursive, cli.BoolOpt{
    Name:       "R recursive",
    Value:      false,
    Desc:       "copy src files recursively",
    EnvVar:     "VAR_RECURSIVE",
    SetByUser:  &recursiveSetByUser,
})

The first version returns a new pointer to a value which will be populated when the app is run, whereas the second version will populate a pointer to an existing variable you specify.

Two features, EnvVar and SetByUser, can be defined in the long-form struct method. EnvVar is a space separated list of environment variables used to initialize the option if a value is not provided by the user. When help messages are shown, the value of any environment variables will be displayed. SetByUser is a pointer to a boolean variable that is set to true if the user specified the value on the command line. This can be useful to determine if the value of the option was explicitly set by the user or set via the default value.

You can only access the values stored in the pointers in the Action func, which is invoked after argument parsing has been completed. This precludes using the value of one option as the default value of another.

On the command line, the following syntaxes are supported when specifying options.

Boolean options:

-f         single dash one letter name
-f=false   single dash one letter name, equal sign followed by true or false
--force    double dash for longer option names
-it        single dash for multiple one letter names (option folding), this is equivalent to: -i -t

String, int and float options:

-e=value       single dash one letter name, equal sign, followed by the value
-e value       single dash one letter name, space followed by the value
-Ivalue        single dash one letter name, immediately followed by the value
--extra=value  double dash for longer option names, equal sign followed by the value
--extra value  double dash for longer option names, space followed by the value

Slice options (StringsOpt, IntsOpt, Floats64Opt) where option is repeated to accumulate values in a slice:

-e PATH:/bin    -e PATH:/usr/bin     resulting slice contains ["/bin", "/usr/bin"]
-ePATH:/bin     -ePATH:/usr/bin      resulting slice contains ["/bin", "/usr/bin"]
-e=PATH:/bin    -e=PATH:/usr/bin     resulting slice contains ["/bin", "/usr/bin"]
--env PATH:/bin --env PATH:/usr/bin  resulting slice contains ["/bin", "/usr/bin"]
--env=PATH:/bin --env=PATH:/usr/bin  resulting slice contains ["/bin", "/usr/bin"]

Arguments

To add one or more command line arguments (not prefixed by dashes), use one of the short-form StringArg, StringsArg, IntArg, IntsArg, Float64Arg, Floats64Arg, or BoolArg methods on App (or Cmd if adding arguments to a command or subcommand). For example, to add two string arguments to our cp command, use the following calls:

src := cp.StringArg("SRC", "", "the file to copy")
dst := cp.StringArg("DST", "", "the destination")

Or:

cp.StringArgPtr(&src, "SRC", "", "the file to copy")
cp.StringArgPtr(&dst, "DST", "", "the destination")

The first version returns a new pointer to a value which will be populated when the app is run, whereas the second version will populate a pointer to an existing variable you specify.

You then specify the argument as will be displayed in help messages. Argument names must be specified as all uppercase. The next parameter is the default value for the argument if it is not supplied. And the last is the description to be shown in help messages.

There is also a second set of methods on App called String, Strings, Int, Ints, Float64, Floats64 and Bool, which accept a long-form struct of the type: cli.StringArg, cli.StringsArg, cli.IntArg, cli.IntsArg, cli.BoolArg. The struct describes the arguments and allows the use of additional features not available in the short-form methods described above:

src = cp.Strings(StringsArg{
    Name:      "SRC",
    Desc:      "The source files to copy",
    Value:     "default value",
    EnvVar:    "VAR1 VAR2",
    SetByUser: &srcSetByUser,
})

Or:

src = cp.StringsPtr(&src, StringsArg{
    Name:      "SRC",
    Desc:      "The source files to copy",
    Value:     "default value",
    EnvVar:    "VAR1 VAR2",
    SetByUser: &srcSetByUser,
})

The first version returns a new pointer to a value which will be populated when the app is run, whereas the second version will populate a pointer to an existing variable you specify.

Two features, EnvVar and SetByUser, can be defined in the long-form struct method. EnvVar is a space separated list of environment variables used to initialize the argument if a value is not provided by the user. When help messages are shown, the value of any environment variables will be displayed. SetByUser is a pointer to a boolean variable that is set to true if the user specified the value on the command line. This can be useful to determine if the value of the argument was explicitly set by the user or set via the default value.

You can only access the values stored in the pointers in the Action func, which is invoked after argument parsing has been completed. This precludes using the value of one argument as the default value of another.

Operators

The -- operator marks the end of command line options. Everything that follows will be treated as an argument, even if starts with a dash. For example, the standard POSIX touch command, which takes a filename as an argument (and possibly other options that we'll ignore here), could be defined as:

file := cp.StringArg("FILE", "", "the file to create")

If we try to create a file named "-f" via our touch command:

$ touch -f

It will fail because the -f will be parsed as an option, not as an argument. The fix is to insert -- after all flags have been specified, so the remaining arguments are parsed as arguments instead of options as follows:

$ touch -- -f

This ensures the -f is parsed as an argument instead of a flag named f.

Commands

This package supports nesting of commands and subcommands. Declare a top-level command by calling the Command func on the top-level App struct. For example, the following creates an application called docker that will have one command called run:

docker := cli.App("docker", "A self-sufficient runtime for linux containers")

docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) {
    // initialize the run command here
})

The first argument is the name of the command the user will specify on the command line to invoke this command. The second argument is the description of the command shown in help messages. And, the last argument is a CmdInitializer, which is a function that receives a pointer to a Cmd struct representing the command.

Within this function, define the options and arguments for the command by calling the same methods as you would with top-level App struct (BoolOpt, StringArg, ...). To execute code when the command is invoked, assign a function to the Action field of the Cmd struct. Within that function, you can safely refer to the options and arguments as command line parsing will be completed at the time the function is invoked:

docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) {
    var (
        detached = cmd.BoolOpt("d detach", false, "Run container in background")
        memory   = cmd.StringOpt("m memory", "", "Set memory limit")
        image    = cmd.StringArg("IMAGE", "", "The image to run")
    )

    cmd.Action = func() {
        if *detached {
            // do something
        }
        runContainer(*image, *detached, *memory)
    }
})

Optionally, to provide a more extensive description of the command, assign a string to LongDesc, which is displayed when a user invokes --help. A LongDesc can be provided for Cmds as well as the top-level App:

cmd.LongDesc = `Run a command in a new container

With the docker run command, an operator can add to or override the
image defaults set by a developer. And, additionally, operators can
override nearly all the defaults set by the Docker runtime itself.
The operator’s ability to override image and Docker runtime defaults
is why run has more options than any other docker command.`

Subcommands can be added by calling Command on the Cmd struct. They can by defined to any depth if needed:

docker.Command("job", "actions on jobs", func(job *cli.Cmd) {
    job.Command("list", "list jobs", listJobs)
    job.Command("start", "start a new job", startJob)
    job.Command("log", "log commands", func(log *cli.Cmd) {
        log.Command("show", "show logs", showLog)
        log.Command("clear", "clear logs", clearLog)
    })
})

Command and subcommand aliases are also supported. To define one or more aliases, specify a space-separated list of strings to the first argument of Command:

job.Command("start run r", "start a new job", startJob)

With the command structure defined above, users can invoke the app in a variety of ways:

$ docker job list
$ docker job start
$ docker job run   # using the alias we defined
$ docker job r     # using the alias we defined
$ docker job log show
$ docker job log clear

As a convenience, to assign an Action to a func with no arguments, use ActionCommand when defining the Command. For example, the following two statements are equivalent:

app.Command("list", "list all configs", cli.ActionCommand(list))

// Exactly the same as above, just more verbose
app.Command("list", "list all configs", func(cmd *cli.Cmd)) {
    cmd.Action = func() {
        list()
    }
}

Please note that options, arguments, specs, and long descriptions cannot be provided when using ActionCommand. This is intended for very simple command invocations that take no arguments.

Finally, as a side-note, it may seem a bit weird that this package uses a function to initialize a command instead of simply returning a command struct. The motivation behind this API decision is scoping: as with the standard flag package, adding an option or an argument returns a pointer to a value which will be populated when the app is run. Since you'll want to store these pointers in variables, and to avoid having dozens of them in the same scope (the main func for example or as global variables), this API was specifically tailored to take a func parameter (called CmdInitializer), which accepts the command struct. With this design, the command's specific variables are limited in scope to this function.

Interceptors

Interceptors, or hooks, can be defined to be executed before and after a command or when any of its subcommands are executed. For example, the following app defines multiple commands as well as a global flag which toggles verbosity:

app := cli.App("app", "bla bla")
verbose := app.BoolOpt("verbose v", false, "Enable debug logs")

app.Command("command1", "...", func(cmd *cli.Cmd) {
    if (*verbose) {
        logrus.SetLevel(logrus.DebugLevel)
    }
})

app.Command("command2", "...", func(cmd *cli.Cmd) {
    if (*verbose) {
        logrus.SetLevel(logrus.DebugLevel)
    }
})

Instead of duplicating the check for the verbose flag and setting the debug level in every command (and its sub-commands), a Before interceptor can be set on the top-level App instead:

app.Before = func() {
    if (*verbose) {
        logrus.SetLevel(logrus.DebugLevel)
    }
}

Whenever a valid command is called by the user, all the Before interceptors defined on the app and the intermediate commands will be called, in order from the root to the leaf.

Similarly, to execute a hook after a command has been called, e.g. to cleanup resources allocated in Before interceptors, simply set the After field of the App struct or any other Command. After interceptors will be called, in order, from the leaf up to the root (the opposite order of the Before interceptors).

The following diagram shows when and in which order multiple Before and After interceptors are executed:

+------------+    success    +------------+   success   +----------------+     success
| app.Before +---------------> cmd.Before +-------------> sub_cmd.Before +---------+
+------------+               +-+----------+             +--+-------------+         |
                               |                           |                     +-v-------+
                 error         |           error           |                     | sub_cmd |
       +-----------------------+   +-----------------------+                     | Action  |
       |                           |                                             +-+-------+
+------v-----+               +-----v------+             +----------------+         |
| app.After  <---------------+ cmd.After  <-------------+  sub_cmd.After <---------+
+------------+    always     +------------+    always   +----------------+      always

Exiting

To exit the application, use cli.Exit function, which accepts an exit code and exits the app with the provided code. It is important to use cli.Exit instead of os.Exit as the former ensures that all of the After interceptors are executed before exiting.

cli.Exit(1)

Spec Strings

An App or Command's invocation syntax can be customized using spec strings. This can be useful to indicate that an argument is optional or that two options are mutually exclusive. The spec string is one of the key differentiators between this package and other CLI packages as it allows the developer to express usage in a simple, familiar, yet concise grammar.

To define option and argument usage for the top-level App, assign a spec string to the App's Spec field:

cp := cli.App("cp", "Copy files around")
cp.Spec = "[-R [-H | -L | -P]]"

Likewise, to define option and argument usage for a command or subcommand, assign a spec string to the Command's Spec field:

docker := cli.App("docker", "A self-sufficient runtime for linux containers")
docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) {
    cmd.Spec = "[-d|--rm] IMAGE [COMMAND [ARG...]]"
    :
    :
}

The spec syntax is mostly based on the conventions used in POSIX command line applications (help messages and man pages). This syntax is described in full below. If a user invokes the app or command with the incorrect syntax, the app terminates with a help message showing the proper invocation. The remainder of this section describes the many features and capabilities of the spec string grammar.

Options can use both short and long option names in spec strings. In the example below, the option is mandatory and must be provided. Any options referenced in a spec string MUST be explicitly declared, otherwise this package will panic. I.e. for each item in the spec string, a corresponding *Opt or *Arg is required:

x.Spec = "-f"  // or x.Spec = "--force"
forceFlag := x.BoolOpt("f force", ...)

Arguments are specified with all-uppercased words. In the example below, both SRC and DST must be provided by the user (two arguments). Like options, any argument referenced in a spec string MUST be explicitly declared, otherwise this package will panic:

x.Spec="SRC DST"
src := x.StringArg("SRC", ...)
dst := x.StringArg("DST", ...)

With the exception of options, the order of the elements in a spec string is respected and enforced when command line arguments are parsed. In the example below, consecutive options (-f and -g) are parsed regardless of the order they are specified (both "-f=5 -g=6" and "-g=6 -f=5" are valid). Order between options and arguments is significant (-f and -g must appear before the SRC argument). The same holds true for arguments, where SRC must appear before DST:

x.Spec = "-f -g SRC -h DST"
var (
    factor = x.IntOpt("f", 1, "Fun factor (1-5)")
    games  = x.IntOpt("g", 1, "# of games")
    health = x.IntOpt("h", 1, "# of hosts")
    src    = x.StringArg("SRC", ...)
    dst    = x.StringArg("DST", ...)
)

Optionality of options and arguments is specified in a spec string by enclosing the item in square brackets []. If the user does not provide an optional value, the app will use the default value specified when the argument was defined. In the example below, if -x is not provided, heapSize will default to 1024:

x.Spec = "[-x]"
heapSize := x.IntOpt("x", 1024, "Heap size in MB")

Choice between two or more items is specified in a spec string by separating each choice with the | operator. Choices are mutually exclusive. In the examples below, only a single choice can be provided by the user otherwise the app will terminate displaying a help message on proper usage:

x.Spec = "--rm | --daemon"
x.Spec = "-H | -L | -P"
x.Spec = "-t | DST"

Repetition of options and arguments is specified in a spec string with the ... postfix operator to mark an item as repeatable. Both options and arguments support repitition. In the example below, users may invoke the command with multiple -e options and multiple SRC arguments:

x.Spec = "-e... SRC..."

// Allows parsing of the following shell command:
//   $ app -eeeee file1 file2
//   $ app -e -e -e -e file1 file2

Grouping of options and arguments is specified in a spec string with parenthesis. When combined with the choice | and repetition ... operators, complex syntaxes can be created. The parenthesis in the example below indicate a repeatable sequence of a -e option followed by an argument, and that is mutually exclusive to a choice between -x and -y options.

x.Spec = "(-e COMMAND)... | (-x|-y)"

// Allows parsing of the following shell command:
//   $ app -e show -e add
//   $ app -y
// But not the following:
//   $ app -e show -x

Option groups, or option folding, are a shorthand method to declaring a choice between multiple options. I.e. any combination of the listed options in any order with at least one option selected. The following two statements are equivalent:

x.Spec = "-abcd"
x.Spec = "(-a | -b | -c | -d)..."

Option groups are typically used in conjunction with optionality [] operators. I.e. any combination of the listed options in any order or none at all. The following two statements are equivalent:

x.Spec = "[-abcd]"
x.Spec = "[-a | -b | -c | -d]..."

All of the options can be specified using a special syntax: [OPTIONS]. This is a special token in the spec string (not optionality and not an argument called OPTIONS). It is equivalent to an optional repeatable choice between all the available options. For example, if an app or a command declares 4 options a, b, c and d, then the following two statements are equivalent:

x.Spec = "[OPTIONS]"
x.Spec = "[-a | -b | -c | -d]..."

Inline option values are specified in the spec string with the =<some-text> notation immediately following an option (long or short form) to provide users with an inline description or value. The actual inline values are ignored by the spec parser as they exist only to provide a contextual hint to the user. In the example below, "absolute-path" and "in seconds" are ignored by the parser:

x.Spec = "[ -a=<absolute-path> | --timeout=<in seconds> ] ARG"

The -- operator can be used to automatically treat everything following it as arguments. In other words, placing a -- in the spec string automatically inserts a -- in the same position in the program call arguments. This lets you write programs such as the POSIX time utility for example:

x.Spec = "-lp [-- CMD [ARG...]]"

// Allows parsing of the following shell command:
//   $ app -p ps -aux

Spec Grammar

Below is the full EBNF grammar for the Specs language:

spec         -> sequence
sequence     -> choice*
req_sequence -> choice+
choice       -> atom ('|' atom)*
atom         -> (shortOpt | longOpt | optSeq | allOpts | group | optional) rep?
shortOp      -> '-' [A-Za-z]
longOpt      -> '--' [A-Za-z][A-Za-z0-9]*
optSeq       -> '-' [A-Za-z]+
allOpts      -> '[OPTIONS]'
group        -> '(' req_sequence ')'
optional     -> '[' req_sequence ']'
rep          -> '...'

By combining a few of these building blocks together (while respecting the grammar above), powerful and sophisticated validation constraints can be created in a simple and concise manner without having to define in code. This is one of the key differentiators between this package and other CLI packages. Validation of usage is handled entirely by the package through the spec string.

Behind the scenes, this package parses the spec string and constructs a finite state machine used to parse the command line arguments. It also handles backtracking, which allows it to handle tricky cases, or what I like to call "the cp test":

cp SRC... DST

Without backtracking, this deceptively simple spec string cannot be parsed correctly. For instance, docopt can't handle this case, whereas this package does.

Default Spec

By default an auto-generated spec string is created for the app and every command unless a spec string has been set by the user. This can simplify use of the package even further for simple syntaxes.

The following logic is used to create an auto-generated spec string: 1) start with an empty spec string, 2) if at least one option was declared, append "[OPTIONS]" to the spec string, and 3) for each declared argument, append it, in the order of declaration, to the spec string. For example, given this command declaration:

docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) {
    var (
        detached = cmd.BoolOpt("d detach", false, "Run container in background")
        memory   = cmd.StringOpt("m memory", "", "Set memory limit")
        image    = cmd.StringArg("IMAGE", "", "The image to run")
        args     = cmd.StringsArg("ARG", nil, "Arguments")
    )
})

The auto-generated spec string, which should suffice for simple cases, would be:

[OPTIONS] IMAGE ARG

If additional constraints are required, the spec string must be set explicitly using the grammar documented above.

Custom Types

By default, the following types are supported for options and arguments: bool, string, int, float64, strings (slice of strings), ints (slice of ints) and floats64 (slice of float64). You can, however, extend this package to handle other types, e.g. time.Duration, float64, or even your own struct types.

To define your own custom type, you must implement the flag.Value interface for your custom type, and then declare the option or argument using VarOpt or VarArg respectively if using the short-form methods. If using the long-form struct, then use Var instead.

The following example defines a custom type for a duration. It defines a duration argument that users will be able to invoke with strings in the form of "1h31m42s":

// Declare your type
type Duration time.Duration

// Make it implement flag.Value
func (d *Duration) Set(v string) error {
    parsed, err := time.ParseDuration(v)
    if err != nil {
        return err
    }
    *d = Duration(parsed)
    return nil
}

func (d *Duration) String() string {
    duration := time.Duration(*d)
    return duration.String()
}

func main() {
    duration := Duration(0)
    app := App("var", "")
    app.VarArg("DURATION", &duration, "")
    app.Run([]string{"cp", "1h31m42s"})
}

To make a custom type to behave as a boolean option, i.e. doesn't take a value, it must implement the IsBoolFlag method that returns true:

type BoolLike int

func (d *BoolLike) IsBoolFlag() bool {
    return true
}

To make a custom type behave as a multi-valued option or argument, i.e. takes multiple values, it must implement the Clear method, which is called whenever the values list needs to be cleared, e.g. when the value was initially populated from an environment variable, and then explicitly set from the CLI:

type Durations []time.Duration

// Make it implement flag.Value
func (d *Durations) Set(v string) error {
    parsed, err := time.ParseDuration(v)
    if err != nil {
        return err
    }
    *d = append(*d, Duration(parsed))
    return nil
}

func (d *Durations) String() string {
    return fmt.Sprintf("%v", *d)
}

// Make it multi-valued
func (d *Durations) Clear() {
    *d = []Duration{}
}

To hide the default value of a custom type, it must implement the IsDefault method that returns a boolean. The help message generator will use the return value to decide whether or not to display the default value to users:

type Action string

func (a *Action) IsDefault() bool {
    return (*a) == "nop"
}

Code:

app := cli.App("app", "App")
bench := app.BoolOpt("b bench", false, "Measure execution time")

var t0 time.Time

app.Before = func() {
    if *bench {
        t0 = time.Now()
    }
}

app.After = func() {
    if *bench {
        d := time.Since(t0)
        fmt.Printf("Command execution took: %vs", d.Seconds())
    }
}

app.Command("cmd1", "first command", func(cmd *cli.Cmd) {
    cmd.Action = func() {
        fmt.Print("Running command 1")
    }
})

app.Command("cmd2", "second command", func(cmd *cli.Cmd) {
    cmd.Action = func() {
        fmt.Print("Running command 2")
    }
})

app.Run(os.Args)

Code:

cp := cli.App("cp", "Copy files around")
cp.Spec = "[-R [-H | -L | -P]] [-fi | -n] SRC... DST"

var (
    recursive          = cp.BoolOpt("R", false, "copy src files recursively")
    followSymbolicCL   = cp.BoolOpt("H", false, "If the -R option is specified, symbolic links on the command line are followed.  (Symbolic links encountered in the tree traversal are not followed.)")
    followSymbolicTree = cp.BoolOpt("L", false, "If the -R option is specified, all symbolic links are followed.")
    followSymbolicNo   = cp.BoolOpt("P", true, "If the -R option is specified, no symbolic links are followed.  This is the default.")
    force              = cp.BoolOpt("f", false, "If the destination file cannot be opened, remove it and create a new file, without prompting for confirmation regardless of its permissions.  (The -f option overrides any previous -n option.)")
    interactive        = cp.BoolOpt("i", false, "Cause cp to write a prompt to the standard error output before copying a file that would overwrite an existing file.  If the response from the standard input begins with the character `y' or `Y', the file copy is attempted.  (The -i option overrides any previous -n option.)")
    noOverwrite        = cp.BoolOpt("f", false, "Do not overwrite an existing file.  (The -n option overrides any previous -f or -i options.)")
)

var (
    src = cp.Strings(cli.StringsArg{
        Name: "SRC",
        Desc: "The source files to copy",
    })
    dst = cp.Strings(cli.StringsArg{Name: "DST", Value: nil, Desc: "The destination directory"})
)

cp.Action = func() {
    fmt.Printf(`copy:
	SRC: %v
	DST: %v
	recursive: %v
	follow links (CL, Tree, No): %v %v %v
	force: %v
	interactive: %v
	no overwrite: %v`,
        *src, *dst, *recursive,
        *followSymbolicCL, *followSymbolicTree, *followSymbolicNo,
        *force,
        *interactive,
        *noOverwrite)
}

cp.Run(os.Args)

Code:

docker := cli.App("docker", "A self-sufficient runtime for linux containers")

docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) {
    cmd.Spec = "[-d|--rm] IMAGE [COMMAND [ARG...]]"

    var (
        detached = cmd.Bool(cli.BoolOpt{Name: "d detach", Value: false, Desc: "Detached mode: run the container in the background and print the new container ID"})
        rm       = cmd.Bool(cli.BoolOpt{Name: "rm", Value: false, Desc: "Automatically remove the container when it exits (incompatible with -d)"})
        memory   = cmd.String(cli.StringOpt{Name: "m memory", Value: "", Desc: "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)"})
    )

    var (
        image   = cmd.String(cli.StringArg{Name: "IMAGE", Value: "", Desc: ""})
        command = cmd.String(cli.StringArg{Name: "COMMAND", Value: "", Desc: "The command to run"})
        args    = cmd.Strings(cli.StringsArg{Name: "ARG", Value: nil, Desc: "The command arguments"})
    )

    cmd.Action = func() {
        var how string
        switch {
        case *detached:
            how = "detached"
        case *rm:
            how = "rm after"
        default:
            how = "--"
        }
        fmt.Printf("Run image %s, command %s, args %v, how? %v, mem %s", *image, *command, *args, how, *memory)
    }
})

docker.Command("pull", "Pull an image or a repository from the registry", func(cmd *cli.Cmd) {
    cmd.Spec = "[-a] NAME"

    var (
        all = cmd.Bool(cli.BoolOpt{Name: "a all-tags", Value: false, Desc: "Download all tagged images in the repository"})
    )

    var (
        name = cmd.String(cli.StringArg{Name: "NAME", Value: "", Desc: "Image name (optionally NAME:TAG)"})
    )

    cmd.Action = func() {
        if *all {
            fmt.Printf("Download all tags for image %s", *name)
            return
        }
        fmt.Printf("Download image %s", *name)
    }
})

docker.Run(os.Args)

Code:

docker := cli.App("docker", "A self-sufficient runtime for linux containers")

docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) {
    cmd.Spec = "[-d|--rm] IMAGE [COMMAND [ARG...]]"

    type RunConfig struct {
        Detached bool
        RM       bool
        Memory   string
        Image    string
        Command  string
        Args     []string
    }

    var cfg RunConfig

    // options
    cmd.BoolOptPtr(&cfg.Detached, "d detach", false, "Detached mode: run the container in the background and print the new container ID")
    cmd.BoolOptPtr(&cfg.RM, "rm", false, "Automatically remove the container when it exits (incompatible with -d)")
    cmd.StringOptPtr(&cfg.Memory, "m memory", "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)")

    // args
    cmd.StringArgPtr(&cfg.Image, "IMAGE", "", "")
    cmd.StringArgPtr(&cfg.Command, "COMMAND", "", "The command to run")
    cmd.StringsArgPtr(&cfg.Args, "ARG", nil, "The command arguments")

    cmd.Action = func() {
        fmt.Printf("Run using config: %+v", cfg)
    }
})

docker.Run(os.Args)

Code:

app := cli.App("greet", "Greet")
app.Spec = "[NAME]"
name := app.String(cli.StringArg{Name: "NAME", Value: "stranger", Desc: "Your name", EnvVar: "USER"})
app.Action = func() {
    fmt.Printf("Hello %s\n", *name)
}
app.Run(os.Args)

Index

Examples

Package Files

args.go cli.go commands.go doc.go errors.go options.go

func Exit Uses

func Exit(code int)

Exit causes the app the exit with the specified exit code while giving the After interceptors a chance to run. This should be used instead of os.Exit.

type BoolArg Uses

type BoolArg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument
    EnvVar string
    // The argument's initial value
    Value bool
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

BoolArg describes a boolean argument

type BoolOpt Uses

type BoolOpt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option
    EnvVar string
    // The option's initial value
    Value bool
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

BoolOpt describes a boolean option

type BoolParam Uses

type BoolParam interface {
    // contains filtered or unexported methods
}

BoolParam represents a Bool option or argument

type Cli Uses

type Cli struct {
    *Cmd
    // contains filtered or unexported fields
}

Cli represents the structure of a CLI app. It should be constructed using the App() function

func App Uses

func App(name, desc string) *Cli

App creates a new and empty CLI app configured with the passed name and description.

name and description will be used to construct the help message for the app:

Usage: $name [OPTIONS] COMMAND [arg...]

$desc

func (*Cli) PrintVersion Uses

func (cli *Cli) PrintVersion()

PrintVersion prints the CLI app's version. In most cases the library users won't need to call this method, unless a more complex validation is needed.

func (*Cli) Run Uses

func (cli *Cli) Run(args []string) error

Run uses the app configuration (specs, commands, ...) to parse the args slice and to execute the matching command.

In case of an incorrect usage, and depending on the configured ErrorHandling policy, it may return an error, panic or exit

func (*Cli) Version Uses

func (cli *Cli) Version(name, version string)

Version sets the version string of the CLI app together with the options that can be used to trigger printing the version string via the CLI.

Usage: appName --$name
$version

type Cmd Uses

type Cmd struct {
    // The code to execute when this command is matched
    Action func()
    // The code to execute before this command or any of its children is matched
    Before func()
    // The code to execute after this command or any of its children is matched
    After func()
    // The command options and arguments
    Spec string
    // The command long description to be shown when help is requested
    LongDesc string
    // The command error handling strategy
    ErrorHandling flag.ErrorHandling
    // contains filtered or unexported fields
}

Cmd represents a command (or sub command) in a CLI application. It should be constructed by calling Command() on an app to create a top level command or by calling Command() on another command to create a sub command

func (*Cmd) Bool Uses

func (c *Cmd) Bool(p BoolParam) *bool

Bool can be used to add a bool option or argument to a command. It accepts either a BoolOpt or a BoolArg struct.

The result should be stored in a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) BoolArg Uses

func (c *Cmd) BoolArg(name string, value bool, desc string) *bool

BoolArg defines a boolean argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) BoolArgPtr Uses

func (c *Cmd) BoolArgPtr(into *bool, name string, value bool, desc string)

BoolArgPtr defines a boolean argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) BoolOpt Uses

func (c *Cmd) BoolOpt(name string, value bool, desc string) *bool

BoolOpt defines a boolean option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) BoolOptPtr Uses

func (c *Cmd) BoolOptPtr(into *bool, name string, value bool, desc string)

BoolOptPtr defines a bool option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) BoolPtr Uses

func (c *Cmd) BoolPtr(into *bool, p BoolParam)

BoolPtr can be used to add a bool option or argument to a command. It accepts either a pointer to a bool var and a BoolOpt or a BoolArg struct.

The into parameter points to a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Command Uses

func (c *Cmd) Command(name, desc string, init CmdInitializer)

Command adds a new (sub) command to c where name is the command name (what you type in the console), description is what would be shown in the help messages, e.g.:

Usage: git [OPTIONS] COMMAND [arg...]

Commands:
  $name	$desc

the last argument, init, is a function that will be called by mow.cli to further configure the created (sub) command, e.g. to add options, arguments and the code to execute

func (*Cmd) Float64 Uses

func (c *Cmd) Float64(p Float64Param) *float64

Float64 can be used to add a float64 option or argument to a command. It accepts either a Float64Opt or a Float64Arg struct.

The result should be stored in a variable (a pointer to a float64) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Float64Arg Uses

func (c *Cmd) Float64Arg(name string, value float64, desc string) *float64

Float64Arg defines an float64 argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to an float64) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Float64ArgPtr Uses

func (c *Cmd) Float64ArgPtr(into *float64, name string, value float64, desc string)

Float64ArgPtr defines an float64 argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a float64) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Float64Opt Uses

func (c *Cmd) Float64Opt(name string, value float64, desc string) *float64

Float64Opt defines an float64 option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to an float64) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Float64OptPtr Uses

func (c *Cmd) Float64OptPtr(into *float64, name string, value float64, desc string)

Float64OptPtr defines a float64 option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to a float64) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Float64Ptr Uses

func (c *Cmd) Float64Ptr(into *float64, p Float64Param)

Float64Ptr can be used to add a float64 option or argument to a command. It accepts either a pointer to a float64 var and a Float64Opt or a Float64Arg struct.

The into parameter points to a variable (a pointer to a float64) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Floats64 Uses

func (c *Cmd) Floats64(p Floats64Param) *[]float64

Floats64 can be used to add an float64 slice option or argument to a command. It accepts either a Floats64Opt or a Floats64Arg struct.

The result should be stored in a variable (a pointer to an float64 slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Floats64Arg Uses

func (c *Cmd) Floats64Arg(name string, value []float64, desc string) *[]float64

Floats64Arg defines an float64 slice argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to an float64 slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Floats64ArgPtr Uses

func (c *Cmd) Floats64ArgPtr(into *[]float64, name string, value []float64, desc string)

Floats64ArgPtr defines a float64 slice argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a float64 slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Floats64Opt Uses

func (c *Cmd) Floats64Opt(name string, value []float64, desc string) *[]float64

Floats64Opt defines an float64 slice option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to an float64 slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Floats64OptPtr Uses

func (c *Cmd) Floats64OptPtr(into *[]float64, name string, value []float64, desc string)

Floats64OptPtr defines a int slice option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Floats64Ptr Uses

func (c *Cmd) Floats64Ptr(into *[]float64, p Floats64Param)

Floats64Ptr can be used to add a float64 slice option or argument to a command. It accepts either a pointer to a float64 slice var and a Floats64Opt or a Floats64Arg struct.

The into parameter points to a variable (a pointer to a float64 slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Int Uses

func (c *Cmd) Int(p IntParam) *int

Int can be used to add an int option or argument to a command. It accepts either a IntOpt or a IntArg struct.

The result should be stored in a variable (a pointer to an int) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntArg Uses

func (c *Cmd) IntArg(name string, value int, desc string) *int

IntArg defines an int argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to an int) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntArgPtr Uses

func (c *Cmd) IntArgPtr(into *int, name string, value int, desc string)

IntArgPtr defines an int argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a int) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntOpt Uses

func (c *Cmd) IntOpt(name string, value int, desc string) *int

IntOpt defines an int option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to an int) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntOptPtr Uses

func (c *Cmd) IntOptPtr(into *int, name string, value int, desc string)

IntOptPtr defines a int option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to an int) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntPtr Uses

func (c *Cmd) IntPtr(into *int, p IntParam)

IntPtr can be used to add a int option or argument to a command. It accepts either a pointer to a int var and a IntOpt or a IntArg struct.

The into parameter points to a variable (a pointer to a int) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Ints Uses

func (c *Cmd) Ints(p IntsParam) *[]int

Ints can be used to add an int slice option or argument to a command. It accepts either a IntsOpt or a IntsArg struct.

The result should be stored in a variable (a pointer to an int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntsArg Uses

func (c *Cmd) IntsArg(name string, value []int, desc string) *[]int

IntsArg defines an int slice argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to an int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntsArgPtr Uses

func (c *Cmd) IntsArgPtr(into *[]int, name string, value []int, desc string)

IntsArgPtr defines a int slice argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntsOpt Uses

func (c *Cmd) IntsOpt(name string, value []int, desc string) *[]int

IntsOpt defines an int slice option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to an int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntsOptPtr Uses

func (c *Cmd) IntsOptPtr(into *[]int, name string, value []int, desc string)

IntsOptPtr defines a int slice option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) IntsPtr Uses

func (c *Cmd) IntsPtr(into *[]int, p IntsParam)

IntsPtr can be used to add a int slice option or argument to a command. It accepts either a pointer to a int slice var and a IntsOpt or a IntsArg struct.

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) PrintHelp Uses

func (c *Cmd) PrintHelp()

PrintHelp prints the command's help message. In most cases the library users won't need to call this method, unless a more complex validation is needed

func (*Cmd) PrintLongHelp Uses

func (c *Cmd) PrintLongHelp()

PrintLongHelp prints the command's help message using the command long description if specified. In most cases the library users won't need to call this method, unless a more complex validation is needed

func (*Cmd) String Uses

func (c *Cmd) String(p StringParam) *string

String can be used to add a string option or argument to a command. It accepts either a StringOpt or a StringArg struct.

The result should be stored in a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringArg Uses

func (c *Cmd) StringArg(name string, value string, desc string) *string

StringArg defines a string argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringArgPtr Uses

func (c *Cmd) StringArgPtr(into *string, name string, value string, desc string)

StringArgPtr defines a string argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringOpt Uses

func (c *Cmd) StringOpt(name string, value string, desc string) *string

StringOpt defines a string option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringOptPtr Uses

func (c *Cmd) StringOptPtr(into *string, name string, value string, desc string)

StringOptPtr defines a string option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringPtr Uses

func (c *Cmd) StringPtr(into *string, p StringParam)

StringPtr can be used to add a string option or argument to a command. It accepts either a pointer to a string var and a StringOpt or a StringArg struct.

The into parameter points to a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Strings Uses

func (c *Cmd) Strings(p StringsParam) *[]string

Strings can be used to add a string slice option or argument to a command. It accepts either a StringsOpt or a StringsArg struct.

The result should be stored in a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringsArg Uses

func (c *Cmd) StringsArg(name string, value []string, desc string) *[]string

StringsArg defines a string slice argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The result should be stored in a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringsArgPtr Uses

func (c *Cmd) StringsArgPtr(into *[]string, name string, value []string, desc string)

StringsArgPtr defines a string slice argument on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The into parameter points to a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringsOpt Uses

func (c *Cmd) StringsOpt(name string, value []string, desc string) *[]string

StringsOpt defines a string slice option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result should be stored in a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringsOptPtr Uses

func (c *Cmd) StringsOptPtr(into *[]string, name string, value []string, desc string)

StringsOptPtr defines a string slice option on the command c named `name`, with an initial value of `value` and a description of `desc` which will be used in help messages.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The into parameter points to a variable (a pointer to a int slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) StringsPtr Uses

func (c *Cmd) StringsPtr(into *[]string, p StringsParam)

StringsPtr can be used to add a string slice option or argument to a command. It accepts either a pointer to a string slice var and a StringsOpt or a StringsArg struct.

The into parameter points to a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) Var Uses

func (c *Cmd) Var(p VarParam)

Var can be used to add a custom option or argument to a command. It accepts either a VarOpt or a VarArg struct.

As opposed to the other built-in types, this function does not return a pointer the the value. Instead, the VarOpt or VarOptArg structs hold the said value.

func (*Cmd) VarArg Uses

func (c *Cmd) VarArg(name string, value flag.Value, desc string)

VarArg defines an argument where the type and format is controlled by the developer on the command c named `name` and a description of `desc` which will be used in help messages.

The result will be stored in the value parameter (a value implementing the flag.Value interface) which will be populated when the app is run and the call arguments get parsed

func (*Cmd) VarOpt Uses

func (c *Cmd) VarOpt(name string, value flag.Value, desc string)

VarOpt defines an option where the type and format is controlled by the developer.

The name is a space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`. The one letter names will then be called with a single dash (short option), the others with two (long options).

The result will be stored in the value parameter (a value implementing the flag.Value interface) which will be populated when the app is run and the call arguments get parsed

type CmdInitializer Uses

type CmdInitializer func(*Cmd)

CmdInitializer is a function that configures a command by adding options, arguments, a spec, sub commands and the code to execute when the command is called

func ActionCommand Uses

func ActionCommand(action func()) CmdInitializer

ActionCommand is a convenience function to configure a command with an action.

cmd.ActionCommand(_, _, myFunc) is equivalent to cmd.Command(_, _, func(cmd *cli.Cmd) { cmd.Action = myFunc })

type Float64Arg Uses

type Float64Arg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument
    EnvVar string
    // The argument's initial value
    Value float64
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

Float64Arg describes an float64 argument

type Float64Opt Uses

type Float64Opt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option
    EnvVar string
    // The option's initial value
    Value float64
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

Float64Opt describes an float64 option

type Float64Param Uses

type Float64Param interface {
    // contains filtered or unexported methods
}

Float64Param represents an Float64 option or argument

type Floats64Arg Uses

type Floats64Arg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument.
    // The env variable should contain a comma separated list of values
    EnvVar string
    // The argument's initial value
    Value []float64
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

Floats64Arg describes an int slice argument

type Floats64Opt Uses

type Floats64Opt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option.
    // The env variable should contain a comma separated list of values
    EnvVar string
    // The option's initial value
    Value []float64
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

Floats64Opt describes an int slice option

type Floats64Param Uses

type Floats64Param interface {
    // contains filtered or unexported methods
}

Floats64Param represents an float64 slice option or argument

type IntArg Uses

type IntArg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument
    EnvVar string
    // The argument's initial value
    Value int
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

IntArg describes an int argument

type IntOpt Uses

type IntOpt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option
    EnvVar string
    // The option's initial value
    Value int
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

IntOpt describes an int option

type IntParam Uses

type IntParam interface {
    // contains filtered or unexported methods
}

IntParam represents an Int option or argument

type IntsArg Uses

type IntsArg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument.
    // The env variable should contain a comma separated list of values
    EnvVar string
    // The argument's initial value
    Value []int
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

IntsArg describes an int slice argument

type IntsOpt Uses

type IntsOpt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option.
    // The env variable should contain a comma separated list of values
    EnvVar string
    // The option's initial value
    Value []int
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

IntsOpt describes an int slice option

type IntsParam Uses

type IntsParam interface {
    // contains filtered or unexported methods
}

IntsParam represents an float64 slice option or argument

type StringArg Uses

type StringArg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument
    EnvVar string
    // The argument's initial value
    Value string
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

StringArg describes a string argument

type StringOpt Uses

type StringOpt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option
    EnvVar string
    // The option's initial value
    Value string
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

StringOpt describes a string option

type StringParam Uses

type StringParam interface {
    // contains filtered or unexported methods
}

StringParam represents a String option or argument

type StringsArg Uses

type StringsArg struct {
    // The argument name as will be shown in help messages
    Name string
    // The argument description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this argument.
    // The env variable should contain a comma separated list of values
    EnvVar string
    // The argument's initial value
    Value []string
    // A boolean to display or not the current value of the argument in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

StringsArg describes a string slice argument

type StringsOpt Uses

type StringsOpt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option.
    // The env variable should contain a comma separated list of values
    EnvVar string
    // The option's initial value
    Value []string
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

StringsOpt describes a string slice option

type StringsParam Uses

type StringsParam interface {
    // contains filtered or unexported methods
}

StringsParam represents a string slice option or argument

type VarArg Uses

type VarArg struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option
    EnvVar string
    // A value implementing the flag.Value type (will hold the final value)
    Value flag.Value
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

VarArg describes an argument where the type and format of the value is controlled by the developer

Code:

package main

import (
    "fmt"
    "time"

    "github.com/jawher/mow.cli"
)

// Declare your type
type Duration time.Duration

// Make it implement flag.Value
func (d *Duration) Set(v string) error {
    parsed, err := time.ParseDuration(v)
    if err != nil {
        return err
    }
    *d = Duration(parsed)
    return nil
}

func (d *Duration) String() string {
    duration := time.Duration(*d)
    return duration.String()
}

func main() {

    app := cli.App("var", "Var arg example")

    // Declare a variable of your type
    duration := Duration(0)
    // Call one of the Var methods (arg, opt, ...) to declare your custom type
    app.VarArg("DURATION", &duration, "")

    app.Action = func() {
        // The variable will be populated after the app is ran
        fmt.Print(time.Duration(duration))
    }

    app.Run([]string{"cp", "1h31m42s"})
}

type VarOpt Uses

type VarOpt struct {
    // A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
    // The one letter names will then be called with a single dash (short option), the others with two (long options).
    Name string
    // The option description as will be shown in help messages
    Desc string
    // A space separated list of environment variables names to be used to initialize this option
    EnvVar string
    // A value implementing the flag.Value type (will hold the final value)
    Value flag.Value
    // A boolean to display or not the current value of the option in the help message
    HideValue bool
    // Set to true if this option was set by the user (as opposed to being set from env or not set at all)
    SetByUser *bool
}

VarOpt describes an option where the type and format of the value is controlled by the developer

Code:

package main

import (
    "fmt"

    "github.com/jawher/mow.cli"
)

// Declare your type
type Counter int

// Make it implement flag.Value
func (c *Counter) Set(v string) error {
    *c++
    return nil
}

func (c *Counter) String() string {
    return fmt.Sprintf("%d", *c)
}

// Make it a bool option
func (c *Counter) IsBoolFlag() bool {
    return true
}

func main() {

    app := cli.App("var", "Var opt example")

    // Declare a variable of your type
    verbosity := Counter(0)
    // Call one of the Var methods (arg, opt, ...) to declare your custom type
    app.VarOpt("v", &verbosity, "verbosity level")

    app.Action = func() {
        // The variable will be populated after the app is ran
        fmt.Print(verbosity)
    }

    app.Run([]string{"app", "-vvvvv"})
}

type VarParam Uses

type VarParam interface {
    // contains filtered or unexported methods
}

VarParam represents an custom option or argument where the type and format are controlled by the developer

Directories

PathSynopsis
internal/container
internal/flow
internal/flow/flowdot
internal/fsm
internal/fsm/fsmdot
internal/fsm/fsmtest
internal/lexer
internal/matcher
internal/matcher/matchertest
internal/parser
internal/values

Package cli imports 13 packages (graph) and is imported by 152 packages. Updated 2019-11-14. Refresh now. Tools for package owners.