cli

package module
v3.0.0-beta1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2024 License: MIT Imports: 23 Imported by: 342

README

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.

Documentation

Overview

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

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	SuggestFlag               SuggestFlagFunc    = suggestFlag
	SuggestCommand            SuggestCommandFunc = suggestCommand
	SuggestDidYouMeanTemplate string             = suggestDidYouMeanTemplate
)
View Source
var AnyArguments = []Argument{
	&StringArg{
		Max: -1,
	},
}

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

View Source
var CommandHelpTemplate = `` /* 477-byte string literal not displayed */

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.

View Source
var DefaultInverseBoolPrefix = "no-"
View Source
var ErrWriter io.Writer = os.Stderr

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

View Source
var FishCompletionTemplate = `` /* 366-byte string literal not displayed */
View Source
var HelpPrinter helpPrinter = printHelp

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 an App, this function should not be modified, as HelpPrinterCustom will be used directly in order to capture the extra information.

View Source
var HelpPrinterCustom helpPrinterCustom = printHelpCustom

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 an App.

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.

View Source
var NewFloatSlice = NewSliceBase[float64, NoConfig, floatValue]
View Source
var NewIntSlice = NewSliceBase[int64, IntegerConfig, intValue]
View Source
var NewStringMap = NewMapBase[string, StringConfig, stringValue]
View Source
var NewStringSlice = NewSliceBase[string, StringConfig, stringValue]
View Source
var NewUintSlice = NewSliceBase[uint64, IntegerConfig, uintValue]
View Source
var OsExiter = os.Exit

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

View Source
var RootCommandHelpTemplate = `` /* 873-byte string literal not displayed */

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.

View Source
var SubcommandHelpTemplate = `` /* 638-byte string literal not displayed */

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 VersionPrinter = printVersion

VersionPrinter prints the version for the App

Functions

func DefaultAppComplete

func DefaultAppComplete(ctx context.Context, cmd *Command)

DefaultAppComplete prints the list of subcommands as the default app completion method

func DefaultCompleteWithFlags

func DefaultCompleteWithFlags(ctx context.Context, cmd *Command)

func FlagNames

func FlagNames(name string, aliases []string) []string

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 an App.

func ShowAppHelp

func ShowAppHelp(cmd *Command) error

ShowAppHelp is an action that displays the help.

func ShowAppHelpAndExit

func ShowAppHelpAndExit(cmd *Command, exitCode int)

ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code.

func ShowCommandHelp

func ShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error

ShowCommandHelp prints help for the given command

func ShowCommandHelpAndExit

func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int)

ShowCommandHelpAndExit - exits with code after showing help

func ShowSubcommandHelp

func ShowSubcommandHelp(cmd *Command) error

ShowSubcommandHelp prints help for the given subcommand

func ShowSubcommandHelpAndExit

func ShowSubcommandHelpAndExit(cmd *Command, exitCode int)

ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code.

func ShowVersion

func ShowVersion(cmd *Command)

ShowVersion prints the version number of the App

Types

type ActionFunc

type ActionFunc func(context.Context, *Command) error

ActionFunc is the action to execute when no subcommands are specified

type ActionableFlag

type ActionableFlag interface {
	RunAction(context.Context, *Command) error
}

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

type AfterFunc

type AfterFunc func(context.Context, *Command) error

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

type Args

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
}

type Argument

type Argument interface {
	Parse([]string) ([]string, error)
	Usage() string
}

type ArgumentBase

type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct {
	Name        string `json:"name"`      // the name of this argument
	Value       T      `json:"value"`     // the default value of this argument
	Destination *T     `json:"-"`         // the destination point for this argument
	Values      *[]T   `json:"-"`         // all the values of this argument, only if multiple are supported
	UsageText   string `json:"usageText"` // the usage text to show
	Min         int    `json:"minTimes"`  // the min num of occurrences of this argument
	Max         int    `json:"maxTimes"`  // the max num of occurrences of this argument, set to -1 for unlimited
	Config      C      `json:"config"`    // config for this argument similar to Flag Config
}

func (*ArgumentBase[T, C, VC]) Parse

func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error)

func (*ArgumentBase[T, C, VC]) Usage

func (a *ArgumentBase[T, C, VC]) Usage() string

