// List of all authors who contributed (string or fmt.Stringer) · pkg.go.dev

Package cli provides a minimal framework for creating and organizing command line Go applications. cli is designed to be easy to understand and write, the most simple cli application can be written as follows:

func main() {
	(&cli.Command{}).Run(context.Background(), os.Args)
}

Of course this application does not do much, so let's make this an actual application:

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)
}

This section is empty.

View Source

var (
	NewIntSlice   = NewSliceBase[int, IntegerConfig, intValue[int]]
	NewInt8Slice  = NewSliceBase[int8, IntegerConfig, intValue[int8]]
	NewInt16Slice = NewSliceBase[int16, IntegerConfig, intValue[int16]]
	NewInt32Slice = NewSliceBase[int32, IntegerConfig, intValue[int32]]
	NewInt64Slice = NewSliceBase[int64, IntegerConfig, intValue[int64]]
)

View Source

var (
	NewUintSlice   = NewSliceBase[uint, IntegerConfig, uintValue[uint]]
	NewUint8Slice  = NewSliceBase[uint8, IntegerConfig, uintValue[uint8]]
	NewUint16Slice = NewSliceBase[uint16, IntegerConfig, uintValue[uint16]]
	NewUint32Slice = NewSliceBase[uint32, IntegerConfig, uintValue[uint32]]
	NewUint64Slice = NewSliceBase[uint64, IntegerConfig, uintValue[uint64]]
)

View Source

var (
	SuggestFlag               SuggestFlagFunc    = suggestFlag
	SuggestCommand            SuggestCommandFunc = suggestCommand
	SuggestDidYouMeanTemplate string             = suggestDidYouMeanTemplate
)

AnyArguments to differentiate between no arguments(nil) vs aleast one

ArgsUsageCommandHelp is a short description of the arguments of the help command

CommandHelpTemplate is the text template for the command help topic. cli.go uses text/template to render templates. You can render custom help text by setting this variable.

DefaultAppComplete is a backward-compatible name for DefaultRootCommandComplete.

ErrWriter is used to write errors to the user. This can be anything implementing the io.Writer interface and defaults to os.Stderr.

OsExiter is the function used when the app exits. If not set defaults to os.Exit.

RootCommandHelpTemplate is the text template for the Default help topic. cli.go uses text/template to render templates. You can render custom help text by setting this variable.

ShowAppHelp is a backward-compatible name for ShowRootCommandHelp.

ShowAppHelpAndExit is a backward-compatible name for ShowRootCommandHelp.

ShowCommandHelp prints help for the given command

ShowRootCommandHelp is an action that displays help for the root command.

ShowSubcommandHelp prints help for the given subcommand

SubcommandHelpTemplate is the text template for the subcommand help topic. cli.go uses text/template to render templates. You can render custom help text by setting this variable.

View Source

var UsageCommandHelp = "Shows a list of commands or help for one command"

UsageCommandHelp is the text to override the USAGE section of the help command

VersionPrinter prints the version for the root Command.

DefaultPrintHelp is the default implementation of HelpPrinter.

DefaultPrintHelpCustom is the default implementation of HelpPrinterCustom.

The customFuncs map will be combined with a default template.FuncMap to allow using arbitrary functions in template rendering.

func DefaultPrintVersion(cmd *Command)

DefaultPrintVersion is the default implementation of VersionPrinter.

func DefaultRootCommandComplete added in v3.4.0

DefaultRootCommandComplete prints the list of subcommands as the default completion method.

func DefaultShowCommandHelp added in v3.4.0

DefaultShowCommandHelp is the default implementation of ShowCommandHelp.

func DefaultShowRootCommandHelp added in v3.4.0

func DefaultShowRootCommandHelp(cmd *Command) error

DefaultShowRootCommandHelp is the default implementation of ShowRootCommandHelp.

func DefaultShowSubcommandHelp added in v3.4.0

func DefaultShowSubcommandHelp(cmd *Command) error

DefaultShowSubcommandHelp is the default implementation of ShowSubcommandHelp.

func HandleExitCoder

func HandleExitCoder(err error)

HandleExitCoder handles errors implementing ExitCoder by printing their message and calling OsExiter with the given exit code.

If the given error instead implements MultiError, each error will be checked for the ExitCoder interface, and OsExiter will be called with the last exit code found, or exit code 1 if no ExitCoder is found.

This function is the default error-handling behavior for a Command.

func ShowRootCommandHelpAndExit added in v3.4.0

func ShowRootCommandHelpAndExit(cmd *Command, exitCode int)

ShowRootCommandHelpAndExit prints the list of subcommands and exits with exit code.

func ShowSubcommandHelpAndExit

func ShowSubcommandHelpAndExit(cmd *Command, exitCode int)

ShowSubcommandHelpAndExit prints help for the given subcommand via ShowSubcommandHelp and exits with exit code.

func ShowVersion(cmd *Command)

ShowVersion prints the version number of the root Command.

ActionFunc is the action to execute when no subcommands are specified

ActionableFlag is an interface that wraps Flag interface and RunAction operation.

AfterFunc is an action that executes after any subcommands are run and have finished. The AfterFunc is run even if Action() panics.

Argument captures a positional argument that can be parsed

