cli Documentation

A declarative, simple, fast, and fun package for building command line tools in Go

24,186 stars Go Go 1 file ยท ~40,844 tokens #cli#command-line#go#golang-library#json#toml#yaml
RAW Doc

1. Project Overview & Quickstart (urfave/cli)

File: README.md

Welcome to urfave/cli

Go Reference
Go Report Card
codecov
Tests status

urfave/cli is a declarative, simple, fast, and fun package for building
command line tools in Go featuring:

  • commands and subcommands with alias and prefix match support
  • flexible and permissive help system
  • dynamic shell completion for bash, zsh, fish, and powershell
  • no dependencies except Go standard library
  • input flags for simple types, slices of simple types, time, duration, and
    others
  • compound short flag support (-a -b -c can be shortened to -abc)
  • documentation generation in man and Markdown (supported via the
    urfave/cli-docs module)
  • input lookup from:
    • environment variables
    • plain text files
    • structured file formats (supported via the
      urfave/cli-altsrc module)

Documentation

See the hosted documentation website at https://cli.urfave.org. Contents of
this website are built from the ./docs directory.

Support

Check the Q&A discussions. If you don't find answer to your question, create
a new discussion
.

If you found a bug or have a feature request, create a new issue.

Please keep in mind that this project is run by unpaid volunteers.

License

See LICENSE.


File: docs/v1/examples/arguments.md


tags:

  • v1

You can lookup arguments by calling the Args function on cli.Context, e.g.:

go
package main

