Documentation
¶
Overview ¶
Example (Basic_usage) ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/broothie/cli"
)
func main() {
// Create and run a command called "fileserver".
// `Run` automatically passes down a `context.Background()` and parses `os.Args[1:]`.
// If an error is returned, and it is either a `cli.ExitError` or an `*exec.ExitError`, the error's exit code will be used.
// For any other errors returned, it exits with code 1.
cli.Run("fileserver", "An HTTP server.",
// Add an optional positional argument called "root" which will default to ".".
cli.AddArg("root", "Directory to serve from", cli.SetArgDefault(".")),
// Add an optional flag called "port" (usage: --port) which will default to 3000.
cli.AddFlag("port", "Port to run server.", cli.SetFlagDefault(3000)),
// Register a handler for this command.
// If no handler is registered, it will simply print help and exit.
cli.SetHandler(func(ctx context.Context) error {
// Extract the value of the "root" argument.
root, _ := cli.ArgValue[string](ctx, "root")
// Extract the value of the "port" flag.
port, _ := cli.FlagValue[int](ctx, "port")
addr := fmt.Sprintf(":%d", port)
return http.ListenAndServe(addr, http.FileServer(http.Dir(root)))
}),
)
}
Example (Kitchen_sink) ¶
package main
import (
"context"
"os"
"github.com/broothie/cli"
)
func main() {
// Create a new command
cmd, err := cli.NewCommand("git", "Modern version control.",
// Set command version
cli.SetVersion("2.37.0"),
// Add a "--version" flag with a short flag "-V" for printing the command version
cli.AddVersionFlag(cli.AddFlagShort('V')),
// Add a "--help" flag
cli.AddHelpFlag(
// Add a short flag "-h" to help
cli.AddFlagShort('h'),
// Make this flag inherited by sub-commands
cli.SetFlagIsInherited(true),
),
// Add a hidden "--debug" flag
cli.AddFlag("debug", "Enable debugging",
cli.SetFlagDefault(false), // Default parser for flags is cli.StringParser
// Make it hidden
cli.SetFlagIsHidden(true),
),
// Add a sub-command "clone"
cli.AddSubCmd("clone", "Clone a repository.",
// Add a required argument "<url>"
cli.AddArg("url", "Repository to clone.",
// Parse it into a *url.URL
cli.SetArgParser(cli.URLParser),
),
// Add optional argument "<dir?>"
cli.AddArg("dir", "Directory to clone repo into.",
// Set its default value to "."
cli.SetArgDefault("."),
),
// Add a flag "--verbose"
cli.AddFlag("verbose", "Be more verbose.",
// Add a short "-v"
cli.AddFlagShort('v'),
// Make it a boolean that defaults to false
cli.SetFlagDefault(false),
),
),
)
if err != nil {
cli.ExitWithError(err)
}
// Pass in your `context.Context` and args
if err := cmd.Run(context.TODO(), os.Args[1:]); err != nil {
cli.ExitWithError(err)
}
}
Index ¶
- Variables
- func AddAlias(alias string) option.Func[*Command]
- func AddArg(name, description string, options ...option.Option[*Argument]) option.Func[*Command]
- func AddFlag(name, description string, options ...option.Option[*Flag]) option.Func[*Command]
- func AddFlagAlias(alias string) option.Func[*Flag]
- func AddFlagShort(short rune) option.Func[*Flag]
- func AddHelpFlag(options ...option.Option[*Flag]) option.Func[*Command]
- func AddSubCmd(name, description string, options ...option.Option[*Command]) option.Func[*Command]
- func AddVersionFlag(options ...option.Option[*Flag]) option.Func[*Command]
- func ArgValue[T any](ctx context.Context, name string) (T, error)
- func BoolParser(s string) (bool, error)
- func DurationParser(s string) (time.Duration, error)
- func ExitWithError(err error)
- func FlagValue[T any](ctx context.Context, name string) (T, error)
- func Float64Parser(s string) (float64, error)
- func IntParser(s string) (int, error)
- func MountSubCmd(subCommand *Command) option.Func[*Command]
- func Run(name, description string, options ...option.Option[*Command])
- func SetArgDefault[T Parseable](defaultValue T) option.Func[*Argument]
- func SetArgParser[T any](parser ArgParser[T]) option.Func[*Argument]
- func SetFlagDefault[T Parseable](defaultValue T) option.Func[*Flag]
- func SetFlagDefaultAndParser[T any](defaultValue T, argParser ArgParser[T]) option.Func[*Flag]
- func SetFlagDefaultEnv(name string) option.Func[*Flag]
- func SetFlagIsHidden(isHidden bool) option.Func[*Flag]
- func SetFlagIsInherited(isInherited bool) option.Func[*Flag]
- func SetHandler(handler Handler) option.Func[*Command]
- func SetVersion(version string) option.Func[*Command]
- func StringParser(s string) (string, error)
- func TimeParser(s string) (time.Time, error)
- func URLParser(s string) (*url.URL, error)
- type ArgParser
- type Argument
- type Command
- type ExitError
- type Flag
- type Handler
- type Parseable
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( NotACommandContextError = errors.New("not a command context") FlagNotFoundError = errors.New("flag not found") ArgumentNotFoundError = errors.New("argument not found") )
var ( InvalidFlagError = errors.New("invalid flag") MissingFlagValueError = errors.New("missing flag value") TooManyArgumentsError = errors.New("too many arguments") FlagGroupWithEqualError = errors.New("short flags with equal signs cannot be grouped") )
var ArgumentMissingValueError = errors.New("argument missing value")
var NotParseableError = errors.New("type not parseable")
Functions ¶
func AddArg ¶
AddArg adds an argument to the command.
Example ¶
command, _ := NewCommand("server", "An http server.",
AddArg("port", "Port to run server on", SetArgParser(IntParser)),
)
command.renderHelp(os.Stdout)
Output: server: An http server. Usage: server <port> Arguments: <port> Port to run server on (type: int)
func AddFlag ¶
AddFlag adds a flag to the command.
Example ¶
command, _ := NewCommand("server", "An http server.",
AddFlag("port", "Port to run server on",
AddFlagShort('p'),
SetFlagDefault(3000),
),
)
command.renderHelp(os.Stdout)
Output: server: An http server. Usage: server [flags] Flags: --port -p Port to run server on (type: int, default: "3000")
Example (With_env) ¶
os.Setenv("PORT", "8080")
defer os.Unsetenv("PORT")
command, _ := NewCommand("server", "An http server.",
AddFlag("port", "Port to run server on",
AddFlagShort('p'),
SetFlagDefault(3000),
SetFlagDefaultEnv("PORT"),
),
)
command.renderHelp(os.Stdout)
Output: server: An http server. Usage: server [flags] Flags: --port -p Port to run server on (type: int, default: $PORT, "3000")
func AddFlagAlias ¶
AddFlagAlias adds an alias to the flag.
func AddFlagShort ¶
AddFlagShort adds a short flag to the flag.
func AddHelpFlag ¶
AddHelpFlag adds a help flag to the command.
Example ¶
command, _ := NewCommand("server", "An http server.",
AddHelpFlag(AddFlagShort('h')),
)
command.renderHelp(os.Stdout)
Output: server: An http server. Usage: server [flags] Flags: --help -h Print help. (type: bool, default: "false")
func AddSubCmd ¶
AddSubCmd adds a subcommand to the command.
Example ¶
command, _ := NewCommand("server", "An http server.",
AddSubCmd("start", "Start the server"),
)
command.renderHelp(os.Stdout)
Output: server: An http server. Usage: server [sub-command] Sub-commands: start: Start the server
func AddVersionFlag ¶
Example ¶
command, _ := NewCommand("server", "An http server.",
SetVersion("v0.1.0"),
AddVersionFlag(AddFlagShort('V')),
)
command.renderHelp(os.Stdout)
Output: server v0.1.0: An http server. Usage: server [flags] Flags: --version -V Print version. (type: bool, default: "false")
func DurationParser ¶
DurationParser parses a string into a time.Duration.
func ExitWithError ¶ added in v0.1.3
func ExitWithError(err error)
ExitWithError exits the program with an error.
func Float64Parser ¶
Float64Parser parses a string into a float64.
func MountSubCmd ¶ added in v0.1.3
MountSubCmd mounds an existing *Command as a sub-command.
func Run ¶
Run creates and runs a command using os.Args as the arguments and context.Background as the context.
Example ¶
oldArgs := os.Args
os.Args = []string{"echo", "hello"}
defer func() { os.Args = oldArgs }()
Run("echo", "Echo the arguments.",
AddArg("arg", "The argument to echo."),
SetHandler(func(ctx context.Context) error {
arg, _ := ArgValue[string](ctx, "arg")
fmt.Println(arg)
return nil
}),
)
Output: hello
func SetArgDefault ¶ added in v0.1.2
SetArgDefault sets the default value of the argument.
func SetArgParser ¶
SetArgParser sets the parser of the argument.
func SetFlagDefault ¶
SetFlagDefault sets the default value of the flag.
func SetFlagDefaultAndParser ¶
SetFlagDefaultAndParser sets the default value and parser of the flag.
func SetFlagDefaultEnv ¶ added in v0.1.3
SetFlagDefaultEnv sets the default value to that of the corresponding environment variable, and parser of the flag.
func SetFlagIsHidden ¶
SetFlagIsHidden controls whether the flag is hidden from the help message.
func SetFlagIsInherited ¶
SetFlagIsInherited controls whether the flag is inherited by child commands.
func SetHandler ¶
SetHandler sets the handler of the command.
Example ¶
command, _ := NewCommand("server", "An http server.",
SetHandler(func(ctx context.Context) error {
fmt.Println("running server")
return nil
}),
)
command.Run(context.Background(), nil)
Output: running server
func SetVersion ¶
SetVersion sets the version of the command.
Example ¶
command, _ := NewCommand("server", "An http server.",
SetVersion("v0.1.0"),
)
command.renderHelp(os.Stdout)
Output: server v0.1.0: An http server. Usage: server
func StringParser ¶
StringParser parses a string into a string.
func TimeParser ¶
TimeParser parses a string into a time.Time.
Types ¶
type ArgParser ¶
ArgParser is a function that parses a string into a value of type T.
func NewArgParser ¶
NewArgParser creates a new ArgParser.
func TimeLayoutParser ¶
TimeLayoutParser parses a string into a time.Time using a specific time layout.
type Command ¶
type Command struct {
// contains filtered or unexported fields
}
func NewCommand ¶
NewCommand creates a new command.
Example ¶
command, _ := NewCommand("server", "An http server.",
SetVersion("v0.1.0"),
AddVersionFlag(AddFlagShort('V')),
AddHelpFlag(AddFlagShort('h')),
AddFlag("port", "Port to run server on.",
AddFlagShort('p'),
SetFlagDefault(3000),
SetFlagDefaultEnv("PORT"),
),
AddFlag("auth-required", "Whether to require authentication.",
SetFlagDefault(true),
),
AddSubCmd("proxy", "Proxy requests to another server.",
AddArg("target", "Target server to proxy requests to.",
SetArgParser(URLParser),
),
),
)
command.renderHelp(os.Stdout)
Output: server v0.1.0: An http server. Usage: server [flags] [sub-command] Sub-commands: proxy: Proxy requests to another server. Flags: --version -V Print version. (type: bool, default: "false") --help -h Print help. (type: bool, default: "false") --port -p Port to run server on. (type: int, default: $PORT, "3000") --auth-required Whether to require authentication. (type: bool, default: "true")