Documentation
¶
Overview ¶
Package cli provides a simple command-line interface framework.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Command ¶
type Command[T any, M any] struct { Name string // name used to invoke the command. Usage string // short usage text Help string // long help text SetFlags func(flags *flag.FlagSet, target T) // function for defining flags Vars map[string]string // map of flag names -> environment variables Action func(ctx context.Context, env Env[M], target T) ExitStatus // command action Subcommands []Command[T, M] // command subcommands // contains filtered or unexported fields }
A Command represents a CLI command.
T is the type of the target value for configuration storage. M is the type of the metadata provided by the execution Env.
Example ¶
package main
import (
"context"
"flag"
"fmt"
"github.com/jonathonwebb/x/cli"
)
func main() {
type meta struct {
build string
}
type values struct {
env string
addr string
}
serveCmd := cli.Command[*values, meta]{
Name: "serve",
Usage: "serve [flags]",
Help: "flags:\n -addr",
SetFlags: func(flags *flag.FlagSet, target *values) {
flags.StringVar(&target.addr, "addr", "", "")
},
Vars: map[string]string{
"addr": "FOO_ADDR",
},
Action: func(ctx context.Context, env cli.Env[meta], target *values) cli.ExitStatus {
fmt.Printf("env=%s\n", target.env)
fmt.Printf("addr=%s\n", target.addr)
return cli.ExitSuccess
},
}
rootCmd := cli.Command[*values, meta]{
Name: "foo",
Usage: "usage: foo [flags] command",
Help: "commands:\n serve\n\nflags:\n -env",
SetFlags: func(flags *flag.FlagSet, target *values) {
flags.StringVar(&target.env, "env", "", "")
},
Subcommands: []cli.Command[*values, meta]{serveCmd},
}
v := values{}
status := rootCmd.Execute(context.Background(), cli.Env[meta]{
Args: []string{"foo", "-env=dev", "serve"},
Vars: map[string]string{
"FOO_ADDR": "localhost:8000",
},
}, &v)
fmt.Printf("status=%d", status)
}
Output: env=dev addr=localhost:8000 status=0
type Env ¶
type Env[M any] struct { Err io.Writer // error output stream Out io.Writer // standard output stream Args []string // command-line arguments Vars map[string]string // environment variables Meta M // custom metadata }
An Env represents the execution environment for a Command.
M is the type of custom metadata that will be available to Command actions.
func DefaultEnv ¶
DefaultEnv returns an Env using the current process's environment.
The returned Env will use the os.Stderr and os.Stdout streams, os.Args, and environment variables from os.Environ.
type ExitStatus ¶
type ExitStatus int
An ExitStatus is the result of command execution.
const ( ExitSuccess ExitStatus = 0 // execution succeeded ExitFailure ExitStatus = 1 // execution failed due to an error ExitUsage ExitStatus = 2 // execution failed due to invalid user input )
Click to show internal directories.
Click to hide internal directories.