import (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Action = func(c *cli.Context) error {
    fmt.Printf("Hello %q", c.Args().Get(0))
    return nil
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

File: docs/v1/examples/bash-completions.md


tags:

  • v1

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
package main

import (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  tasks := []string{"cook", "clean", "laundry", "eat", "sleep", "code"}

  app := cli.NewApp()
  app.EnableBashCompletion = true
  app.Commands = []cli.Command{
    {
      Name:  "complete",
      Aliases: []string{"c"},
      Usage: "complete a task on the list",
      Action: func(c *cli.Context) error {
         fmt.Println("completed task: ", c.Args().First())
         return nil
      },
      BashComplete: func(c *cli.Context) {
        // This will complete if no args are passed
        if c.NArg() > 0 {
          return
        }
        for _, t := range tasks {
          fmt.Println(t)
        }
      },
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Enabling

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

Distribution

Copy autocomplete/bash_autocomplete into /etc/bash_completion.d/ and rename
it to the name of the program you wish to add autocomplete support for (or
automatically install it there if you are distributing a package). Don't forget
to source the file to make it active in the current shell.

text
sudo cp src/bash_autocomplete /etc/bash_completion.d/<myprogram>
source /etc/bash_completion.d/<myprogram>

Alternatively, you can just document that users should source the generic
autocomplete/bash_autocomplete in their bash configuration with $PROG set
to the name of their program (as above).

Customization

The default bash completion flag (--generate-bash-completion) is defined as
cli.BashCompletionFlag, and may be redefined if desired, e.g.:

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  cli.BashCompletionFlag = cli.BoolFlag{
    Name:   "compgen",
    Hidden: true,
  }

  app := cli.NewApp()
  app.EnableBashCompletion = true
  app.Commands = []cli.Command{
    {
      Name: "wat",
    },
  }
  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

File: docs/v1/examples/combining-short-options.md


tags:

  • v1

Traditional use of options using their shortnames look like this:

text
$ cmd -s -o -m "Some message"

Suppose you want users to be able to combine options with their shortnames. This
can be done using the UseShortOptionHandling bool in your app configuration,
or for individual commands by attaching it to the command configuration. For
example:

go
package main

import (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()
  app.UseShortOptionHandling = true
  app.Commands = []cli.Command{
    {
      Name:  "short",
      Usage: "complete a task on the list",
      Flags: []cli.Flag{
        cli.BoolFlag{Name: "serve, s"},
        cli.BoolFlag{Name: "option, o"},
        cli.StringFlag{Name: "message, m"},
      },
      Action: func(c *cli.Context) error {
        fmt.Println("serve:", c.Bool("serve"))
        fmt.Println("option:", c.Bool("option"))
        fmt.Println("message:", c.String("message"))
        return nil
      },
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

If your program has any number of bool flags such as serve and option, and
optionally one non-bool flag message, with the short options of -s, -o,
and -m respectively, setting UseShortOptionHandling will also support the
following syntax:

text
$ cmd -som "Some message"

If you enable UseShortOptionHandling, then you must not use any flags that
have a single leading - or this will result in failures. For example,
-option can no longer be used. Flags with two leading dashes (such as
--options) are still valid.


File: docs/v1/examples/exit-codes.md


tags:

  • v1

Calling App.Run will not automatically call os.Exit, which means that by
default the exit code will "fall through" to being 0. An explicit exit code
may be set by returning a non-nil error that fulfills cli.ExitCoder, or a
cli.MultiError that includes an error that fulfills cli.ExitCoder, e.g.:

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()
  app.Flags = []cli.Flag{
    cli.BoolFlag{
      Name:  "ginger-crouton",
      Usage: "Add ginger croutons to the soup",
    },
  }
  app.Action = func(ctx *cli.Context) error {
    if !ctx.Bool("ginger-crouton") {
      return cli.NewExitError("Ginger croutons are not in the soup", 86)
    }
    return nil
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

File: docs/v1/examples/flags.md


tags:

  • v1

Setting and querying flags is simple.

go
package main

import (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "lang",
      Value: "english",
      Usage: "language for the greeting",
    },
  }

  app.Action = func(c *cli.Context) error {
    name := "Nefertiti"
    if c.NArg() > 0 {
      name = c.Args().Get(0)
    }
    if c.String("lang") == "spanish" {
      fmt.Println("Hola", name)
    } else {
      fmt.Println("Hello", name)
    }
    return nil
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

You can also set a destination variable for a flag, to which the content will be
scanned.

go
package main

import (
  "log"
  "os"
  "fmt"

  "github.com/urfave/cli"
)

func main() {
  var language string

  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name:        "lang",
      Value:       "english",
      Usage:       "language for the greeting",
      Destination: &language,
    },
  }

  app.Action = func(c *cli.Context) error {
    name := "someone"
    if c.NArg() > 0 {
      name = c.Args()[0]
    }
    if language == "spanish" {
      fmt.Println("Hola", name)
    } else {
      fmt.Println("Hello", name)
    }
    return nil
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

See full list of flags at https://pkg.go.dev/github.com/urfave/cli

Placeholder Values

Sometimes it's useful to specify a flag's value within the usage string itself.
Such placeholders are indicated with back quotes.

For example this:

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag{
    cli.StringFlag{
      Name:  "config, c",
      Usage: "Load configuration from `FILE`",
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Will result in help output like:

text
--config FILE, -c FILE   Load configuration from FILE

Note that only the first placeholder is used. Subsequent back-quoted words will
be left as-is.

Alternate Names

You can set alternate (or short) names for flags by providing a comma-delimited
list for the Name. e.g.

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "lang, l",
      Value: "english",
      Usage: "language for the greeting",
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

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.

Ordering

Flags for the application and commands are shown in the order they are defined.
However, it's possible to sort them from outside this library by using FlagsByName
or CommandsByName with sort.

For example this:

go
package main

import (
  "log"
  "os"
  "sort"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "lang, l",
      Value: "english",
      Usage: "Language for the greeting",
    },
    cli.StringFlag{
      Name: "config, c",
      Usage: "Load configuration from `FILE`",
    },
  }

  app.Commands = []cli.Command{
    {
      Name:    "complete",
      Aliases: []string{"c"},
      Usage:   "complete a task on the list",
      Action:  func(c *cli.Context) error {
        return nil
      },
    },
    {
      Name:    "add",
      Aliases: []string{"a"},
      Usage:   "add a task to the list",
      Action:  func(c *cli.Context) error {
        return nil
      },
    },
  }

  sort.Sort(cli.FlagsByName(app.Flags))
  sort.Sort(cli.CommandsByName(app.Commands))

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Will result in help output like:

text
--config FILE, -c FILE  Load configuration from FILE
--lang value, -l value  Language for the greeting (default: "english")

Values from the Environment

You can also have the default value set from the environment via EnvVar. e.g.

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "lang, l",
      Value: "english",
      Usage: "language for the greeting",
      EnvVar: "APP_LANG",
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

The EnvVar may also be given as a comma-delimited "cascade", where the first
environment variable that resolves is used as the default.

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "lang, l",
      Value: "english",
      Usage: "language for the greeting",
      EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Values from files

You can also have the default value set from file via FilePath. e.g.

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "password, p",
      Usage: "password for the mysql database",
      FilePath: "/etc/mysql/password",
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Note that default values set from file (e.g. FilePath) take precedence over
default values set from the environment (e.g. EnvVar).

Values from alternate input sources (YAML, TOML, and others)

There is a separate package altsrc that adds support for getting flag values
from other file input sources.

Currently supported input source formats:

  • YAML
  • JSON
  • TOML

In order to get values for a flag from an alternate input source the following
code would be added to wrap an existing cli.Flag like below:

go
altsrc.NewIntFlag(cli.IntFlag{Name: "test"})

Initialization must also occur for these flags. Below is an example initializing
getting data from a yaml file below.

go
command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))

The code above will use the "load" string as a flag name to get the file name of
a yaml file from the cli.Context. It will then use that file name to initialize
the yaml input source for any flags that are defined on that command. As a note
the "load" flag used would also have to be defined on the command flags in order
for this code snippet to work.

Currently only YAML, JSON, and TOML files are supported but developers can add support
for other input sources by implementing the altsrc.InputSourceContext for their
given sources.

Here is a more complete sample of a command using YAML support:

go
package notmain

import (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
  "github.com/urfave/cli/altsrc"
)

func main() {
  app := cli.NewApp()

  flags := []cli.Flag{
    altsrc.NewIntFlag(cli.IntFlag{Name: "test"}),
    cli.StringFlag{Name: "load"},
  }

  app.Action = func(c *cli.Context) error {
    fmt.Println("yaml is rad")
    return nil
  }

  app.Before = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("load"))
  app.Flags = flags

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Precedence

The precedence for flag value sources is as follows (highest to lowest):

  1. Command line flag value from user
  2. Environment variable (if specified)
  3. Configuration file (if specified)
  4. Default defined on the flag

File: docs/v1/examples/generated-help-text.md


tags:

  • v1

The default help flag (-h/--help) is defined as cli.HelpFlag and is checked
by the cli internals in order to print generated help text for the app, command,
or subcommand, and break execution.

Customization

All of the help text generation may be customized, and at multiple levels. The
templates are exposed as variables AppHelpTemplate, CommandHelpTemplate, and
SubcommandHelpTemplate which may be reassigned or augmented, and full override
is possible by assigning a compatible func to the cli.HelpPrinter variable,
e.g.:

go
package main

import (
  "fmt"
  "log"
  "io"
  "os"

  "github.com/urfave/cli"
)

func main() {
  // EXAMPLE: Append to an existing template
  cli.AppHelpTemplate = fmt.Sprintf(`%s

WEBSITE: http://awesometown.example.com

SUPPORT: [email protected]

`, cli.AppHelpTemplate)

  // EXAMPLE: Override a template
  cli.AppHelpTemplate = `NAME:
   {{.Name}} - {{.Usage}}
USAGE:
   {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
   {{if len .Authors}}
AUTHOR:
   {{range .Authors}}{{ . }}{{end}}
   {{end}}{{if .Commands}}
COMMANDS:
{{range .Commands}}{{if not .HideHelp}}   {{join .Names ", "}}{{ "\t"}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
   {{range .VisibleFlags}}{{.}}
   {{end}}{{end}}{{if .Copyright }}
COPYRIGHT:
   {{.Copyright}}
   {{end}}{{if .Version}}
VERSION:
   {{.Version}}
   {{end}}
`

  // EXAMPLE: Replace the `HelpPrinter` func
  cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
    fmt.Println("Ha HA.  I pwnd the help!!1")
  }

  err := cli.NewApp().Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

The default flag may be customized to something other than -h/--help by
setting cli.HelpFlag, e.g.:

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  cli.HelpFlag = cli.BoolFlag{
    Name: "halp, haaaaalp",
    Usage: "HALP",
    EnvVar: "SHOW_HALP,HALPPLZ",
  }

  err := cli.NewApp().Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

File: docs/v1/examples/greet.md


tags:

  • v1

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 (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()
  app.Name = "greet"
  app.Usage = "fight the loneliness!"
  app.Action = func(c *cli.Context) error {
    fmt.Println("Hello friend!")
    return nil
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Install our command to the $GOPATH/bin directory:

text
$ go install

Finally run our new command:

text
$ greet
Hello friend!

cli also generates neat help text:

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

File: docs/v1/examples/subcommands.md


tags:

  • v1

Subcommands can be defined for a more git-like command line app.

go
package main

import (
  "fmt"
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Commands = []cli.Command{
    {
      Name:    "add",
      Aliases: []string{"a"},
      Usage:   "add a task to the list",
      Action:  func(c *cli.Context) error {
        fmt.Println("added task: ", c.Args().First())
        return nil
      },
    },
    {
      Name:    "complete",
      Aliases: []string{"c"},
      Usage:   "complete a task on the list",
      Action:  func(c *cli.Context) error {
        fmt.Println("completed task: ", c.Args().First())
        return nil
      },
    },
    {
      Name:        "template",
      Aliases:     []string{"t"},
      Usage:       "options for task templates",
      Subcommands: []cli.Command{
        {
          Name:  "add",
          Usage: "add a new template",
          Action: func(c *cli.Context) error {
            fmt.Println("new task template: ", c.Args().First())
            return nil
          },
        },
        {
          Name:  "remove",
          Usage: "remove an existing template",
          Action: func(c *cli.Context) error {
            fmt.Println("removed task template: ", c.Args().First())
            return nil
          },
        },
      },
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

File: docs/v1/examples/subcommands-categories.md


tags:

  • v1

For additional organization in apps that have many subcommands, you can
associate a category for each command to group them together in the help
output.

E.g.

go
package main

import (
  "log"
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Commands = []cli.Command{
    {
      Name: "noop",
    },
    {
      Name:     "add",
      Category: "Template actions",
    },
    {
      Name:     "remove",
      Category: "Template actions",
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

Will include:

text
COMMANDS:
  noop

  Template actions:
    add
    remove

2. Official Technical Reference & Guides (urfave/cli-docs)

Welcome to urfave/cli-docs/v3



urfave/cli-docs/v3 is an extended documentation library for use with urfave/cli/v3.

Start using

  1. Add the dependency to your project
sh
go get github.com/urfave/cli-docs/v3@latest
  1. Add it as import
diff
import (
+  docs "github.com/urfave/cli-docs/v3"
 )
  1. Now use it e.g. to generate markdown document from a command
go
package main

import (
    "context"
    "fmt"
    "os"

    docs "github.com/urfave/cli-docs/v3"
    cli "github.com/urfave/cli/v3"
)

func main() {
    app := &cli.Command{
        Name:  "greet",
        Usage: "say a greeting",
        Action: func(ctx context.Context, c *cli.Command) error {
            fmt.Println("Greetings")
            return nil
        },
    }

    md, err := docs.ToMarkdown(app)
    if err != nil {
        panic(err)
    }

    fi, err := os.Create("cli-docs.md")
    if err != nil {
        panic(err)
    }
    defer fi.Close()
    if _, err := fi.WriteString("# CLI\n\n" + md); err != nil {
        panic(err)
    }
}

This will create a file cli-docs.md with content:

md
# CLI

# NAME

greet - say a greeting

# SYNOPSIS

greet

**Usage**:

```
greet [GLOBAL OPTIONS] [command [COMMAND OPTIONS]] [ARGUMENTS...]
```

Examples

Some examples of the cli generated using this markdown