type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct {
	Name        string `json:"name"`
	Value       T      `json:"value"`
	Destination *T     `json:"-"`
	UsageText   string `json:"usageText"`
	Config      C      `json:"config"`

}
func (a *ArgumentBase[T, C, VC]) Get() any
type ArgumentsBase[T any, C any, VC ValueCreator[T, C]] struct {
	Name        string `json:"name"`
	Value       T      `json:"value"`
	Destination *[]T   `json:"-"`
	UsageText   string `json:"usageText"`
	Min         int    `json:"minTimes"`
	Max         int    `json:"maxTimes"`
	Config      C      `json:"config"`

}

ArgumentsBase is a base type for slice arguments

func (a *ArgumentsBase[T, C, VC]) Get() any

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.

type BoolConfig struct {
	Count *int
}

BoolConfig defines the configuration for bool flags

type BoolFlag = FlagBase[bool, BoolConfig, boolValue]
type BoolWithInverseFlag struct {
	Name             string                                      `json:"name"`
	Category         string                                      `json:"category"`
	DefaultText      string                                      `json:"defaultText"`
	HideDefault      bool                                        `json:"hideDefault"`
	Usage            string                                      `json:"usage"`
	Sources          ValueSourceChain                            `json:"-"`
	Required         bool                                        `json:"required"`
	Hidden           bool                                        `json:"hidden"`
	Local            bool                                        `json:"local"`
	Value            bool                                        `json:"defaultValue"`
	Destination      *bool                                       `json:"-"`
	Aliases          []string                                    `json:"aliases"`
	TakesFile        bool                                        `json:"takesFileArg"`
	Action           func(context.Context, *Command, bool) error `json:"-"`
	OnlyOnce         bool                                        `json:"onlyOnce"`
	Validator        func(bool) error                            `json:"-"`
	ValidateDefaults bool                                        `json:"validateDefaults"`
	Config           BoolConfig                                  `json:"config"`
	InversePrefix    string                                      `json:"invPrefix"`

}
package main
import (
	"context"
	"fmt"
	cli "github.com/urfave/cli/v3"
)
func main() {
	flagWithInverse := &cli.BoolWithInverseFlag{
		Name: "env",
	}
	cmd := &cli.Command{
		Flags: []cli.Flag{
			flagWithInverse,
		},
		Action: func(_ context.Context, cmd *cli.Command) error {
			if flagWithInverse.IsSet() {
				if cmd.Bool("env") {
					fmt.Println("env is set")
				} else {
					fmt.Println("no-env is set")
				}
			}
			return nil
		},
	}
	_ = cmd.Run(context.Background(), []string{"prog", "--no-env"})
	fmt.Println("flags:", len(flagWithInverse.Names()))
}
Output:
no-env is set
flags: 2

Count returns the number of times this flag has been invoked

GetCategory returns the category of the flag

GetDefaultText returns the default text for this flag

GetEnvVars returns the env vars for this flag

GetUsage returns the usage string for the flag

GetValue returns the flags value as string representation and an empty string if the flag takes no value at all.

func (bif *BoolWithInverseFlag) IsBoolFlag() bool

IsBoolFlag returns whether the flag doesn't need to accept args

func (bif *BoolWithInverseFlag) IsDefaultVisible() bool

IsDefaultVisible returns true if the flag is not hidden, otherwise false

func (bif *BoolWithInverseFlag) IsRequired() bool

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)

func (bif *BoolWithInverseFlag) TakesValue() bool

TypeName is used for stringify/docs. For bool its a no-op

type CategorizableFlag interface {

	GetCategory() string

	SetCategory(string)
}

CategorizableFlag is an interface that allows us to potentially use a flag in a categorized representation.

type Command