type BeforeFunc

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.

type BoolConfig

type BoolConfig struct {
	Count *int
}

BoolConfig defines the configuration for bool flags

type BoolFlag

type BoolFlag = FlagBase[bool, BoolConfig, boolValue]

type BoolWithInverseFlag

type BoolWithInverseFlag struct {
	// The BoolFlag which the positive and negative flags are generated from
	*BoolFlag

	// The prefix used to indicate a negative value
	// Default: `env` becomes `no-env`
	InversePrefix string
	// contains filtered or unexported fields
}
Example
package main

import (
	"context"
	"fmt"

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

func main() {
	flagWithInverse := &cli.BoolWithInverseFlag{
		BoolFlag: &cli.BoolFlag{
			Name: "env",
		},
	}

	cmd := &cli.Command{
		Flags: []cli.Flag{
			flagWithInverse,
		},
		Action: func(_ context.Context, cmd *cli.Command) error {
			if flagWithInverse.IsSet() {
				if flagWithInverse.Value() {
					fmt.Println("env is set")
				} else {
					fmt.Println("no-env is set")
				}
			}

			return nil
		},
	}

	_ = cmd.Run(context.Background(), []string{"prog", "--no-env"})
	_ = cmd.Run(context.Background(), []string{"prog", "--env"})

	fmt.Println("flags:", len(flagWithInverse.Flags()))

}
Output:

no-env is set
env is set
flags: 2

func (*BoolWithInverseFlag) Apply

func (parent *BoolWithInverseFlag) Apply(set *flag.FlagSet) error

func (*BoolWithInverseFlag) Flags

func (parent *BoolWithInverseFlag) Flags() []Flag

func (*BoolWithInverseFlag) IsSet

func (parent *BoolWithInverseFlag) IsSet() bool

func (*BoolWithInverseFlag) Names

func (parent *BoolWithInverseFlag) Names() []string

func (*BoolWithInverseFlag) RunAction

func (parent *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error

func (*BoolWithInverseFlag) String

func (parent *BoolWithInverseFlag) String() string

String implements the standard Stringer interface.

Example for BoolFlag{Name: "env"} --[no-]env (default: false)

func (*BoolWithInverseFlag) Value

func (parent *BoolWithInverseFlag) Value() bool

type CategorizableFlag

type CategorizableFlag interface {
	// Returns the category of the flag
	GetCategory() string

	// Sets the category of the flag
	SetCategory(string)
}

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

type Command

type Command struct {
	// The name of the command
	Name string `json:"name"`
	// A list of aliases for the command
	Aliases []string `json:"aliases"`
	// A short description of the usage of this command
	Usage string `json:"usage"`
	// Text to override the USAGE section of help
	UsageText string `json:"usageText"`
	// A short description of the arguments of this command
	ArgsUsage string `json:"argsUsage"`
	// Version of the command
	Version string `json:"version"`
	// Longer explanation of how the command works
	Description string `json:"description"`
	// DefaultCommand is the (optional) name of a command
	// to run if no command names are passed as CLI arguments.
	DefaultCommand string `json:"defaultCommand"`
	// The category the command is part of
	Category string `json:"category"`
	// List of child commands
	Commands []*Command `json:"commands"`
	// List of flags to parse
	Flags []Flag `json:"flags"`
	// Boolean to hide built-in help command and help flag
	HideHelp bool `json:"hideHelp"`
	// Ignored if HideHelp is true.
	HideHelpCommand bool `json:"hideHelpCommand"`
	// Boolean to hide built-in version flag and the VERSION section of help
	HideVersion bool `json:"hideVersion"`
	// Boolean to enable shell completion commands
	EnableShellCompletion bool `json:"-"`
	// Shell Completion generation command name
	ShellCompletionCommandName string `json:"-"`
	// The function to call when checking for shell command completions
	ShellComplete ShellCompleteFunc `json:"-"`
	// An action to execute before any subcommands are run, but after the context is ready
	// If a non-nil error is returned, no subcommands are run
	Before BeforeFunc `json:"-"`
	// An action to execute after any subcommands are run, but after the subcommand has finished
	// It is run even if Action() panics
	After AfterFunc `json:"-"`
	// The function to call when this command is invoked
	Action ActionFunc `json:"-"`
	// Execute this function if the proper command cannot be found
	CommandNotFound CommandNotFoundFunc `json:"-"`
	// Execute this function if a usage error occurs.
	OnUsageError OnUsageErrorFunc `json:"-"`
	// Execute this function when an invalid flag is accessed from the context
	InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"`
	// Boolean to hide this command from help or completion
	Hidden bool `json:"hidden"`
	// List of all authors who contributed (string or fmt.Stringer)
	// TODO: ~string | fmt.Stringer when interface unions are available
	Authors []any `json:"authors"`
	// Copyright of the binary if any
	Copyright string `json:"copyright"`
	// Reader reader to write input to (useful for tests)
	Reader io.Reader `json:"-"`
	// Writer writer to write output to
	Writer io.Writer `json:"-"`
	// ErrWriter writes error output
	ErrWriter io.Writer `json:"-"`
	// ExitErrHandler processes any error encountered while running an App before
	// it is returned to the caller. If no function is provided, HandleExitCoder
	// is used as the default behavior.
	ExitErrHandler ExitErrHandlerFunc `json:"-"`
	// Other custom info
	Metadata map[string]interface{} `json:"metadata"`
	// Carries a function which returns app specific info.
	ExtraInfo func() map[string]string `json:"-"`
	// CustomRootCommandHelpTemplate the text template for app help topic.
	// cli.go uses text/template to render templates. You can
	// render custom help text by setting this variable.
	CustomRootCommandHelpTemplate string `json:"-"`
	// SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
	SliceFlagSeparator string `json:"sliceFlagSeparator"`
	// DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
	DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"`
	// Boolean to enable short-option handling so user can combine several
	// single-character bool arguments into one
	// i.e. foobar -o -v -> foobar -ov
	UseShortOptionHandling bool `json:"useShortOptionHandling"`
	// Enable suggestions for commands and flags
	Suggest bool `json:"suggest"`
	// Allows global flags set by libraries which use flag.XXXVar(...) directly
	// to be parsed through this library
	AllowExtFlags bool `json:"allowExtFlags"`
	// Treat all flags as normal arguments if true
	SkipFlagParsing bool `json:"skipFlagParsing"`
	// CustomHelpTemplate 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.
	CustomHelpTemplate string `json:"-"`
	// Use longest prefix match for commands
	PrefixMatchCommands bool `json:"prefixMatchCommands"`
	// Custom suggest command for matching
	SuggestCommandFunc SuggestCommandFunc `json:"-"`
	// Flag exclusion group
	MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`
	// Arguments to parse for this command
	Arguments []Argument `json:"arguments"`
	// Whether to read arguments from stdin
	// applicable to root command only
	ReadArgsFromStdin bool `json:"readArgsFromStdin"`
	// contains filtered or unexported fields
}

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 (cmd *Command) Bool(name string) bool

func (*Command) Command

func (cmd *Command) Command(name string) *Command

func (*Command) Count

func (cmd *Command) Count(name string) int

Count returns the num of occurrences of this flag

func (*Command) Duration

func (cmd *Command) Duration(name string) time.Duration

func (*Command) FlagNames

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

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

func (*Command) Float

func (cmd *Command) Float(name string) float64

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

func (*Command) FloatSlice

func (cmd *Command) FloatSlice(name string) []float64

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

func (*Command) FullName

func (cmd *Command) FullName() string

FullName returns the full name of the command. For commands with parents this ensures that the parent commands are part of the command path.

func (*Command) Generic

func (cmd *Command) Generic(name string) Value

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

func (*Command) HasName

func (cmd *Command) HasName(name string) bool

HasName returns true if Command.Name matches given name

func (*Command) Int

func (cmd *Command) Int(name string) int64

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

func (*Command) IntSlice

func (cmd *Command) IntSlice(name string) []int64

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

func (*Command) IsSet

func (cmd *Command) IsSet(name string) bool

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

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

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

func (cmd *Command) Root() *Command

Root returns the Command at the root of the graph

func (*Command) Run

func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error)

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.

Example
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
Example (AppHelp)
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 value   a name to say (default: "bob")
   --help, -h     show help
   --version, -v  print the version
Example (CommandHelp)
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 [arguments...]

DESCRIPTION:
   This is how we describe describeit the function

OPTIONS:
   --help, -h  show help
Example (MapValues)
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>
Example (NoAction)
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
Example (ShellComplete_bash)
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.Setenv("SHELL", "bash")
	os.Args = []string{"greet", "--generate-shell-completion"}

	_ = cmd.Run(context.Background(), os.Args)
}
Output:

describeit
next
help
Example (ShellComplete_bash_withLongFlag)
package main

import (
	"context"
	"os"

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

func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Flags: []cli.Flag{
			&cli.IntFlag{
				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.Setenv("SHELL", "bash")
	os.Args = []string{"greet", "--s", "--generate-shell-completion"}

	_ = cmd.Run(context.Background(), os.Args)
}
Output:

--some-flag
--similar-flag
Example (ShellComplete_bash_withMultipleLongFlag)
package main

import (
	"context"
	"os"

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

func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Flags: []cli.Flag{
			&cli.IntFlag{
				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.Setenv("SHELL", "bash")
	os.Args = []string{"greet", "--st", "--generate-shell-completion"}

	_ = cmd.Run(context.Background(), os.Args)
}
Output:

--string
--string-flag-2
Example (ShellComplete_bash_withShortFlag)
package main

import (
	"context"
	"os"

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

func main() {
	cmd := &cli.Command{
		Name:                  "greet",
		EnableShellCompletion: true,
		Flags: []cli.Flag{
			&cli.IntFlag{
				Name:    "other",
				Aliases: []string{"o"},
			},
			&cli.StringFlag{
				Name:    "xyz",
				Aliases: []string{"x"},
			},
		},
	}

	// Simulate a bash environment and command line arguments
	os.Setenv("SHELL", "bash")
	os.Args = []string{"greet", "-", "--generate-shell-completion"}

	_ = cmd.Run(context.Background(), os.Args)
}
Output:

--other
--xyz
--help
Example (ShellComplete_zsh)
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"}
	os.Setenv("SHELL", "/usr/bin/zsh")

	_ = 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
Example (SliceValues)
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.IntSliceFlag{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-float64Slice []float64{13.3, 14.4, 15.5, 16.6}
1-intSlice []int64{13, 14, 15, 16}
2-stringSlice []string{"parsed1", "parsed2", "parsed3", "parsed4"}
error: <nil>
Example (Subcommand)
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
Example (SubcommandNoAction)
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 [command [command options]] [arguments...]

DESCRIPTION:
   This is how we describe describeit the function

OPTIONS:
   --help, -h  show help

func (*Command) Set

func (cmd *Command) Set(name, value string) error

Set sets a context flag to a value.

func (*Command) String

func (cmd *Command) String(name string) string

func (*Command) StringMap

func (cmd *Command) StringMap(name string) map[string]string

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

func (*Command) StringSlice

func (cmd *Command) StringSlice(name string) []string

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

func (*Command) Timestamp

func (cmd *Command) Timestamp(name string) time.Time

Timestamp gets the timestamp from a flag name

func (*Command) ToFishCompletion

func (cmd *Command) ToFishCompletion() (string, error)

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

func (*Command) Uint

func (cmd *Command) Uint(name string) uint64

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

func (*Command) UintSlice

func (cmd *Command) UintSlice(name string) []uint64

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

func (*Command) Value

func (cmd *Command) Value(name string) interface{}

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.

type CommandCategories

type CommandCategories interface {
	// AddCommand adds a command to a category, creating a new category if necessary.
	AddCommand(category string, command *Command)
	// Categories returns a slice of categories sorted by name
	Categories() []CommandCategory
}

CommandCategories interface allows for category manipulation

type CommandCategory

type CommandCategory interface {
	// Name returns the category name string
	Name() string
	// VisibleCommands returns a slice of the Commands with Hidden=false
	VisibleCommands() []*Command
}

CommandCategory is a category containing commands.

type CommandNotFoundFunc

type CommandNotFoundFunc func(context.Context, *Command, string)

CommandNotFoundFunc is executed if the proper command cannot be found

type Countable

type Countable interface {
	Count() int
}

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

type DocGenerationFlag

type DocGenerationFlag interface {
	// TakesValue returns true if the flag takes a value, otherwise false
	TakesValue() bool

	// GetUsage returns the usage string for the flag
	GetUsage() string

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

	// GetDefaultText returns the default text for this flag
	GetDefaultText() string

	// GetEnvVars returns the env vars for this flag
	GetEnvVars() []string

	// IsDefaultVisible returns whether the default value should be shown in
	// help text
	IsDefaultVisible() bool
}

DocGenerationFlag is an interface that allows documentation generation for the flag

type DocGenerationMultiValueFlag

type DocGenerationMultiValueFlag interface {
	DocGenerationFlag

	// IsMultiValueFlag returns true for flags that can be given multiple times.
	IsMultiValueFlag() bool
}

DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags.

type DurationFlag

type DurationFlag = FlagBase[time.Duration, NoConfig, durationValue]

type EnvValueSource

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

EnvValueSource is to specifically detect env sources when printing help text

type ErrorFormatter

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

ErrorFormatter is the interface that will suitably format the error output

type ExitCoder

type ExitCoder interface {
	error
	ExitCode() int
}

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

func Exit

func Exit(message interface{}, 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 an App without having to call os.Exit manually. During testing, this behavior can be avoided by overriding the ExitErrHandler function on an App or the package-global OsExiter function.

type ExitErrHandlerFunc

type ExitErrHandlerFunc func(context.Context, *Command, error)

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

type Flag

type Flag interface {
	fmt.Stringer

	// Apply Flag settings to the given flag set
	Apply(*flag.FlagSet) error

	// All possible names for this flag
	Names() []string

	// Whether the flag has been set or not
	IsSet() bool
}

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

type FlagBase[T any, C any, VC ValueCreator[T, C]] struct {
	Name             string                                   `json:"name"`             // name of the flag
	Category         string                                   `json:"category"`         // category of the flag, if any
	DefaultText      string                                   `json:"defaultText"`      // default text of the flag for usage purposes
	HideDefault      bool                                     `json:"hideDefault"`      // whether to hide the default value in output
	Usage            string                                   `json:"usage"`            // usage string for help output
	Sources          ValueSourceChain                         `json:"-"`                // sources to load flag value from
	Required         bool                                     `json:"required"`         // whether the flag is required or not
	Hidden           bool                                     `json:"hidden"`           // whether to hide the flag in help output
	Local            bool                                     `json:"local"`            // whether the flag needs to be applied to subcommands as well
	Value            T                                        `json:"defaultValue"`     // default value for this flag if not set by from any source
	Destination      *T                                       `json:"-"`                // destination pointer for value when set
	Aliases          []string                                 `json:"aliases"`          // Aliases that are allowed for this flag
	TakesFile        bool                                     `json:"takesFileArg"`     // whether this flag takes a file argument, mainly for shell completion purposes
	Action           func(context.Context, *Command, T) error `json:"-"`                // Action callback to be called when flag is set
	Config           C                                        `json:"config"`           // Additional/Custom configuration associated with this flag type
	OnlyOnce         bool                                     `json:"onlyOnce"`         // whether this flag can be duplicated on the command line
	Validator        func(T) error                            `json:"-"`                // custom function to validate this flag value
	ValidateDefaults bool                                     `json:"validateDefaults"` // whether to validate defaults or not
	// contains filtered or unexported fields
}

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 (*FlagBase[T, C, V]) Apply

func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error

Apply populates the flag given the flag set and environment

func (*FlagBase[T, C, V]) GetCategory

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

GetCategory returns the category of the flag

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

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

GetDefaultText returns the default text for this flag

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

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

GetEnvVars returns the env vars for this flag

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

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

GetUsage returns the usage string for the flag

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

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 (*FlagBase[T, C, V]) IsDefaultVisible

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

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

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

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

IsLocal returns false if flag needs to be persistent across subcommands

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

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 (*FlagBase[T, C, V]) IsRequired

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

IsRequired returns whether or not the flag is required

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

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

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

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

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

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

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

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

Names returns the names of the flag

func (*FlagBase[T, C, V]) RunAction

func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error

RunAction executes flag action if set

func (*FlagBase[T, C, V]) SetCategory

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

func (*FlagBase[T, C, V]) String

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

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

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

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

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

type FlagCategories

type FlagCategories interface {
	// AddFlags adds a flag to a category, creating a new category if necessary.
	AddFlag(category string, fl Flag)
	// VisibleCategories returns a slice of visible flag categories sorted by name
	VisibleCategories() []VisibleFlagCategory
}

FlagCategories interface allows for category manipulation

type FlagEnvHintFunc

type FlagEnvHintFunc func(envVars []string, str string) string

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.

type FlagFileHintFunc

type FlagFileHintFunc func(filePath, str string) string

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.

type FlagNamePrefixFunc

type FlagNamePrefixFunc func(fullName []string, placeholder string) string

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

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.

type FlagsByName

type FlagsByName []Flag

FlagsByName is a slice of Flag.

func (FlagsByName) Len

func (f FlagsByName) Len() int

func (FlagsByName) Less

func (f FlagsByName) Less(i, j int) bool

func (FlagsByName) Swap

func (f FlagsByName) Swap(i, j int)

type FloatArg

type FloatArg = ArgumentBase[float64, NoConfig, floatValue]

type FloatFlag

type FloatFlag = FlagBase[float64, NoConfig, floatValue]

type FloatSlice

type FloatSlice = SliceBase[float64, NoConfig, floatValue]

type FloatSliceFlag

type FloatSliceFlag = FlagBase[[]float64, NoConfig, FloatSlice]

type GenericFlag

type GenericFlag = FlagBase[Value, NoConfig, genericValue]

type IntArg

type IntArg = ArgumentBase[int64, IntegerConfig, intValue]

type IntFlag

type IntFlag = FlagBase[int64, IntegerConfig, intValue]

type IntSlice

type IntSlice = SliceBase[int64, IntegerConfig, intValue]

type IntSliceFlag

type IntSliceFlag = FlagBase[[]int64, IntegerConfig, IntSlice]

type IntegerConfig

type IntegerConfig struct {
	Base int
}

IntegerConfig is the configuration for all integer type flags

type InvalidFlagAccessFunc

type InvalidFlagAccessFunc func(context.Context, *Command, string)

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

type LocalFlag

type LocalFlag interface {
	IsLocal() bool
}

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

type MapBase

type MapBase[T any, C any, VC ValueCreator[T, C]] struct {
	// contains filtered or unexported fields
}

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

func NewMapBase

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 (MapBase[T, C, VC]) Create

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

func (*MapBase[T, C, VC]) Get

func (i *MapBase[T, C, VC]) Get() interface{}

Get returns the mapping of values set by this flag

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

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

Serialize allows MapBase to fulfill Serializer

func (*MapBase[T, C, VC]) Set

func (i *MapBase[T, C, VC]) Set(value string) error

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

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

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

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

func (MapBase[T, C, VC]) ToString

func (i MapBase[T, C, VC]) ToString(t map[string]T) string

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

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

Value returns the mapping of values set by this flag

type MapSource

type MapSource interface {
	fmt.Stringer
	fmt.GoStringer

	// Lookup returns the value from the source based on key
	// and if it was found
	// or returns an empty string and false
	Lookup(string) (any, bool)
}

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

func NewMapSource

func NewMapSource(name string, m map[any]any) MapSource

type MultiError

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

MultiError is an error that wraps multiple errors.

type MutuallyExclusiveFlags

type MutuallyExclusiveFlags struct {
	// Flag list
	Flags [][]Flag

	// whether this group is required
	Required bool

	// Category to apply to all flags within group
	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

type NoConfig struct{}

NoConfig is for flags which dont need a custom configuration

type OnUsageErrorFunc

type OnUsageErrorFunc func(ctx context.Context, cmd *Command, err error, isSubcommand bool) error

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

type RequiredFlag interface {
	// whether the flag is a required flag or not
	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 Serializer

type Serializer interface {
	Serialize() string
}

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

type ShellCompleteFunc

type ShellCompleteFunc func(context.Context, *Command)

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

type SliceBase

type SliceBase[T any, C any, VC ValueCreator[T, C]] struct {
	// contains filtered or unexported fields
}

SliceBase wraps []T to satisfy flag.Value

func NewSliceBase

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

NewSliceBase makes a *SliceBase with default values

func (SliceBase[T, C, VC]) Create

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

func (*SliceBase[T, C, VC]) Get

func (i *SliceBase[T, C, VC]) Get() interface{}

Get returns the slice of values set by this flag

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

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

Serialize allows SliceBase to fulfill Serializer

func (*SliceBase[T, C, VC]) Set

func (i *SliceBase[T, C, VC]) Set(value string) error

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

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

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

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

func (SliceBase[T, C, VC]) ToString

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

func (*SliceBase[T, C, VC]) Value

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

Value returns the slice of values set by this flag

type StringArg

type StringArg = ArgumentBase[string, StringConfig, stringValue]

type StringConfig

type StringConfig struct {
	// Whether to trim whitespace of parsed value
	TrimSpace bool
}

StringConfig defines the configuration for string flags

type StringFlag

type StringFlag = FlagBase[string, StringConfig, stringValue]

type StringMap

type StringMap = MapBase[string, StringConfig, stringValue]

type StringMapArg

type StringMapArg = ArgumentBase[map[string]string, StringConfig, StringMap]

type StringMapFlag

type StringMapFlag = FlagBase[map[string]string, StringConfig, StringMap]

type StringSlice

type StringSlice = SliceBase[string, StringConfig, stringValue]

type StringSliceFlag

type StringSliceFlag = FlagBase[[]string, StringConfig, StringSlice]

type SuggestCommandFunc

type SuggestCommandFunc func(commands []*Command, provided string) string

type SuggestFlagFunc

type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string

type TimestampArg

type TimestampArg = ArgumentBase[time.Time, TimestampConfig, timestampValue]

type TimestampConfig

type TimestampConfig struct {
	Timezone *time.Location
	// Available layouts for flag value.
	//
	// Note that value for formats with missing year/date will be interpreted as current year/date respectively.
	//
	// Read more about time layouts: https://pkg.go.dev/time#pkg-constants
	Layouts []string
}

TimestampConfig defines the config for timestamp flags

type TimestampFlag

type TimestampFlag = FlagBase[time.Time, TimestampConfig, timestampValue]

type UintArg

type UintArg = ArgumentBase[uint64, IntegerConfig, uintValue]

type UintFlag

type UintFlag = FlagBase[uint64, IntegerConfig, uintValue]

type UintSlice

type UintSlice = SliceBase[uint64, IntegerConfig, uintValue]

type UintSliceFlag

type UintSliceFlag = FlagBase[[]uint64, IntegerConfig, UintSlice]

type Value

type Value interface {
	flag.Value
	flag.Getter
}

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

type ValueCreator

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

type ValueSource

type ValueSource interface {
	fmt.Stringer
	fmt.GoStringer

	// Lookup returns the value from the source and if it was found
	// or returns an empty string and false
	Lookup() (string, bool)
}

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

func EnvVar

func EnvVar(key string) ValueSource

func File

func File(path string) ValueSource

func NewMapValueSource

func NewMapValueSource(key string, ms MapSource) ValueSource

type ValueSourceChain

type ValueSourceChain struct {
	Chain []ValueSource
}

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

func EnvVars

func EnvVars(keys ...string) ValueSourceChain

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

func Files

func Files(paths ...string) ValueSourceChain

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

func NewValueSourceChain

func NewValueSourceChain(src ...ValueSource) ValueSourceChain

func (*ValueSourceChain) Append

func (vsc *ValueSourceChain) Append(other ValueSourceChain)

func (*ValueSourceChain) EnvKeys

func (vsc *ValueSourceChain) EnvKeys() []string

func (*ValueSourceChain) GoString

func (vsc *ValueSourceChain) GoString() string

func (*ValueSourceChain) Lookup

func (vsc *ValueSourceChain) Lookup() (string, bool)

func (*ValueSourceChain) LookupWithSource

func (vsc *ValueSourceChain) LookupWithSource() (string, ValueSource, bool)

func (*ValueSourceChain) String

func (vsc *ValueSourceChain) String() string

type VisibleFlag

type VisibleFlag interface {
	// IsVisible returns true if the flag is not hidden, otherwise false
	IsVisible() bool
}

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

type VisibleFlagCategory

type VisibleFlagCategory interface {
	// Name returns the category name string
	Name() string
	// Flags returns a slice of VisibleFlag sorted by name
	Flags() []Flag
}

VisibleFlagCategory is a category containing flags.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL