### Start Documentation Development Server Source: https://github.com/urfave/cli/blob/main/docs/CONTRIBUTING.md Start an mkdocs development server to preview the documentation locally. ```sh make serve-docs ``` -------------------------------- ### Install gfmrun Source: https://github.com/urfave/cli/blob/main/docs/CONTRIBUTING.md Install the gfmrun tool, which is required to run examples. This command uses go install to get the latest version. ```sh go install github.com/urfave/gfmrun/cmd/gfmrun@latest ``` -------------------------------- ### Install and Run the CLI Application Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/greet.md Commands to install the Go application and then execute it from the terminal. The output shows the greeting and the generated help text. ```sh $ go install ``` ```sh $ greet Hello friend! ``` ```sh $ greet help NAME: greet - fight the loneliness! USAGE: greet [global options] GLOBAL OPTIONS: --help, -h show help ``` ```sh NAME: greet - fight the loneliness! USAGE: greet [global options] command [command options] [arguments...] COMMANDS: help, h Shows a list of commands or help for one command GLOBAL OPTIONS --help, -h show help (default: false) ``` -------------------------------- ### CLI App with Shell Completion Enabled (Default) Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/completions/shell-completions.md This Go program is a variation of the first example, specifically demonstrating the default setup for enabling shell completion without a specific command name defined at the root level. Ensure `EnableShellCompletion` is set to `true`. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ EnableShellCompletion: true, Commands: []*cli.Command{ { Name: "add", Aliases: []string{"a"}, Usage: "add a task to the list", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("added task: ", cmd.Args().First()) return nil }, }, { Name: "complete", Aliases: []string{"c"}, Usage: "complete a task on the list", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("completed task: ", cmd.Args().First()) return nil }, }, { Name: "template", Aliases: []string{"t"}, Usage: "options for task templates", Commands: []*cli.Command{ { Name: "add", Usage: "add a new template", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("new task template: ", cmd.Args().First()) return nil }, }, { Name: "remove", Usage: "remove an existing template", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("removed task template: ", cmd.Args().First()) return nil }, }, }, }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Greet Application Usage Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-commands.md Illustrates the basic usage pattern for the greet application, showing how to pass arguments. ```bash app [first_arg] [second_arg] ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/urfave/cli/blob/main/docs/CONTRIBUTING.md Install the necessary documentation dependencies using pip. ```sh make ensure-mkdocs ``` -------------------------------- ### Usage Command Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-flags.md Demonstrates the structure for the 'usage' command and its options. ```bash usage --another-flag value --flag value ``` -------------------------------- ### Example Command Line Usage with Short Options Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/short-options.md Demonstrates traditional command-line usage with individual short options. ```sh-session $ cmd -s -o -m "Some message" ``` -------------------------------- ### Greet CLI Usage Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-usagetext.md Illustrates the general command structure for the greet CLI, showing how to use global options, commands, and arguments. ```bash greet [GLOBAL OPTIONS] [command [COMMAND OPTIONS]] [ARGUMENTS...] ``` -------------------------------- ### Sub-command Usage Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-full.md Demonstrates the usage of a sub-command with its own flags. ```bash >Single line of UsageText ``` -------------------------------- ### Basic CLI Application with a Command Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Shows how to create a functional CLI application with a named command that performs an action. This example defines a 'greet' command that prints 'Greetings'. ```Go func main() { cmd := &cli.Command{ Name: "greet", Usage: "say a greeting", Action: func(c *cli.Context) error { fmt.Println("Greetings") return nil }, } cmd.Run(context.Background(), os.Args) } ``` -------------------------------- ### Sub-Usage Command Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-flags.md Illustrates the usage of the 'sub-usage' subcommand with its specific flags. ```bash sub-usage --sub-command-flag value --sub-flag value ``` -------------------------------- ### Install urfave/cli v3 Source: https://github.com/urfave/cli/blob/main/docs/index.md Use this command to install the latest v3 release of urfave/cli. This is the recommended version for new development. ```sh go get github.com/urfave/cli/v3@latest ``` -------------------------------- ### Initialize urfave/cli Customizations Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/full-api-example.md Customize help templates, flags, and printers globally. This setup affects all commands and flags within the application. ```go package main import ( "context" "errors" "fmt" "io" "io/ioutil" "os" "time" "slices" "github.com/urfave/cli/v3" ) func init() { cli.RootCommandHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n" cli.CommandHelpTemplate += "\nYMMV\n" cli.SubcommandHelpTemplate += "\nor something\n" cli.HelpFlag = &cli.BoolFlag{Name: "halp"} cli.VersionFlag = &cli.BoolFlag{Name: "print-version", Aliases: []string{"V"}} cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { fmt.Fprintf(w, "best of luck to you\n") } cli.VersionPrinter = func(cmd *cli.Command) { fmt.Fprintf(cmd.Root().Writer, "version=%s\n", cmd.Root().Version) } cli.OsExiter = func(cmd int) { fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", cmd) } cli.ErrWriter = ioutil.Discard cli.FlagStringer = func(fl cli.Flag) string { return fmt.Sprintf("\t\t%s", fl.Names()[0]) } } ``` -------------------------------- ### Get Multiple Integer Arguments Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/arguments/advanced.md Demonstrates how to define and retrieve multiple integer arguments using `IntArgs` and `cmd.IntArgs()`. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Arguments: []cli.Argument{ &cli.IntArgs{ Name: "someint", Min: 0, Max: -1, }, }, Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("We got ", cmd.IntArgs("someint")) return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Combined Short Option Usage Example Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/short-options.md Illustrates how combined short options can be used when `UseShortOptionHandling` is enabled. ```sh-session $ cmd -som "Some message" ``` -------------------------------- ### Compiler Error Message Example Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md Example compiler message when migrating ActionFunc from v2 to v3. ```go cannot use func literal (type func(*cli.Context) error) as type cli.ActionFunc in field value ``` -------------------------------- ### Install urfave/cli v2 Source: https://github.com/urfave/cli/blob/main/docs/index.md Use this command to install the latest v2 release of urfave/cli. This version is only receiving security and bug fixes. ```sh go get github.com/urfave/cli/v2@latest ``` -------------------------------- ### Define a Function Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-full.md A simple function definition example. ```bash func() { ... } ``` -------------------------------- ### Timestamp Flag Example Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/basics.md Demonstrates how to use a TimestampFlag with a specific layout. Ensure the provided date string matches the defined layout. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Flags: []cli.Flag{ &cli.TimestampFlag{ Name: "meeting", Config: cli.TimestampConfig{ Layouts: []string{"2006-01-02T15:04:05"}, }, }, }, Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Printf("%s", cmd.Timestamp("meeting").String()) return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` ```sh-session $ myapp --meeting 2019-08-12T15:04:05 ``` -------------------------------- ### Placeholder Function Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-authors.md A placeholder function definition. This snippet is likely a template or an example of where custom logic would be implemented within a CLI command. ```go ``` func() { ... } ``` ``` -------------------------------- ### Glob Argument Example Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/arguments/advanced.md Illustrates how to use a glob argument with `Max: -1` at the end of the Arguments slice to capture remaining values. ```go &StringArgs{ Max: -1, } ``` -------------------------------- ### Defining a Simple Command Source: https://github.com/urfave/cli/blob/main/testdata/godoc-v3.x.txt Defines a basic command with a name, usage, and an action that prints a greeting. This is a fundamental example for creating interactive CLI tools. ```Go func main() { cmd := &cli.Command{ Name: "greet", Usage: "say a greeting", Action: func(c *cli.Context) error { fmt.Println("Greetings") return nil }, } cmd.Run(context.Background(), os.Args) } ``` -------------------------------- ### BoolWithInverseFlag String Method Example Source: https://github.com/urfave/cli/blob/main/testdata/godoc-v3.x.txt Demonstrates how the String() method formats the output for a BoolWithInverseFlag, including its name and aliases. It shows the expected command-line syntax for setting and negating the flag. ```go func (bif *BoolWithInverseFlag) String() string String implements the standard Stringer interface. Example for BoolFlag{Name: "env"} --[no-]env (default: false) Example for BoolFlag{Name: "env", Aliases: []string{"e"}} --[no-]env, -e (default: false) ``` -------------------------------- ### urfave/cli v3 Application with Action Source: https://github.com/urfave/cli/blob/main/docs/v3/getting-started.md An urfave/cli application with a defined command and action. This example includes error handling for the command execution. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Name: "boom", Usage: "make an explosive entrance", Action: func(context.Context, *cli.Command) error { fmt.Println("boom! I say!") return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### StringFlag Example Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/basics.md Demonstrates a StringFlag for setting a language preference. The default value is 'english', and the flag can be set using space or '=' notation. The output changes based on the flag's value. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Flags: []cli.Flag{ &cli.StringFlag{ Name: "lang", Value: "english", Usage: "language for the greeting", }, }, Action: func(ctx context.Context, cmd *cli.Command) error { name := "Nefertiti" if cmd.NArg() > 0 { name = cmd.Args().Get(0) } if cmd.String("lang") == "spanish" { fmt.Println("Hola", name) } else { fmt.Println("Hello", name) } return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` ```sh-session $ greet Hello Nefertiti ``` ```sh-session $ greet --lang spanish Hola Nefertiti ``` ```sh-session $ greet --lang=spanish Hola Nefertiti ``` ```sh-session $ greet --lang=spanish my-friend Hola my-friend ``` -------------------------------- ### Customize Help Flag Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/help/generated-help-text.md Customizes the default help flag to a different name and adds aliases. This example sets the flag to 'haaaaalp' with an alias 'halp'. ```go package main import ( "os" "context" "github.com/urfave/cli/v3" ) func main() { cli.HelpFlag = &cli.BoolFlag{ Name: "haaaaalp", Aliases: []string{"halp"}, Usage: "HALP", Sources: cli.EnvVars("SHOW_HALP", "HALPPLZ"), } (&cli.Command{}).Run(context.Background(), os.Args) } ``` -------------------------------- ### Get Command Path with Path() Source: https://github.com/urfave/cli/blob/main/docs/v3/path-and-walk.md Use `Command.Path()` to retrieve a slice of strings representing the command names from the root to the current command. This is useful for constructing the full command path. ```go package main import ( "context" "fmt" "os" "strings" "github.com/urfave/cli/v3" ) func main() { subSubCmd := &cli.Command{Name: "bottom", Action: func(context.Context, *cli.Command) error { return nil }} subCmd := &cli.Command{Name: "mid", Subcommands: []*cli.Command{subSubCmd}, Action: func(context.Context, *cli.Command) error { return nil }} cmd := &cli.Command{ Name: "top", Subcommands: []*cli.Command{subCmd}, Action: func(ctx context.Context, c *cli.Command) error { fmt.Println(strings.Join(c.Path(), " ")) return nil }, } cmd.Run(context.Background(), []string{"top", "mid", "bottom"}) } ``` ```sh $ go run . top mid bottom ``` -------------------------------- ### Access Multiple Arguments and Count in Go CLI Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/arguments/basics.md Utilize `cmd.Args().Len()` to get the total number of arguments and iterate using `cmd.Args().Get(i)` to access each one. This example concatenates all arguments into a single output string. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Printf("Number of args : %d\n", cmd.Args().Len()) var out string for i := 0; i < cmd.Args().Len(); i++ { out = out + fmt.Sprintf(" %v", cmd.Args().Get(i)) } fmt.Printf("Hello%v", out) return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` ```sh $ greet Friend 1 bar 2.0 Number of args : 4 Hello Friend 1 bar 2.0 ``` -------------------------------- ### ZSH Auto-completion Setup Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/completions/shell-completions.md For ZSH users, add the provided lines to your `.zshrc` file to enable persistent auto-completion across new shell sessions. This involves setting a program variable and sourcing the completion script. ```sh-session $ PROG= $ source path/to/autocomplete/zsh_autocomplete ``` -------------------------------- ### Define and Run CLI Application Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/full-api-example.md Sets up a root command with subcommands, handles environment variable overrides for writers, and runs the application. ```go func main() { cmd := &cli.Command{ Name: "app", Usage: "app usage", Subcommands: []cli.Command{ { Name: "doo", Usage: "doo usage", Description: "this is a description", ArgsUsage: "[arguments...]", Flags: []cli.Flag{ &cli.BoolFlag{Name: "infinite"}, &cli.BoolFlag{Name: "forevar"}, }, Category: "test", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Fprintf(cmd.Root().Writer, "WRONG: %#v\n", err) return nil }, Action: func(ctx context.Context, cmd *cli.Command) error { cli.DefaultRootCommandComplete(ctx, cmd) cli.HandleExitCoder(errors.New("not an exit coder, though")) cli.ShowRootCommandHelp(cmd) cli.ShowCommandHelp(ctx, cmd, "also-nope") cli.ShowSubcommandHelp(cmd) cli.ShowVersion(cmd) fmt.Printf("%#v\n", cmd.Root().Command("doo")) if cmd.Bool("infinite") { cmd.Root().Run(ctx, []string{"app", "doo", "wop"}) } if cmd.Bool("forevar") { cmd.Root().Run(ctx, nil) } fmt.Printf("%#v\n", cmd.Root().VisibleCategories()) fmt.Printf("%#v\n", cmd.Root().VisibleCommands()) fmt.Printf("%#v\n", cmd.Root().VisibleFlags()) fmt.Printf("%#v\n", cmd.Args().First()) if cmd.Args().Len() > 0 { fmt.Printf("%#v\n", cmd.Args().Get(1)) } fmt.Printf("%#v\n", cmd.Args().Present()) fmt.Printf("%#v\n", cmd.Args().Tail()) ec := cli.Exit("ohwell", 86) fmt.Fprintf(cmd.Root().Writer, "%d", ec.ExitCode()) fmt.Printf("made it!\n") return ec }, Metadata: map[string]interface{}{ "layers": "many", "explicable": false, "whatever-values": 19.99, }, } }, } if os.Getenv("HEXY") != "" { cmd.Writer = &hexWriter{} cmd.ErrWriter = &hexWriter{} } cmd.Run(context.Background(), os.Args) } func wopAction(ctx context.Context, cmd *cli.Command) error { fmt.Fprintf(cmd.Root().Writer, ":wave: over here, eh\n") return nil } ``` -------------------------------- ### Minimal CLI Application Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Demonstrates the most basic structure for a command-line application using the cli package. It initializes a command and runs it. ```Go func main() { (&cli.Command{}).Run(context.Background(), os.Args) } ``` -------------------------------- ### Build Documentation Site Source: https://github.com/urfave/cli/blob/main/docs/CONTRIBUTING.md Build the static documentation site into the './site' directory. ```sh make docs ``` -------------------------------- ### Basic CLI App with Shell Completion Enabled Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/completions/shell-completions.md This Go program demonstrates setting up a CLI application with shell completion enabled. Ensure `EnableShellCompletion` is set to `true` on the root command. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Name: "greet", EnableShellCompletion: true, Commands: []*cli.Command{ { Name: "add", Aliases: []string{"a"}, Usage: "add a task to the list", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("added task: ", cmd.Args().First()) return nil }, }, { Name: "complete", Aliases: []string{"c"}, Usage: "complete a task on the list", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("completed task: ", cmd.Args().First()) return nil }, }, { Name: "template", Aliases: []string{"t"}, Usage: "options for task templates", Commands: []*cli.Command{ { Name: "add", Usage: "add a new template", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("new task template: ", cmd.Args().First()) return nil }, }, { Name: "remove", Usage: "remove an existing template", Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("removed task template: ", cmd.Args().First()) return nil }, }, }, }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Altsrc Flag Declaration v2 Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md Example of declaring an Altsrc flag in v2. ```go altsrc.NewStringFlag( &cli.StringFlag{ Name: "key", Value: "/tmp/foo", }, ), ``` -------------------------------- ### Go Program with Short Option Handling Enabled Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/short-options.md A Go program demonstrating how to enable `UseShortOptionHandling` for a command, allowing combined short options. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ UseShortOptionHandling: true, Commands: []*cli.Command{ { Name: "short", Usage: "complete a task on the list", Flags: []cli.Flag{ &cli.BoolFlag{Name: "serve", Aliases: []string{"s"}}, &cli.BoolFlag{Name: "option", Aliases: []string{"o"}}, &cli.StringFlag{Name: "message", Aliases: []string{"m"}}, }, Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Println("serve:", cmd.Bool("serve")) fmt.Println("option:", cmd.Bool("option")) fmt.Println("message:", cmd.String("message")) return nil }, }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-full.md Illustrates the basic structure for defining command-line arguments and flags. ```bash [--another-flag|-b] [--flag|--fl|-f]=[value] [--socket|-s]=[value] ``` ```bash app [first_arg] [second_arg] ``` -------------------------------- ### Greet Application Synopsis Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-commands.md Defines the command-line structure for the greet application, including optional flags and their arguments. ```bash [--another-flag|-b] [--flag|--fl|-f]=[value] [--socket|-s]=[value] ``` -------------------------------- ### Get Integer Argument Value Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/arguments/advanced.md Demonstrates how to define and retrieve an integer argument using `IntArg` and the `cmd.IntArg()` function. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Arguments: []cli.Argument{ &cli.IntArg{ Name: "someint", }, }, Action: func(ctx context.Context, cmd *cli.Command) error { fmt.Printf("We got %d", cmd.IntArg("someint")) return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` ```sh $ greet 10 We got 10 ``` -------------------------------- ### Create a Basic Greeter Command in Go Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/greet.md Defines a simple command-line application that prints a greeting. Ensure the 'urfave/cli/v3' package is imported. ```go package main import ( "fmt" "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Name: "greet", Usage: "fight the loneliness!", Action: func(context.Context, *cli.Command) error { fmt.Println("Hello friend!") return nil }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Build and Measure Basic Binary Size Source: https://github.com/urfave/cli/blob/main/docs/v3/binary-size.md Compile your Go application and check its file size. Use -trimpath for reproducible build paths. ```sh go build -trimpath -o myapp ./cmd/myapp ls -lh myapp ``` -------------------------------- ### Altsrc Flag Declaration v3 with JSON Source Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md In v3, Altsrc is integrated as a ValueSource, shown here with a JSON source example. ```go cli.StringFlag{ Sources: cli.NewValueSourceChain(altsrcjson.JSON("key", altsrc.StringSourcer("/path/to/foo.json"))), } ``` -------------------------------- ### FlagBase Get Method Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Retrieves the flag's value. The return type is 'any' as it depends on the generic type T. ```go func (f *FlagBase[T, C, V]) Get() any ``` -------------------------------- ### ShowAppHelp Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Displays help for the root command. This is a backward-compatible alias for ShowRootCommandHelp. ```APIDOC ## ShowAppHelp ### Description Displays help for the root command. This is a backward-compatible alias for ShowRootCommandHelp. ### Usage `ShowAppHelp` ``` -------------------------------- ### Run All Verification Steps Source: https://github.com/urfave/cli/blob/main/docs/CONTRIBUTING.md Execute the default 'make' target to run all critical steps for verifying changes. This is also run during the CI phase. ```sh make ``` -------------------------------- ### String Slice Initialization: v1 vs v2 Source: https://github.com/urfave/cli/blob/main/docs/migrate-v1-to-v2.md In v2, use `cli.NewStringSlice("")` instead of `&cli.StringSlice({""})` for initializing string slices. ```go Value: &cli.StringSlice{"}, ``` ```go Value: cli.NewStringSlice(""), ``` -------------------------------- ### CommandCategory Interface Source: https://github.com/urfave/cli/blob/main/testdata/godoc-v3.x.txt The CommandCategory interface represents a category containing commands and provides methods to get the category name and its visible commands. ```APIDOC ## interface CommandCategory ### Description A category containing commands. ### Methods #### Name Returns the category name string. #### VisibleCommands Returns a slice of the Commands with Hidden=false. ``` -------------------------------- ### v3 BeforeFunc Signature Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md The v3 signature for BeforeFunc, now including context.Context and *cli.Command. ```go type BeforeFunc func(context.Context, *cli.Command) (context.Context, error) ``` -------------------------------- ### Custom Version Printer Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/basics.md Override the default version printer at cli.VersionPrinter to customize how the version information is displayed. This example includes a revision string. ```go package main import ( "fmt" "os" "context" "github.com/urfave/cli/v3" ) var ( Revision = "fafafaf" ) func main() { cli.VersionPrinter = func(cmd *cli.Command) { fmt.Printf("version=%s revision=%s\n", cmd.Root().Version, Revision) } cmd := &cli.Command{ Name: "partay", Version: "v19.99.0", } cmd.Run(context.Background(), os.Args) } ``` -------------------------------- ### Minimal urfave/cli v3 Application Source: https://github.com/urfave/cli/blob/main/docs/v3/getting-started.md A basic urfave/cli application that shows help text. It requires no arguments to run. ```go package main import ( "os" "context" "github.com/urfave/cli/v3" ) func main() { (&cli.Command{}).Run(context.Background(), os.Args) } ``` -------------------------------- ### ShowCommandHelp Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Prints help for the given command. This is an alias for DefaultShowCommandHelp. ```APIDOC ## ShowCommandHelp ### Description Prints help for the given command. This is an alias for DefaultShowCommandHelp. ### Usage `ShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error` ``` -------------------------------- ### Basic CLI Application Source: https://github.com/urfave/cli/blob/main/testdata/godoc-v3.x.txt The simplest possible urfave/cli application. It initializes a command and runs it. ```Go func main() { (&cli.Command{}).Run(context.Background(), os.Args) } ``` -------------------------------- ### ShowSubcommandHelp Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Prints help for the given subcommand. This is an alias for DefaultShowSubcommandHelp. ```APIDOC ## ShowSubcommandHelp ### Description Prints help for the given subcommand. This is an alias for DefaultShowSubcommandHelp. ### Usage `ShowSubcommandHelp(cmd *Command) error` ``` -------------------------------- ### Argument Interface Definition Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Defines the interface for a single command-line argument, including methods for checking its name, parsing, retrieving usage text, and getting its value. ```go type Argument interface { // which this argument can be accessed using the given name HasName(string) bool // Parse the given args and return unparsed args and/or error Parse([]string) ([]string, error) // The usage template for this argument to use in help Usage() string // The Value of this Arg Get() any } Argument captures a positional argument that can be parsed ``` -------------------------------- ### ValueSource Interface Source: https://github.com/urfave/cli/blob/main/testdata/godoc-v3.x.txt The ValueSource interface defines a contract for retrieving values from various sources. It includes a Lookup method to get the value and a boolean indicating if it was found. ```APIDOC ## ValueSource Interface ### Description ValueSource is an interface for sources that can be used to look up a value, typically for use with a cli.Flag. It includes methods for string representation and looking up values. ### Methods - **Lookup() (string, bool)**: Returns the value from the source and a boolean indicating if it was found. Returns an empty string and false if not found. ``` -------------------------------- ### BeforeFunc Type Definition Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Defines a function type that executes prior to any subcommands being run, allowing for context setup or pre-execution logic. It returns a context and an error. ```go type BeforeFunc func(context.Context, *Command) (context.Context, error) BeforeFunc is an action that executes prior to any subcommands being run once the context is ready. If a non-nil error is returned, no subcommands are run. ``` -------------------------------- ### Order of Precedence for Sources v2 Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md Demonstrates the order of precedence for EnvVars and FilePath in v2 when using Altsrc. ```go altsrc.NewStringFlag( &cli.StringFlag{ Name: "key", EnvVars: []string{"APP_LANG"}, FilePath: "/path/to/foo", }, ), ``` -------------------------------- ### DefaultShowRootCommandHelp Source: https://github.com/urfave/cli/blob/main/godoc-current.txt The default implementation of ShowRootCommandHelp. ```APIDOC ## DefaultShowRootCommandHelp ### Description The default implementation of ShowRootCommandHelp. ### Usage `DefaultShowRootCommandHelp(cmd *Command) error` ``` -------------------------------- ### Custom Version Flag Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/basics.md Customize the default version flag (-v/--version) by setting the Name and Aliases fields of cli.VersionFlag. This example changes it to --print-version. ```go package main import ( "os" "context" "github.com/urfave/cli/v3" ) func main() { cli.VersionFlag = &cli.BoolFlag{ Name: "print-version", Aliases: []string{"V"}, Usage: "print only the version", } cmd := &cli.Command{ Name: "partay", Version: "v19.99.0", } cmd.Run(context.Background(), os.Args) } ``` -------------------------------- ### Config Command Usage Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-flags.md Shows the usage of the 'config' command with its flags and subcommands. ```bash config [command] [subcommand] --flag value --another-flag value ``` -------------------------------- ### Define Subcommand Flags Example Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-authors.md Defines flags specific to a subcommand, including their short and long forms, and usage text. This is used within the definition of a subcommand in a CLI application. ```go ``` --sub-command-flag, -s: some usage text ``` ``` -------------------------------- ### Get Current Version Source: https://github.com/urfave/cli/blob/main/docs/RELEASING.md Use this command to retrieve the current version of the project, including dirty status if applicable. A 'dirty' work tree is not suitable for creating a release tag. ```sh git describe --always --dirty --tags ``` -------------------------------- ### Read Default Value from YAML File Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/value-sources.md Integrate with `urfave/cli-altsrc` to read default flag values from a YAML file. This example shows how to specify the key within the YAML and the path to the file. ```go package main import ( "log" "os" "context" "github.com/urfave/cli/v3" "github.com/urfave/cli-altsrc/v3" yaml "github.com/urfave/cli-altsrc/v3/yaml" ) func main() { cmd := &cli.Command{ Flags: []cli.Flag{ &cli.StringFlag{ Name: "password", Aliases: []string{"p"}, Usage: "password for the mysql database", Sources: cli.NewValueSourceChain(yaml.YAML("somekey", altsrc.StringSourcer("/path/to/filename"))), }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Generate Bash Completion Script Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/completions/shell-completions.md After compiling your Go application (e.g., as `greet`), you can generate the bash completion script by running the `completion bash` subcommand. This script can then be sourced or saved to a directory like `/etc/bash_completion.d/`. ```sh-session $ greet completion bash ``` -------------------------------- ### Args Interface Definition Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Defines the interface for accessing command-line arguments, providing methods to retrieve arguments by index, get the first or tail arguments, check length, and check for presence. ```go type Args interface { // Get returns the nth argument, or else a blank string Get(n int) string // First returns the first argument, or else a blank string First() string // Tail returns the rest of the arguments (not the first one) // or else an empty string slice Tail() []string // Len returns the length of the wrapped slice Len() int // Present checks if there are any arguments present Present() bool // Slice returns a copy of the internal slice Slice() []string } ``` -------------------------------- ### Define Flag with Placeholder in Usage Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/advanced.md Use backticks within the Usage string of a StringFlag to indicate a placeholder value. This placeholder will be displayed in the help output to guide users on the expected input. ```go package main import ( "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Flags: []cli.Flag{ &cli.StringFlag{ Name: "config", Aliases: []string{"c"}, Usage: "Load configuration from `FILE`", }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### CommandHelpTemplate Definition Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Defines the text template used for rendering the help information for individual commands. This allows for custom help text formatting. ```Go var CommandHelpTemplate = `# {{ .Command.Name }} fish shell completion function __fish_{{ .Command.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' for i in (commandline -opc) if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} return 1 end end return 0 end {{ range $v := .Completions }}{{ $v }} {{ end }}` ``` -------------------------------- ### Main Command Definition with Subcommands and Flags Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/full-api-example.md Define the root command with various flags, subcommands, and lifecycle hooks. This serves as the entry point for the CLI application. ```go func main() { cmd := &cli.Command{ Name: "kənˈtrīv", Version: "v19.99.0", /*Authors: []any{ &cli.Author{ Name: "Example Human", Email: "human@example.com", }, */ Copyright: "(c) 1999 Serious Enterprise", Usage: "demonstrate available API", UsageText: "contrive - demonstrating the available API", ArgsUsage: "[args and such]", Commands: []*cli.Command{ &cli.Command{ Name: "doo", Aliases: []string{"do"}, Category: "motion", Usage: "do the doo", UsageText: "doo - does the dooing", Description: "no really, there is a lot of dooing to be done", ArgsUsage: "[arrgh]", Flags: []cli.Flag{ &cli.BoolFlag{Name: "forever", Aliases: []string{"forevvarr"}}, }, Commands: []*cli.Command{ &cli.Command{ Name: "wop", Action: wopAction, }, }, SkipFlagParsing: false, HideHelp: false, Hidden: false, ShellComplete: func(ctx context.Context, cmd *cli.Command) { fmt.Fprintf(cmd.Root().Writer, "--better\n") }, Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) { fmt.Fprintf(cmd.Root().Writer, "brace for impact\n") return nil, nil }, After: func(ctx context.Context, cmd *cli.Command) error { fmt.Fprintf(cmd.Root().Writer, "did we lose anyone?\n") return nil }, Action: func(ctx context.Context, cmd *cli.Command) error { cmd.FullName() cmd.HasName("wop") cmd.Names() cmd.VisibleFlags() fmt.Fprintf(cmd.Root().Writer, "dodododododoodododddooooododododooo\n") if cmd.Bool("forever") { cmd.Run(ctx, nil) } return nil }, OnUsageError: func(ctx context.Context, cmd *cli.Command, err error, isSubcommand bool) error { fmt.Fprintf(cmd.Root().Writer, "for shame\n") return err }, }, }, Flags: []cli.Flag{ &cli.BoolFlag{Name: "fancy"}, &cli.BoolFlag{Value: true, Name: "fancier"}, &cli.DurationFlag{Name: "howlong", Aliases: []string{"H"}, Value: time.Second * 3}, &cli.FloatFlag{Name: "howmuch"}, &cli.IntFlag{Name: "longdistance", Validator: func (t int) error { if t < 10 { return fmt.Errorf("10 miles isn't long distance!!!!!!") } return nil }}, &cli.IntSliceFlag{Name: "intervals"}, &cli.StringFlag{Name: "dance-move", Aliases: []string{"d"}, Validator: func(move string) error { moves := []string{"salsa", "tap", "two-step", "lock-step"} if !slices.Contains(moves, move) { return fmt.Errorf("Haven't learnt %s move yet", move) } return nil }}, &cli.StringSliceFlag{Name: "names", Aliases: []string{"N"}}, &cli.UintFlag{Name: "age"}, }, EnableShellCompletion: true, HideHelp: false, HideVersion: false, ShellComplete: func(ctx context.Context, cmd *cli.Command) { fmt.Fprintf(cmd.Root().Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") }, Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) { fmt.Fprintf(cmd.Root().Writer, "HEEEERE GOES\n") return nil, nil }, After: func(ctx context.Context, cmd *cli.Command) error { fmt.Fprintf(cmd.Root().Writer, "Phew!\n") return nil }, CommandNotFound: func(ctx context.Context, cmd *cli.Command, command string) { fmt.Fprintf(cmd.Root().Writer, "Thar be no %q here.\n", command) }, OnUsageError: func(ctx context.Context, cmd *cli.Command, err error, isSubcommand bool) error { if isSubcommand { return err } ``` -------------------------------- ### Basic Application Usage Source: https://github.com/urfave/cli/blob/main/testdata/expected-doc-no-authors.md Illustrates the fundamental structure for invoking a CLI application with arguments. This pattern is common for simple CLIs that accept positional parameters. ```bash ``` app [first_arg] [second_arg] ``` ``` -------------------------------- ### Implement Flag Validation with Actions in Go Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/flags/advanced.md Register a handler per flag using the `Action` field to perform validation or other logic after a flag is processed. This example validates an integer flag against a specific range. ```go package main import ( "log" "os" "fmt" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ Flags: []cli.Flag{ &cli.IntFlag{ Name: "port", Usage: "Use a randomized port", Value: 0, DefaultText: "random", Action: func(ctx context.Context, cmd *cli.Command, v int) error { if v >= 65536 { return fmt.Errorf("Flag port value %v out of range[0-65535]", v) } return nil }, }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Redefine Default Shell Completion Flag Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/completions/customizations.md The default shell completion flag (`--generate-shell-completion`) can be redefined by setting `cli.EnableShellCompletion` to true. This example demonstrates enabling shell completion for a command named 'wat'. ```go package main import ( "log" "os" "context" "github.com/urfave/cli/v3" ) func main() { cmd := &cli.Command{ EnableShellCompletion: true, Commands: []*cli.Command{ { Name: "wat", }, }, } if err := cmd.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Enable Flag and Command Suggestions Source: https://github.com/urfave/cli/blob/main/docs/v3/examples/help/suggestions.md Set `Command.Suggest` to `true` to enable the suggestion feature. This will provide suggestions in the help output for incorrect flags or subcommands. ```go Command.Suggest = true ``` -------------------------------- ### DefaultRootCommandComplete Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Prints the list of subcommands as the default completion method. ```APIDOC ## DefaultRootCommandComplete ### Description Prints the list of subcommands as the default completion method. ### Usage `DefaultRootCommandComplete(ctx context.Context, cmd *Command)` ``` -------------------------------- ### Argument Interface Source: https://github.com/urfave/cli/blob/main/godoc-current.txt The Argument interface defines the contract for a single command-line argument. It includes methods for checking if an argument has a specific name, parsing arguments, retrieving usage information, and getting the argument's value. ```APIDOC ## Interface: Argument ### Description Captures a positional argument that can be parsed. It defines methods for name checking, parsing, usage display, and value retrieval. ### Methods - **HasName(string) bool** Checks if this argument can be accessed using the given name. - **Parse([]string) ([]string, error)** Parses the given arguments and returns unparsed arguments and/or an error. - **Usage() string** Returns the usage template for this argument to use in help messages. - **Get() any** Returns the Value of this Argument. ``` -------------------------------- ### PathFlag Migration v2 to v3 Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md Illustrates how PathFlag in v2 is replaced by StringFlag with TakesFile set to true in v3. ```go v2: &cli.PathFlag{ Name: "foo", } v3: &cli.StringFlag{ Name: "foo", TakesFile: true, } ``` -------------------------------- ### Flag Interface Source: https://github.com/urfave/cli/blob/main/testdata/godoc-v3.x.txt The Flag interface is a common interface related to parsing flags in cli. It provides methods for retrieving flag values, lifecycle callbacks, setting flag values, getting flag names, and checking if a flag has been set. ```APIDOC ## interface Flag ### Description A common interface related to parsing flags in cli. For more advanced flag parsing techniques, it is recommended that this interface be implemented. ### Methods #### Get Retrieves the value of the Flag. #### PreParse Callback executed prior to parsing the flag. #### PostParse Callback executed post parsing the flag. #### Set Applies flag settings to the given flag set. #### Names Returns all possible names for this flag. #### IsSet Returns whether the flag has been set or not. ``` -------------------------------- ### ShowSubcommandHelpAndExit Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Prints help for the given subcommand via ShowSubcommandHelp and exits with exit code. ```APIDOC ## ShowSubcommandHelpAndExit ### Description Prints help for the given subcommand via ShowSubcommandHelp and exits with exit code. ### Usage `ShowSubcommandHelpAndExit(cmd *Command, exitCode int)` ``` -------------------------------- ### ShowAppHelpAndExit Source: https://github.com/urfave/cli/blob/main/godoc-current.txt Exits after displaying help for the root command. This is a backward-compatible alias for ShowRootCommandHelpAndExit. ```APIDOC ## ShowAppHelpAndExit ### Description Exits after displaying help for the root command. This is a backward-compatible alias for ShowRootCommandHelpAndExit. ### Usage `ShowAppHelpAndExit` ``` -------------------------------- ### Update Import Path Source: https://github.com/urfave/cli/blob/main/docs/migrate-v2-to-v3.md Change the import path from v2 to v3. ```go import "github.com/urfave/cli/v2" ``` ```go import "github.com/urfave/cli/v3" ``` -------------------------------- ### DefaultShowCommandHelp Source: https://github.com/urfave/cli/blob/main/godoc-current.txt The default implementation of ShowCommandHelp. ```APIDOC ## DefaultShowCommandHelp ### Description The default implementation of ShowCommandHelp. ### Usage `DefaultShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error` ```