type Command struct {

	Name string `json:"name"`

	Aliases []string `json:"aliases"`

	Usage string `json:"usage"`

	UsageText string `json:"usageText"`

	ArgsUsage string `json:"argsUsage"`

	Version string `json:"version"`

	Description string `json:"description"`


	DefaultCommand string `json:"defaultCommand"`

	Category string `json:"category"`

	Commands []*Command `json:"commands"`

	Flags []Flag `json:"flags"`

	HideHelp bool `json:"hideHelp"`


	HideHelpCommand bool `json:"hideHelpCommand"`

	HideVersion bool `json:"hideVersion"`

	EnableShellCompletion bool `json:"-"`

	ShellCompletionCommandName string `json:"-"`

	ShellComplete ShellCompleteFunc `json:"-"`

	ConfigureShellCompletionCommand ConfigureShellCompletionCommand `json:"-"`


	Before BeforeFunc `json:"-"`


	After AfterFunc `json:"-"`

	Action ActionFunc `json:"-"`

	CommandNotFound CommandNotFoundFunc `json:"-"`

	OnUsageError OnUsageErrorFunc `json:"-"`

	InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"`

	Hidden bool `json:"hidden"`
	Authors []any `json:"authors"`

	Copyright string `json:"copyright"`

	Reader io.Reader `json:"-"`

	Writer io.Writer `json:"-"`

	ErrWriter io.Writer `json:"-"`


	ExitErrHandler ExitErrHandlerFunc `json:"-"`

	Metadata map[string]any `json:"metadata"`

	ExtraInfo func() map[string]string `json:"-"`


	CustomRootCommandHelpTemplate string `json:"-"`

	SliceFlagSeparator string `json:"sliceFlagSeparator"`

	DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"`

	MapFlagKeyValueSeparator string `json:"mapFlagKeyValueSeparator"`


	UseShortOptionHandling bool `json:"useShortOptionHandling"`

	Suggest bool `json:"suggest"`


	AllowExtFlags bool `json:"allowExtFlags"`

	SkipFlagParsing bool `json:"skipFlagParsing"`


	CustomHelpTemplate string `json:"-"`

	PrefixMatchCommands bool `json:"prefixMatchCommands"`

	SuggestCommandFunc SuggestCommandFunc `json:"-"`

	MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`

	Arguments []Argument `json:"arguments"`


	ReadArgsFromStdin bool `json:"readArgsFromStdin"`


	StopOnNthArg *int `json:"stopOnNthArg"`
}

Command contains everything needed to run an application that accepts a string slice of arguments such as os.Args. A given Command may contain Flags and sub-commands in Commands.

func (*Command) Args

func (cmd *Command) Args() Args

Args returns the command line arguments associated with the command.

func (*Command) Bool

func (*Command) Count

Count returns the num of occurrences of this flag

func (*Command) FlagNames

FlagNames returns a slice of flag names used by the this command and all of its parent commands.

func (*Command) Float

Float looks up the value of a local FloatFlag, returns 0 if not found

func (*Command) Float32 added in v3.3.0

Float32 looks up the value of a local Float32Flag, returns 0 if not found

func (*Command) Float32Slice added in v3.3.0

Float32Slice looks up the value of a local Float32Slice, returns nil if not found

func (*Command) Float64 added in v3.3.0

Float64 looks up the value of a local Float64Flag, returns 0 if not found

func (*Command) Float64Slice added in v3.3.0

Float64Slice looks up the value of a local Float64SliceFlag, returns nil if not found

func (*Command) FloatArg added in v3.2.0

func (*Command) FloatSlice

FloatSlice looks up the value of a local FloatSliceFlag, returns nil if not found

func (*Command) FullName

FullName returns the full name of the command. Includes parent commands separated by space.

func (*Command) Generic

Generic looks up the value of a local GenericFlag, returns nil if not found

func (*Command) HasName

HasName returns true if Command.Name matches given name

func (*Command) Int

Int looks up the value of a local Int64Flag, returns 0 if not found

func (*Command) Int8 added in v3.2.0

Int8 looks up the value of a local Int8Flag, returns 0 if not found

func (*Command) Int8Arg added in v3.2.0

func (*Command) Int8Args added in v3.2.0

func (*Command) Int8Slice added in v3.2.0

Int8Slice looks up the value of a local Int8SliceFlag, returns nil if not found

func (*Command) Int16 added in v3.2.0

Int16 looks up the value of a local Int16Flag, returns 0 if not found

func (*Command) Int16Arg added in v3.2.0

func (*Command) Int16Slice added in v3.2.0

Int16Slice looks up the value of a local Int16SliceFlag, returns nil if not found

func (*Command) Int32 added in v3.2.0

Int32 looks up the value of a local Int32Flag, returns 0 if not found

func (*Command) Int32Arg added in v3.2.0

func (*Command) Int32Slice added in v3.2.0

Int32Slice looks up the value of a local Int32SliceFlag, returns nil if not found

func (*Command) Int64 added in v3.2.0

Int64 looks up the value of a local Int64Flag, returns 0 if not found

func (*Command) Int64Arg added in v3.2.0

func (*Command) Int64Slice added in v3.2.0

Int64Slice looks up the value of a local Int64SliceFlag, returns nil if not found

func (*Command) IntArg added in v3.2.0

func (*Command) IntArgs added in v3.2.0

func (*Command) IntSlice

IntSlice looks up the value of a local IntSliceFlag, returns nil if not found

func (*Command) IsSet

IsSet determines if the flag was actually set

func (*Command) Lineage

func (cmd *Command) Lineage() []*Command

Lineage returns *this* command and all of its ancestor commands in order from child to parent

func (*Command) LocalFlagNames

func (cmd *Command) LocalFlagNames() []string

LocalFlagNames returns a slice of flag names used in this command.

func (*Command) NArg

func (cmd *Command) NArg() int

NArg returns the number of the command line arguments.

func (*Command) Names

Names returns the names including short names and aliases.

func (*Command) NumFlags

func (cmd *Command) NumFlags() int

NumFlags returns the number of flags set

func (*Command) Path added in v3.10.0

Path returns the path of command names from the root to cmd, inclusive. Each element is a Command.Name. Path traverses upward via parent pointers similar to Lineage. FullName() is equivalent to strings.Join(cmd.Path(), " ").

func (*Command) Root

func (cmd *Command) Root() *Command

Root returns the Command at the root of the graph

func (*Command) Run

Run is the entry point to the command graph. The positional arguments are parsed according to the Flag and Command definitions and the matching Action functions are run.

package main
import (
	"context"
	"fmt"
	"net/mail"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	// Declare a command
	cmd := &cli.Command{
		Name: "greet",
		Flags: []cli.Flag{
			&cli.StringFlag{Name: "name", Value: "pat", Usage: "a name to say"},
		},
		Action: func(_ context.Context, cmd *cli.Command) error {
			fmt.Printf("Hello %[1]v\n", cmd.String("name"))
			return nil
		},
		Authors: []any{
			&mail.Address{Name: "Oliver Allen", Address: "oliver@toyshop.example.com"},
			"gruffalo@soup-world.example.org",
		},
		Version: "v0.13.12",
	}
	// Simulate the command line arguments
	os.Args = []string{"greet", "--name", "Jeremy"}
	if err := cmd.Run(context.Background(), os.Args); err != nil {
		// do something with unhandled errors
		fmt.Fprintf(os.Stderr, "Unhandled error: %[1]v\n", err)
		os.Exit(86)
	}
}
Output:
Hello Jeremy
package main
import (
	"context"
	"fmt"
	"net/mail"
	"os"
	"time"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:        "greet",
		Version:     "0.1.0",
		Description: "This is how we describe greet the app",
		Authors: []any{
			&mail.Address{Name: "Harrison", Address: "harrison@lolwut.example.com"},
			"Oliver Allen  <oliver@toyshop.example.com>",
		},
		Flags: []cli.Flag{
			&cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
		},
		Arguments: cli.AnyArguments,
		Commands: []*cli.Command{
			{
				Name:        "describeit",
				Aliases:     []string{"d"},
				Usage:       "use it to see a description",
				Description: "This is how we describe describeit the function",
				ArgsUsage:   "[arguments...]",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("i like to describe things")
					return nil
				},
			},
		},
	}
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	// Simulate the command line arguments
	os.Args = []string{"greet", "help"}
	_ = cmd.Run(ctx, os.Args)
}
Output:
NAME:
   greet - A new cli application
USAGE:
   greet [global options] [command [command options]] [arguments...]
VERSION:
   0.1.0
DESCRIPTION:
   This is how we describe greet the app
AUTHORS:
   "Harrison" <harrison@lolwut.example.com>
   Oliver Allen  <oliver@toyshop.example.com>
COMMANDS:
   describeit, d  use it to see a description
   help, h        Shows a list of commands or help for one command
GLOBAL OPTIONS:
   --name string  a name to say (default: "bob")
   --help, -h     show help
   --version, -v  print the version
package main
import (
	"context"
	"fmt"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name: "greet",
		Flags: []cli.Flag{
			&cli.StringFlag{Name: "name", Value: "pat", Usage: "a name to say"},
		},
		Action: func(_ context.Context, cmd *cli.Command) error {
			fmt.Fprintf(cmd.Root().Writer, "hello to %[1]q\n", cmd.String("name"))
			return nil
		},
		Commands: []*cli.Command{
			{
				Name:        "describeit",
				Aliases:     []string{"d"},
				Usage:       "use it to see a description",
				Description: "This is how we describe describeit the function",
				ArgsUsage:   "[arguments...]",
				Action: func(context.Context, *cli.Command) error {
					fmt.Println("i like to describe things")
					return nil
				},
			},
		},
	}
	// Simulate the command line arguments
	os.Args = []string{"greet", "h", "describeit"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
NAME:
   greet describeit - use it to see a description
USAGE:
   greet describeit [options] [arguments...]
DESCRIPTION:
   This is how we describe describeit the function
OPTIONS:
   --help, -h  show help
GLOBAL OPTIONS:
   --name string  a name to say (default: "pat")
package main
import (
	"context"
	"fmt"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name: "multi_values",
		Flags: []cli.Flag{
			&cli.StringMapFlag{Name: "stringMap"},
		},
		HideHelp: true,
		Action: func(ctx context.Context, cmd *cli.Command) error {
			for i, v := range cmd.FlagNames() {
				fmt.Printf("%d-%s %#v\n", i, v, cmd.StringMap(v))
			}
			fmt.Printf("notfound %#v\n", cmd.StringMap("notfound"))
			err := ctx.Err()
			fmt.Println("error:", err)
			return err
		},
	}
	// Simulate command line arguments
	os.Args = []string{
		"multi_values",
		"--stringMap", "parsed1=parsed two", "--stringMap", "parsed3=",
	}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
0-stringMap map[string]string{"parsed1":"parsed two", "parsed3":""}
notfound map[string]string(nil)
error: <nil>
package main
import (
	"context"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{Name: "greet"}
	// Simulate the command line arguments
	os.Args = []string{"greet"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
NAME:
   greet - A new cli application
USAGE:
   greet [global options]
GLOBAL OPTIONS:
   --help, -h  show help
package main
import (
	"context"
	"fmt"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Commands: []*cli.Command{
			{
				Name:        "describeit",
				Aliases:     []string{"d"},
				Usage:       "use it to see a description",
				Description: "This is how we describe describeit the function",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("i like to describe things")
					return nil
				},
			}, {
				Name:        "next",
				Usage:       "next example",
				Description: "more stuff to see when generating shell completion",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("the next example")
					return nil
				},
			},
		},
	}
	// Simulate a bash environment and command line arguments
	os.Args = []string{"greet", "--generate-shell-completion"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
describeit:use it to see a description
next:next example
help:Shows a list of commands or help for one command
package main
import (
	"context"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Flags: []cli.Flag{
			&cli.Int64Flag{
				Name:    "other",
				Aliases: []string{"o"},
			},
			&cli.StringFlag{
				Name:    "xyz",
				Aliases: []string{"x"},
			},
			&cli.StringFlag{
				Name: "some-flag,s",
			},
			&cli.StringFlag{
				Name: "similar-flag",
			},
		},
	}
	// Simulate a bash environment and command line arguments
	os.Args = []string{"greet", "--s", "--generate-shell-completion"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
--some-flag
--similar-flag
package main
import (
	"context"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Flags: []cli.Flag{
			&cli.Int64Flag{
				Name:    "int-flag",
				Aliases: []string{"i"},
			},
			&cli.StringFlag{
				Name:    "string",
				Aliases: []string{"s"},
			},
			&cli.StringFlag{
				Name: "string-flag-2",
			},
			&cli.StringFlag{
				Name: "similar-flag",
			},
			&cli.StringFlag{
				Name: "some-flag",
			},
		},
	}
	// Simulate a bash environment and command line arguments
	os.Args = []string{"greet", "--st", "--generate-shell-completion"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
--string
--string-flag-2
package main
import (
	"context"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Flags: []cli.Flag{
			&cli.Int64Flag{
				Name:    "other",
				Aliases: []string{"o"},
			},
			&cli.StringFlag{
				Name:    "xyz",
				Aliases: []string{"x"},
			},
		},
	}
	// Simulate a bash environment and command line arguments
	os.Args = []string{"greet", "-", "--generate-shell-completion"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
--other
--xyz
--help:show help
package main
import (
	"context"
	"fmt"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Commands: []*cli.Command{
			{
				Name:        "describeit",
				Aliases:     []string{"d"},
				Usage:       "use it to see a description",
				Description: "This is how we describe describeit the function",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("i like to describe things")
					return nil
				},
			}, {
				Name:        "next",
				Usage:       "next example",
				Description: "more stuff to see when generating bash completion",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("the next example")
					return nil
				},
			},
		},
	}
	// Simulate a fish environment and command line arguments
	os.Args = []string{"greet", "--generate-shell-completion"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
describeit:use it to see a description
next:next example
help:Shows a list of commands or help for one command
package main
import (
	"context"
	"fmt"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Commands: []*cli.Command{
			{
				Name:        "describeit",
				Aliases:     []string{"d"},
				Usage:       "use it to see a description",
				Description: "This is how we describe describeit the function",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("i like to describe things")
					return nil
				},
			}, {
				Name:        "next",
				Usage:       "next example",
				Description: "more stuff to see when generating bash completion",
				Action: func(context.Context, *cli.Command) error {
					fmt.Printf("the next example")
					return nil
				},
			},
		},
	}
	// Simulate a zsh environment and command line arguments
	os.Args = []string{"greet", "--generate-shell-completion"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
describeit:use it to see a description
next:next example
help:Shows a list of commands or help for one command
package main
import (
	"context"
	"fmt"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name: "multi_values",
		Flags: []cli.Flag{
			&cli.StringSliceFlag{Name: "stringSlice"},
			&cli.FloatSliceFlag{Name: "float64Slice"},
			&cli.Int64SliceFlag{Name: "intSlice"},
		},
		HideHelp: true,
		Action: func(ctx context.Context, cmd *cli.Command) error {
			for i, v := range cmd.FlagNames() {
				fmt.Printf("%d-%s %#v\n", i, v, cmd.Value(v))
			}
			err := ctx.Err()
			fmt.Println("error:", err)
			return err
		},
	}
	// Simulate command line arguments
	os.Args = []string{
		"multi_values",
		"--stringSlice", "parsed1,parsed2", "--stringSlice", "parsed3,parsed4",
		"--float64Slice", "13.3,14.4", "--float64Slice", "15.5,16.6",
		"--intSlice", "13,14", "--intSlice", "15,16",
	}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
0-stringSlice []string{"parsed1", "parsed2", "parsed3", "parsed4"}
1-float64Slice []float64{13.3, 14.4, 15.5, 16.6}
2-intSlice []int64{13, 14, 15, 16}
error: <nil>
package main
import (
	"context"
	"fmt"
	"os"
	"time"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name: "say",
		Commands: []*cli.Command{
			{
				Name:        "hello",
				Aliases:     []string{"hi"},
				Usage:       "use it to see a description",
				Description: "This is how we describe hello the function",
				Commands: []*cli.Command{
					{
						Name:        "english",
						Aliases:     []string{"en"},
						Usage:       "sends a greeting in english",
						Description: "greets someone in english",
						Flags: []cli.Flag{
							&cli.StringFlag{
								Name:  "name",
								Value: "Bob",
								Usage: "Name of the person to greet",
							},
						},
						Action: func(_ context.Context, cmd *cli.Command) error {
							fmt.Println("Hello,", cmd.String("name"))
							return nil
						},
					},
				},
			},
		},
	}
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	// Simulate the command line arguments
	os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
	_ = cmd.Run(ctx, os.Args)
}
Output:
Hello, Jeremy
package main
import (
	"context"
	"os"
	cli "github.com/urfave/cli/v3"
)
func main() {
	cmd := &cli.Command{
		Name: "greet",
		Commands: []*cli.Command{
			{
				Name:        "describeit",
				Aliases:     []string{"d"},
				Usage:       "use it to see a description",
				ArgsUsage:   "[arguments...]",
				Description: "This is how we describe describeit the function",
			},
		},
	}
	// Simulate the command line arguments
	os.Args = []string{"greet", "describeit"}
	_ = cmd.Run(context.Background(), os.Args)
}
Output:
NAME:
   greet describeit - use it to see a description
USAGE:
   greet describeit [options] [arguments...]
DESCRIPTION:
   This is how we describe describeit the function
OPTIONS:
   --help, -h  show help

func (*Command) Set

Set sets a context flag to a value.

func (*Command) StringMap

StringMap looks up the value of a local StringMapFlag, returns nil if not found

func (*Command) StringSlice

StringSlice looks up the value of a local StringSliceFlag, returns nil if not found

func (*Command) Timestamp

Timestamp gets the timestamp from a flag name

func (*Command) ToFishCompletion

ToFishCompletion creates a fish completion string for the `*Command` The function errors if either parsing or writing of the string fails.

func (*Command) Uint

Uint looks up the value of a local Uint64Flag, returns 0 if not found

func (*Command) Uint8 added in v3.2.0

Uint8 looks up the value of a local Uint8Flag, returns 0 if not found

func (*Command) Uint8Arg added in v3.2.0

func (*Command) Uint8Slice added in v3.2.0

Uint8Slice looks up the value of a local Uint8SliceFlag, returns nil if not found

func (*Command) Uint16 added in v3.2.0

Uint16 looks up the value of a local Uint16Flag, returns 0 if not found

func (*Command) Uint16Slice added in v3.2.0

Uint16Slice looks up the value of a local Uint16SliceFlag, returns nil if not found

func (*Command) Uint32 added in v3.2.0

Uint32 looks up the value of a local Uint32Flag, returns 0 if not found

func (*Command) Uint32Slice added in v3.2.0

Uint32Slice looks up the value of a local Uint32SliceFlag, returns nil if not found

func (*Command) Uint64 added in v3.2.0

Uint64 looks up the value of a local Uint64Flag, returns 0 if not found

func (*Command) Uint64Slice added in v3.2.0

Uint64Slice looks up the value of a local Uint64SliceFlag, returns nil if not found

func (*Command) UintArg added in v3.2.0

func (*Command) UintArgs added in v3.2.0

func (*Command) UintSlice

UintSlice looks up the value of a local UintSliceFlag, returns nil if not found

func (*Command) Value

Value returns the value of the flag corresponding to `name`

func (*Command) VisibleCategories

func (cmd *Command) VisibleCategories() []CommandCategory

VisibleCategories returns a slice of categories and commands that are Hidden=false

func (*Command) VisibleCommands

func (cmd *Command) VisibleCommands() []*Command

VisibleCommands returns a slice of the Commands with Hidden=false

func (*Command) VisibleFlagCategories

func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory

VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain

func (*Command) VisibleFlags

func (cmd *Command) VisibleFlags() []Flag

VisibleFlags returns a slice of the Flags with Hidden=false

func (*Command) VisiblePersistentFlags

func (cmd *Command) VisiblePersistentFlags() []Flag

VisiblePersistentFlags returns a slice of LocalFlag with Persistent=true and Hidden=false.

func (*Command) Walk added in v3.10.0

Walk visits cmd and every descendant. If fn returns a non-nil error, the walk terminates and the error is returned to the caller.

type CommandCategories

type CommandCategories interface {

	AddCommand(category string, command *Command)

	Categories() []CommandCategory
}

CommandCategories interface allows for category manipulation

type CommandCategory

type CommandCategory interface {

	Name() string

	VisibleCommands() []*Command
}

CommandCategory is a category containing commands.

type ConfigureShellCompletionCommand added in v3.3.0

type ConfigureShellCompletionCommand func(*Command)

ConfigureShellCompletionCommand is a function to configure a shell completion command

type Countable interface {
	Count() int
}

Countable is an interface to enable detection of flag values which support repetitive flags

DocGenerationFlag is an interface that allows documentation generation for the flag

type DocGenerationMultiValueFlag interface {
	DocGenerationFlag

	IsMultiValueFlag() bool
}

DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags.

type EnvValueSource interface {
	IsFromEnv() bool
	Key() string
}

EnvValueSource is to specifically detect env sources when printing help text

type ErrorFormatter interface {
	Format(s fmt.State, verb rune)
}

ErrorFormatter is the interface that will suitably format the error output

type ExitCoder interface {
	error
	ExitCode() int
}

ExitCoder is the interface checked by `Command` for a custom exit code.

func Exit(message any, exitCode int) ExitCoder

Exit wraps a message and exit code into an error, which by default is handled with a call to os.Exit during default error handling.

This is the simplest way to trigger a non-zero exit code for a Command without having to call os.Exit manually. During testing, this behavior can be avoided by overriding the ExitErrHandler function on a Command or the package-global OsExiter function.

type ExitErrHandlerFunc

ExitErrHandlerFunc is executed if provided in order to handle exitError values returned by Actions and Before/After functions.

Flag is a common interface related to parsing flags in cli. For more advanced flag parsing techniques, it is recommended that this interface be implemented.

var GenerateShellCompletionFlag Flag = &BoolFlag{
	Name:   "generate-shell-completion",
	Hidden: true,
}

GenerateShellCompletionFlag enables shell completion

var HelpFlag Flag = &BoolFlag{
	Name:        "help",
	Aliases:     []string{"h"},
	Usage:       "show help",
	HideDefault: true,
	Local:       true,
}

HelpFlag prints the help for all commands and subcommands. Set to nil to disable the flag. The subcommand will still be added unless HideHelp or HideHelpCommand is set to true.

var VersionFlag Flag = &BoolFlag{
	Name:        "version",
	Aliases:     []string{"v"},
	Usage:       "print the version",
	HideDefault: true,
	Local:       true,
}

VersionFlag prints the version for the application

type FlagBase[T any, C any, VC ValueCreator[T, C]] struct {
	Name             string                                   `json:"name"`
	Category         string                                   `json:"category"`
	DefaultText      string                                   `json:"defaultText"`
	HideDefault      bool                                     `json:"hideDefault"`
	Usage            string                                   `json:"usage"`
	Sources          ValueSourceChain                         `json:"-"`
	Required         bool                                     `json:"required"`
	Hidden           bool                                     `json:"hidden"`
	Local            bool                                     `json:"local"`
	Value            T                                        `json:"defaultValue"`
	Destination      *T                                       `json:"-"`
	Aliases          []string                                 `json:"aliases"`
	TakesFile        bool                                     `json:"takesFileArg"`
	Action           func(context.Context, *Command, T) error `json:"-"`
	Config           C                                        `json:"config"`
	OnlyOnce         bool                                     `json:"onlyOnce"`
	Validator        func(T) error                            `json:"-"`
	ValidateDefaults bool                                     `json:"validateDefaults"`

}

FlagBase [T,C,VC] is a generic flag base which can be used as a boilerplate to implement the most common interfaces used by urfave/cli.

T specifies the type
C specifies the configuration required(if any for that flag type)
VC specifies the value creator which creates the flag.Value emulation
func (f *FlagBase[T, C, VC]) Count() int

Count returns the number of times this flag has been invoked

func (f *FlagBase[T, C, V]) Get() any
func (f *FlagBase[T, C, V]) GetCategory() string

GetCategory returns the category of the flag

func (f *FlagBase[T, C, V]) GetDefaultText() string

GetDefaultText returns the default text for this flag

func (f *FlagBase[T, C, V]) GetEnvVars() []string

GetEnvVars returns the env vars for this flag

func (f *FlagBase[T, C, V]) GetUsage() string

GetUsage returns the usage string for the flag

func (f *FlagBase[T, C, V]) GetValue() string

GetValue returns the flags value as string representation and an empty string if the flag takes no value at all.

func (f *FlagBase[T, C, VC]) IsBoolFlag() bool

IsBoolFlag returns whether the flag doesn't need to accept args

func (f *FlagBase[T, C, V]) IsDefaultVisible() bool

IsDefaultVisible returns true if the flag is not hidden, otherwise false

func (f *FlagBase[T, C, VC]) IsLocal() bool

IsLocal returns false if flag needs to be persistent across subcommands

func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool

IsMultiValueFlag returns true if the value type T can take multiple values from cmd line. This is true for slice and map type flags

func (f *FlagBase[T, C, V]) IsRequired() bool

IsRequired returns whether or not the flag is required

func (f *FlagBase[T, C, V]) IsSet() bool

IsSet returns whether or not the flag has been set through env or file

func (f *FlagBase[T, C, V]) IsVisible() bool

IsVisible returns true if the flag is not hidden, otherwise false

func (f *FlagBase[T, C, V]) Names() []string

Names returns the names of the flag

func (f *FlagBase[T, C, V]) PostParse() error

PostParse populates the flag given the flag set and environment

func (f *FlagBase[T, C, V]) PreParse() error

RunAction executes flag action if set

func (f *FlagBase[T, C, V]) SchemaItemsType() string

SchemaItemsType returns the JSON Schema element type for slice flags.

func (f *FlagBase[T, C, V]) SchemaType() string

SchemaType returns the JSON Schema type for the flag's value type.

Set applies given value from string

func (f *FlagBase[T, C, V]) SetCategory(c string)
func (f *FlagBase[T, C, V]) String() string

String returns a readable representation of this value (for usage defaults)

func (f *FlagBase[T, C, V]) TakesValue() bool

TakesValue returns true if the flag takes a value, otherwise false

func (f *FlagBase[T, C, V]) TypeName() string

TypeName returns the type of the flag.

type FlagCategories interface {

	AddFlag(category string, fl Flag)

	VisibleCategories() []VisibleFlagCategory
}

FlagCategories interface allows for category manipulation

FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help with the environment variable details.

var FlagEnvHinter FlagEnvHintFunc = withEnvHint

FlagEnvHinter annotates flag help message with the environment variable details. This is used by the default FlagStringer.

FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help with the file path details.

var FlagFileHinter FlagFileHintFunc = withFileHint

FlagFileHinter annotates flag help message with the environment variable details. This is used by the default FlagStringer.

FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix text for a flag's full name.

var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames

FlagNamePrefixer converts a full flag name and its placeholder into the help message flag prefix. This is used by the default FlagStringer.

type FlagStringFunc func(Flag) string

FlagStringFunc is used by the help generation to display a flag, which is expected to be a single line.

var FlagStringer FlagStringFunc = stringifyFlag

FlagStringer converts a flag definition to a string. This is used by help to display a flag.

FlagsByName is a slice of Flag.

func (f FlagsByName) Swap(i, j int)
type GenericFlag = FlagBase[Value, NoConfig, genericValue]

Prints help for the Command with custom template function.

HelpPrinterCustom is a function that writes the help output. It is used as the default implementation of HelpPrinter, and may be called directly if the ExtraInfo field is set on a Command.

In the default implementation, if the customFuncs argument contains a "wrapAt" key, which is a function which takes no arguments and returns an int, this int value will be used to produce a "wrap" function used by the default template to wrap long lines.

HelpPrinterFunc prints help for the Command.

var HelpPrinter HelpPrinterFunc = DefaultPrintHelp

HelpPrinter is a function that writes the help output. If not set explicitly, this calls HelpPrinterCustom using only the default template functions.

If custom logic for printing help is required, this function can be overridden. If the ExtraInfo field is defined on a Command, this function should not be modified, as HelpPrinterCustom will be used directly in order to capture the extra information.

type IntSliceFlag = FlagBase[[]int, IntegerConfig, IntSlice]
type IntegerConfig struct {
	Base int
}

IntegerConfig is the configuration for all integer type flags

InvalidFlagAccessFunc is executed when an invalid flag is accessed from the context.

type LocalFlag interface {
	IsLocal() bool
}

LocalFlag is an interface to enable detection of flags which are local to current command

type MapBase[T any, C any, VC ValueCreator[T, C]] struct {
}

MapBase wraps map[string]T to satisfy flag.Value

func NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC]

NewMapBase makes a *MapBase with default values

func (i MapBase[T, C, VC]) Create(val map[string]T, p *map[string]T, c C) Value
func (i *MapBase[T, C, VC]) Get() any

Get returns the mapping of values set by this flag

func (i *MapBase[T, C, VC]) Serialize() string

Serialize allows MapBase to fulfill Serializer

Set parses the value and appends it to the list of values

func (i *MapBase[T, C, VC]) String() string

String returns a readable representation of this value (for usage defaults)

func (i *MapBase[T, C, VC]) Value() map[string]T

Value returns the mapping of values set by this flag

MapSource is a source which can be used to look up a value based on a key typically for use with a cli.Flag

type MultiError interface {
	error
	Errors() []error
}

MultiError is an error that wraps multiple errors.

type MutuallyExclusiveFlags struct {

	Flags [][]Flag

	Required bool

	Category string
}

MutuallyExclusiveFlags defines a mutually exclusive flag group Multiple option paths can be provided out of which only one can be defined on cmdline So for example [ --foo | [ --bar something --darth somethingelse ] ]

type NoConfig struct{}

NoConfig is for flags which dont need a custom configuration

OnUsageErrorFunc is executed if a usage error occurs. This is useful for displaying customized usage error messages. This function is able to replace the original error messages. If this function is not set, the "Incorrect usage" is displayed and the execution is interrupted.

type RequiredFlag interface {

	IsRequired() bool
}

RequiredFlag is an interface that allows us to mark flags as required it allows flags required flags to be backwards compatible with the Flag interface

type SchemaItemsTyper interface {


	SchemaItemsType() string
}

SchemaItemsTyper is an optional interface for multi-value flags that can report the JSON Schema type of their elements.

type SchemaTyper interface {


	SchemaType() string
}

SchemaTyper is an optional interface for flags that can report their JSON Schema type for programmatic introspection.

type Serializer interface {
	Serialize() string
}

Serializer is used to circumvent the limitations of flag.FlagSet.Set

ShellCompleteFunc is an action to execute when the shell completion flag is set

type SliceBase[T any, C any, VC ValueCreator[T, C]] struct {
}

SliceBase wraps []T to satisfy flag.Value

func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC]

NewSliceBase makes a *SliceBase with default values

func (i SliceBase[T, C, VC]) Create(val []T, p *[]T, c C) Value
func (i *SliceBase[T, C, VC]) Get() any

Get returns the slice of values set by this flag

func (i *SliceBase[T, C, VC]) Serialize() string

Serialize allows SliceBase to fulfill Serializer

Set parses the value and appends it to the list of values

func (i *SliceBase[T, C, VC]) String() string

String returns a readable representation of this value (for usage defaults)

func (i SliceBase[T, C, VC]) ToString(t []T) string
func (i *SliceBase[T, C, VC]) Value() []T

Value returns the slice of values set by this flag

type StringConfig struct {

	TrimSpace bool
}

StringConfig defines the configuration for string flags

type StringFlag = FlagBase[string, StringConfig, stringValue]
type StringMap = MapBase[string, StringConfig, stringValue]
type StringSlice = SliceBase[string, StringConfig, stringValue]

TimestampConfig defines the config for timestamp flags

Value represents a value as used by cli. For now it implements the golang flag.Value interface

type ValueCreator[T any, C any] interface {
	Create(T, *T, C) Value
	ToString(T) string
}

ValueCreator is responsible for creating a flag.Value emulation as well as custom formatting

T specifies the type
C specifies the config for the type

ValueSource is a source which can be used to look up a value, typically for use with a cli.Flag

func NewMapValueSource(key string, ms MapSource) ValueSource
type ValueSourceChain struct {
	Chain []ValueSource
}

ValueSourceChain contains an ordered series of ValueSource that allows for lookup where the first ValueSource to resolve is returned

EnvVars is a helper function to encapsulate a number of envVarValueSource together as a ValueSourceChain

Files is a helper function to encapsulate a number of fileValueSource together as a ValueSourceChain

func NewValueSourceChain(src ...ValueSource) ValueSourceChain
func (vsc *ValueSourceChain) Append(other ValueSourceChain)
type VisibleFlag interface {

	IsVisible() bool
}

VisibleFlag is an interface that allows to check if a flag is visible

type VisibleFlagCategory interface {

	Name() string

	Flags() []Flag
}

VisibleFlagCategory is a category containing flags.

Read the original on pkg.go.dev ↗