Documentation
¶
Overview ¶
Package ox is a minimal dependency Go (and TinyGo compatible) command-line flag and argument parsing library.
Example ¶
Example demonstrates quickly using the xo/ox package.
package main
import (
"net/url"
"time"
"github.com/xo/ox"
)
func main() {
type Verbosity int
args := struct {
MyString string `ox:"a string,short:s"`
MyBool bool `ox:"a bool,short:b"`
Ints []int `ox:"a slice of ints,short:i"`
Date time.Time `ox:"formatted date,type:date,short:d"`
MyURL *url.URL `ox:"a url,name:url,short:u"`
Verbose Verbosity `ox:"enable verbose,short:v,type:count"`
Sub struct {
Bools map[string]bool `ox:"bool map,short:y"`
} `ox:""`
Extra struct {
SomeOtherString string `ox:"another string,short:S"`
AReallyLongName string `ox:"long arg"`
} `ox:"x"`
}{}
ox.Run(
// ox.Exec(myFunc),
ox.Usage("myApp", "my app"),
ox.Defaults(
ox.Banner(`an example ox app.`),
ox.Footer(`See: https://github.com/xo/ox for more information.`),
),
ox.From(&args),
)
}
Output: an example ox app. Usage: myApp [flags] [args] Flags: -s, --my-string string a string -b, --my-bool a bool -i, --ints int a slice of ints -d, --date date formatted date -u, --url url a url -v, --verbose enable verbose -y, --sub-bools string=bool bool map -S, --x-some-other-string string another string --x-a-really-long-name string long arg --version show version, then exit -h, --help show help, then exit See: https://github.com/xo/ox for more information.
Example (ArgsTest) ¶
Example_argsTest demonstrates testing arbitrary command-line invocations by setting the arguments to Parse with ox.Args.
package main
import (
"context"
"errors"
"net/netip"
"net/url"
"github.com/xo/ox"
)
func main() {
args := struct {
Number float64 `ox:"a number"`
}{}
subArgs := struct {
URL *url.URL `ox:"a url,short:u"`
Addr *netip.Addr `ox:"an ip address"`
}{}
ox.RunContext(
context.Background(),
// ox.Exec(myFunc),
ox.Usage("extest", "test example"),
ox.Defaults(),
ox.From(&args),
ox.Sub(
ox.Exec(func() error {
// return an error to show that this func is not called
return errors.New("oops")
}),
ox.Usage("sub", "a sub command to test"),
ox.From(&subArgs),
ox.Sort(true),
),
ox.Sort(true),
// the command line args to test
ox.Args("help", "sub"),
)
}
Output: sub a sub command to test Usage: extest sub [flags] [args] Flags: -u, --url url a url --addr addr an ip address -h, --help show help, then exit
Example (Context) ¶
Example_context reads the values of the flags from the context of the exec func, with the generic funcs of the otx package. A sub command reads the flags of its parents too.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("tool", "a tool"),
ox.Defaults(),
ox.Flags().
Count("verbose", "verbosity", ox.Short("v")).
Slice("port", "a port", ox.IntT, ox.Short("p")),
ox.Sub(
ox.Usage("run", "run a job"),
ox.Flags().
Map("env", "an environment variable", ox.Short("e")),
ox.Exec(func(ctx context.Context, args []string) error {
fmt.Println("verbose:", otx.Get[int](ctx, "verbose"))
fmt.Println("ports:", otx.Slice[int](ctx, "port"))
fmt.Println("ports as strings:", otx.Slice[string](ctx, "port"))
fmt.Println("env:", otx.Map[string, string](ctx, "env"))
fmt.Println("args:", args)
return nil
}),
),
ox.Args("-v", "-p", "80,443", "run", "-e", "A=1", "-e", "B=2", "job1"),
)
}
Output: verbose: 1 ports: [80 443] ports as strings: [80 443] env: map[A:1 B:2] args: [job1]
Example (DefaultVariables) ¶
Example_defaultVariables expands variables in a default. A \$ in a default is a $ that does not start a variable.
package main
import (
"context"
"fmt"
"os"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
_ = os.Setenv("APP_DIR", "/srv/app")
defer func() { _ = os.Unsetenv("APP_DIR") }()
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
String("dir", "the directory", ox.Default("${env::APP_DIR}/data")).
String("rc", "the startup file", ox.Default("/etc/.${APPNAME|lower}rc")).
String("price", "the price", ox.Default(`\$5`)),
ox.Exec(func(ctx context.Context) {
fmt.Println("dir:", otx.String(ctx, "dir"))
fmt.Println("rc:", otx.String(ctx, "rc"))
fmt.Println("price:", otx.String(ctx, "price"))
}),
ox.Args(),
)
}
Output: dir: /srv/app/data rc: /etc/.apprc price: $5
Example (Help) ¶
Example_help demonstrates configuring help output.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("cmdtree", "help command tree"),
ox.Defaults(ox.Sort(true)),
ox.Sub(
ox.Usage("sub1", "sub1 tree"),
ox.Sub(
ox.Usage("sub2", "sub2 tree"),
ox.Aliases("subcommand2", "subby2"),
ox.Flags().
String("my-flag", "my flag").
BigInt("big-int", "big int", ox.Short("B")).
Int("a", "the a int"),
ox.Sub(ox.Usage("sub3", "sub3 tree")),
ox.Sub(ox.Usage("a", "another command")),
),
),
ox.Args("help", "sub1", "subcommand2", "--bad-flag", "-b"),
)
}
Output: sub2 sub2 tree Usage: cmdtree sub1 sub2 [flags] [command] [args] Aliases: sub2, subcommand2, subby2 Available Commands: a another command sub3 sub3 tree Flags: --a int the a int -B, --big-int bigint big int -h, --help show help, then exit --my-flag string my flag Use "cmdtree sub1 sub2 [command] --help" for more information about a command.
Example (Psql) ¶
Example_psql demonstrates building complex help output, based on original output of `psql --help`. The output formatting has been slightly changed, as the generated help output alters the column formatting, and the output cannot be duplicated perfectly -- that said, a faithful attempt has been made to stick to the original help output wherever possible.
package main
import (
"github.com/xo/ox"
)
func main() {
args := struct {
Command string `ox:"run only single command (SQL or internal) and exit,short:c,section:0"`
Dbname string `ox:"database name to connect to,short:d,default:$USER,section:0"`
File string `ox:"execute commands from file\\, then exit,short:f,spec:FILENAME,section:0"`
List bool `ox:"list databases\\, then exit,short:l,section:0"`
Variable map[string]string `ox:"set psql variable NAME to VALUE,short:v,alias:set,spec:NAME=VALUE,section:0"`
Version bool `ox:"output version information\\, then exit,hook:version,short:V,section:0"`
NoPsqlrc bool `ox:"do not read startup file (~/.psqlrc),short:X,section:0"`
SingleTransaction bool `ox:"execute as a single transaction (if non-interactive),short:1,section:0"`
Help bool `ox:"show this help\\, then exit,short:?,hook:help,section:0"`
EchoAll bool `ox:"echo all input from script,short:a,section:1"`
EchoErrors bool `ox:"echo failed commands,short:b,section:1"`
EchoQueries bool `ox:"echo commands sent to server,short:e,section:1"`
EchoHidden bool `ox:"disply queries that internal commands generate,short:E,section:1"`
LogFile string `ox:"send session log to file,spec:FILENAME,short:L,section:1"`
NoReadline bool `ox:"display enhanced command line editing (readline),short:n,section:1"`
Output string `ox:"send query results to file (or |pipe),short:o,section:1"`
Quiet bool `ox:"run quietly (no messages\\, only query output),short:q,section:1"`
SingleStep bool `ox:"single-step mode (confirm each query),short:s,section:1"`
SingleLine bool `ox:"single-line mode (end of line terminates SQL command),short:S,section:1"`
NoAlign bool `ox:"unaligned table output mode,short:A,section:2"`
CSV bool `ox:"CSV (Comma-Separated Values) table output mode,section:2"`
FieldSeparator string `ox:"field separator for unaligned output,default:|,short:F,section:2"`
HTML bool `ox:"HTML table output mode,short:H,section:2"`
Pset map[string]string `ox:"set printing option VAR to ARG (see \\pset command),short:P,spec:VAR[=ARG],section:2"`
RecordSeparator string `ox:"record separator for unaligned output,default:newline,short:R,section:2"`
TuplesOnly bool `ox:"print rows only,short:t,section:2"`
TableAttr string `ox:"set HTML table tag attributes (e.g.\\, width\\, border),short:T,section:2"`
Expanded bool `ox:"turn on expanded table output,short:x,section:2"`
FieldSeparatorZero string `ox:"set field separator for unaligned output to zero byte,short:z,section:2"`
RecordSeparatorZero string `ox:"set record separator for unaligned output to zero byte,short:0,section:2"`
Host string `ox:"database server host or socket directory,default:local socket,spec:HOSTNAME,short:h,section:3"`
Port uint `ox:"database server port,default:5432,spec:PORT,short:p,section:3"`
Username string `ox:"database user name,default:$USER,spec:USERNAME,short:U,section:3"`
NoPassword bool `ox:"never prompt for password,short:w,section:3"`
Password bool `ox:"force password prompt (should happen automatically),short:W,section:3"`
}{}
ox.Run(
// ox.Exec(myFunc),
ox.Usage("psql", "the PostgreSQL interactive terminal"),
ox.Help(
ox.Banner("psql is the PostgreSQL interactive terminal."),
ox.Spec("[OPTION]... [DBNAME [USERNAME]]"),
ox.Sections(
"General options",
"Input and output options",
"Output format options",
"Connection options",
),
ox.Footer(`For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.
Report bugs to <pgsql-bugs@lists.postgresql.org>.
PostgreSQL home page: <https://www.postgresql.org/>`),
),
ox.From(&args),
// override replacement key expansion, used for testing/injecting configurations
ox.OverrideMap(map[string]string{
"USER": "fuser",
}),
)
}
Output: psql is the PostgreSQL interactive terminal. Usage: psql [OPTION]... [DBNAME [USERNAME]] General options: -c, --command string run only single command (SQL or internal) and exit -d, --dbname string database name to connect to (default: fuser) -f, --file FILENAME execute commands from file, then exit -l, --list list databases, then exit -v, --variable NAME=VALUE set psql variable NAME to VALUE -V, --version output version information, then exit -X, --no-psqlrc do not read startup file (~/.psqlrc) -1, --single-transaction execute as a single transaction (if non-interactive) -?, --help show this help, then exit Input and output options: -a, --echo-all echo all input from script -b, --echo-errors echo failed commands -e, --echo-queries echo commands sent to server -E, --echo-hidden disply queries that internal commands generate -L, --log-file FILENAME send session log to file -n, --no-readline display enhanced command line editing (readline) -o, --output string send query results to file (or |pipe) -q, --quiet run quietly (no messages, only query output) -s, --single-step single-step mode (confirm each query) -S, --single-line single-line mode (end of line terminates SQL command) Output format options: -A, --no-align unaligned table output mode --csv CSV (Comma-Separated Values) table output mode -F, --field-separator string field separator for unaligned output (default: |) -H, --html HTML table output mode -P, --pset VAR[=ARG] set printing option VAR to ARG (see pset command) -R, --record-separator string record separator for unaligned output (default: newline) -t, --tuples-only print rows only -T, --table-attr string set HTML table tag attributes (e.g., width, border) -x, --expanded turn on expanded table output -z, --field-separator-zero string set field separator for unaligned output to zero byte -0, --record-separator-zero string set record separator for unaligned output to zero byte Connection options: -h, --host HOSTNAME database server host or socket directory (default: local socket) -p, --port PORT database server port (default: 5432) -U, --username USERNAME database user name (default: fuser) -w, --no-password never prompt for password -W, --password force password prompt (should happen automatically) For more information, type "\?" (for internal commands) or "\help" (for SQL commands) from within psql, or consult the psql section in the PostgreSQL documentation. Report bugs to <pgsql-bugs@lists.postgresql.org>. PostgreSQL home page: <https://www.postgresql.org/>
Example (PsqlHelp) ¶
Example_psqlHelp builds a help that looks like the help of psql, by hand. The help and version flags are in the "General options" section, with psql's short names.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("psql", "the PostgreSQL interactive terminal"),
ox.VersionString("18.1"),
ox.Version(),
ox.Help(
ox.Banner("psql is the PostgreSQL interactive terminal."),
ox.Spec("[OPTION]... [DBNAME [USERNAME]]"),
ox.Sections(
"General options",
"Connection options",
),
ox.Footer("PostgreSQL home page: <https://www.postgresql.org/>"),
),
ox.Flags().
String("command", "run only single command (SQL or internal) and exit", ox.Short("c"), ox.Section(0)).
String("file", "execute commands from file, then exit", ox.Short("f"), ox.Spec("FILENAME"), ox.Section(0)).
Bool("version", "output version information, then exit", ox.Short("V"), ox.Special("hook:version"), ox.Section(0)).
Bool("help", "show this help, then exit", ox.Short("?"), ox.Special("hook:help"), ox.Section(0)).
String("host", "database server host or socket directory", ox.Short("h"), ox.Spec("HOSTNAME"), ox.Section(1)).
Uint("port", "database server port", ox.Short("p"), ox.Spec("PORT"), ox.Default("5432"), ox.Section(1)),
ox.Args("-?"),
)
}
Output: psql is the PostgreSQL interactive terminal. Usage: psql [OPTION]... [DBNAME [USERNAME]] General options: -c, --command string run only single command (SQL or internal) and exit -f, --file FILENAME execute commands from file, then exit -V, --version output version information, then exit -?, --help show this help, then exit Connection options: -h, --host HOSTNAME database server host or socket directory -p, --port PORT database server port (default: 5432) PostgreSQL home page: <https://www.postgresql.org/>
Example (Sections) ¶
Example_sections demonstrates setting the help section for commands and flags, including default `--help` flag and `help` command.
package main
import (
"net/url"
"github.com/xo/ox"
)
func main() {
args := struct {
Config string `ox:"config file,spec:FILE,section:1"`
MyInts []int `ox:"a integer slice,short:i"`
URLMap map[int]*url.URL `ox:"urls,short:U"`
}{}
ox.Run(
ox.Usage("tree", "a command tree"),
ox.Defaults(ox.Sections(
"Normal flags",
"More flags",
"Other flags",
)),
ox.Sub(
ox.Usage("sub1", "the sub1 command"),
ox.Section(0),
),
ox.Sub(
ox.Usage("sub2.b", "the sub2.b command"),
),
ox.Sub(
ox.Usage("sub2.a", "the sub2.a command"),
ox.Section(1),
),
ox.Sections(
"Primary commands",
"Secondary commands",
),
ox.SectionMap{
"help": 0,
"sub2.b": 1,
"flag:help": 0,
"flag:my-ints": 2,
},
ox.From(&args),
)
}
Output: tree a command tree Usage: tree [flags] [command] [args] Available Commands: completion generate completion script for a specified shell version show tree version information Primary commands: help show help for any command sub1 the sub1 command Secondary commands: sub2.a the sub2.a command sub2.b the sub2.b command Flags: -U, --url-map int=url urls Normal flags: -h, --help show help, then exit More flags: --config FILE config file Other flags: -i, --my-ints int a integer slice Use "tree [command] --help" for more information about a command.
Example (Sources) ¶
Example_sources shows the order of the sources of a value. The command line wins over the environment. The environment wins over the config files, and the config files win over the default.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
dir, err := os.MkdirTemp("", "app")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "config.json")
_ = os.WriteFile(path, []byte(`{"level": "from-file"}`), 0o600)
run := func(args ...string) {
ox.Run(
ox.Usage("app", "an app"),
ox.EnvPrefix("APP"),
ox.ConfigFiles(path),
ox.Flags().
String("level", "the level", ox.Default("from-default")),
ox.Exec(func(ctx context.Context) {
fmt.Println(otx.String(ctx, "level"))
}),
ox.Args(args...),
)
}
_ = os.Setenv("APP_LEVEL", "from-env")
run("--level", "from-command-line")
run()
_ = os.Unsetenv("APP_LEVEL")
run()
_ = os.Remove(path)
run()
}
Output: from-command-line from-env from-file from-default
Index ¶
- Constants
- Variables
- func AddHelpFlag(cmd *Command) error
- func AppFrom[T *E, E any](v T, opts ...Option)
- func AppendRate(b []byte, rate Rate, verb rune, prec int, space bool) []byte
- func AppendSize(b []byte, size int64, verb rune, prec int, space bool) []byte
- func Apply(v any, opts ...Option) error
- func ApplyPost(cmd *Command, opts ...Option) error
- func As[T any](value Value) (T, error)
- func AsMap[K cmp.Ordered, E any](value Value) (map[K]E, error)
- func AsSlice[E any](value Value) ([]E, error)
- func BuildVersion() string
- func FormatRate(rate Rate, verb rune, prec int, space bool) string
- func FormatSize(size int64, verb rune, prec int, space bool) string
- func InterpolateVar(ctx *Context, v any) (any, error)
- func Ldist[T []E, E cmp.Ordered](a, b T) int
- func NewComp(cmd *Command, opts ...Option) error
- func NewCompFlags(cmd *Command, _ ...Option) error
- func NewHelp(cmd *Command, opts ...Option) error
- func NewHelpFlag(cmd *Command, opts ...Option) error
- func NewSuggestionError(parent *Command, arg string, command *Command) error
- func NewTime(typ Type, layout string) func() (Value, error)
- func NewVal[T any](opts ...Option) func() (Value, error)
- func NewVersion(cmd *Command, opts ...Option) error
- func NewVersionFlag(cmd *Command, opts ...Option) error
- func ParseFlagLong(ctx *Context, cmd *Command, s string, args []string) ([]string, error)
- func ParseFlagPlus(ctx *Context, cmd *Command, s string, args []string) ([]string, error)
- func ParseFlagShort(ctx *Context, cmd *Command, s string, args []string) ([]string, error)
- func Realpath(path string) (string, error)
- func RegisterBinaryType[T BinaryMarshalUnmarshaler](f func() (T, error))
- func RegisterConfigFormat(typ ConfigType, decode func([]byte) (Config, error), exts ...string)
- func RegisterConfigLoader(typ ConfigType, loader func(*Context, string) (any, bool, error))
- func RegisterConfigLoaderOrder(order ...ConfigType)
- func RegisterDoc[T any](doc string, fields map[string]string)
- func RegisterTextType[T TextMarshalUnmarshaler](f func() (T, error))
- func RegisterType(typ Type, f func() (Value, error), opts ...Option)
- func RegisterTypeName(typ Type, names ...string)
- func Run(opts ...Option)
- func RunContext(ctx context.Context, opts ...Option)
- func RunError(ctx context.Context, opts ...Option) error
- func SplitBy(str string, cut rune) []string
- func To[T any](value Value) T
- func ToMap[K cmp.Ordered, E any](value Value) map[K]E
- func ToSlice[E any](value Value) []E
- func UserStateDir() (string, error)
- func WithContext(parent context.Context, ctx *Context) context.Context
- func Wrap(s string, width, prefixWidth int) string
- type ArgOption
- type Argument
- type BinaryMarshalUnmarshaler
- type Binder
- type Command
- func (cmd *Command) Command(name string) *Command
- func (cmd *Command) CommandSpecial(special string) *Command
- func (cmd *Command) CompCommands(name string, hidden, deprecated bool) ([]Completion, CompDirective)
- func (cmd *Command) CompFlags(name string, hidden, deprecated, short bool) ([]Completion, CompDirective)
- func (cmd *Command) CompPlus(name string, hidden, deprecated bool) ([]Completion, CompDirective)
- func (cmd *Command) Flag(name string, parents, short bool) *Flag
- func (cmd *Command) FlagSpecial(special string) *Flag
- func (cmd *Command) HelpContext(ctx *Context) io.WriterTo
- func (cmd *Command) Lookup(args ...string) *Command
- func (cmd *Command) NegatedNames(g *Flag) []string
- func (cmd *Command) Path() []string
- func (cmd *Command) RootName() string
- func (cmd *Command) Sub(opts ...Option) error
- func (cmd *Command) SubSpecial(special string) *Command
- func (cmd *Command) Suggest(args ...string) error
- func (cmd *Command) Tree() []string
- func (cmd *Command) UsageString() string
- func (cmd *Command) Validate(args []string) error
- func (cmd *Command) WalkFlags(hidden, deprecated bool) iter.Seq[*Flag]
- func (cmd *Command) WriteTo(w io.Writer) (int64, error)
- type CommandFlagOption
- func Aliases(aliases ...string) CommandFlagOption
- func CompFunc(f func(ctx *Context, toComplete string) ([]Completion, CompDirective, error)) CommandFlagOption
- func Deprecated(deprecated bool) CommandFlagOption
- func Help(opts ...Option) CommandFlagOption
- func Hidden(hidden bool) CommandFlagOption
- func Name(name string) CommandFlagOption
- func Section(section int) CommandFlagOption
- func Usage(name, usage string) CommandFlagOption
- type CommandHelp
- func (help *CommandHelp) AddAliases(w StringWriter)
- func (help *CommandHelp) AddArgs(w StringWriter)
- func (help *CommandHelp) AddBanner(w StringWriter)
- func (help *CommandHelp) AddCommands(w StringWriter)
- func (help *CommandHelp) AddExample(w StringWriter)
- func (help *CommandHelp) AddFlags(w StringWriter)
- func (help *CommandHelp) AddFooter(w StringWriter)
- func (help *CommandHelp) AddInheritedFlags(w StringWriter)
- func (help *CommandHelp) AddUsage(w StringWriter)
- func (help *CommandHelp) FlagUsage(g *Flag) string
- func (help *CommandHelp) SetContext(ctx *Context)
- func (help *CommandHelp) SpecString() string
- func (help *CommandHelp) WriteTo(w io.Writer) (int64, error)
- type CommandOption
- func Abbrev() CommandOption
- func After[F ExecType](f F) CommandOption
- func AllOrNoneOf(names ...string) CommandOption
- func App[T *E, E any](v T) CommandOption
- func AppNameVersion(name, version string) CommandOption
- func Arg(name, usage string, opts ...Option) CommandOption
- func ArgsFunc(funcs ...func([]string) error) CommandOption
- func AtLeastOneOf(names ...string) CommandOption
- func BashLongFlags() CommandOption
- func Before[F ExecType](f F) CommandOption
- func CommandSort(commandSort bool) CommandOption
- func Comp() CommandOption
- func ConfigFiles(paths ...string) CommandOption
- func ConfigRequired() CommandOption
- func Defaults(opts ...Option) CommandOption
- func EnvPrefix(prefix string) CommandOption
- func Exec[F ExecType](f F) CommandOption
- func Extend(name string, f func(*Command) error) CommandOption
- func From[T *E, E any](val T) CommandOption
- func HelpColumn(column int) CommandOption
- func InheritedFlags(show bool) CommandOption
- func LetterClusters() CommandOption
- func MaxDist(maxDist int) CommandOption
- func NegateBools(prefixes ...string) CommandOption
- func OnlyOneOf(names ...string) CommandOption
- func Parent(parent *Command) CommandOption
- func PlusWords() CommandOption
- func Sort(sort bool) CommandOption
- func StopAtArg() CommandOption
- func Sub(opts ...Option) CommandOption
- func Suggested(suggested ...string) CommandOption
- func ValidArgs(minimum, maximum int, values ...string) CommandOption
- func Version() CommandOption
- func VersionString(version string) CommandOption
- type CompDirective
- type Completion
- type Config
- type ConfigType
- type Context
- func (ctx *Context) Comps() ([]Completion, CompDirective, error)
- func (ctx *Context) Expand(v any) (any, error)
- func (ctx *Context) Fill(cmd *Command) error
- func (ctx *Context) IsPlus() bool
- func (ctx *Context) NoValue() bool
- func (ctx *Context) Parse() error
- func (ctx *Context) Populate(cmd *Command, all, overwrite bool) error
- func (ctx *Context) Run(parent context.Context) error
- func (ctx *Context) Validate() error
- type ContextOption
- func Args(args ...string) ContextOption
- func Interpolate(interpolate func(*Context, any) (any, error)) ContextOption
- func Lookup(lookup func(*Context, ConfigType, string) (any, error)) ContextOption
- func Override(override func(ConfigType, string) (any, bool, error)) ContextOption
- func OverrideMap(override map[string]string) ContextOption
- func Pipe(stdin io.Reader, stdout, stderr io.Writer) ContextOption
- type Error
- type ExecFunc
- type ExecType
- type Flag
- type FlagGroup
- type FlagHelpOption
- type FlagOption
- func Abs() FlagOption
- func AllowPlus() FlagOption
- func Bind[T *E, E any](v T) FlagOption
- func BindRef(value reflect.Value, set *bool) FlagOption
- func BindSet[T *E, E any](v T, set *bool) FlagOption
- func ConfigFlag() FlagOption
- func Default(def any) FlagOption
- func DeprecatedAliases(aliases ...string) FlagOption
- func Elem(elem Type) FlagOption
- func EnvVar(name string) FlagOption
- func Ext(exts ...string) FlagOption
- func HelpValue(value, usage string, funcs ...func(*Context) error) FlagOption
- func HiddenAliases(aliases ...string) FlagOption
- func Home() FlagOption
- func Hook(f func(context.Context) error) FlagOption
- func Key(typ, key string) FlagOption
- func Local() FlagOption
- func MapKey(mapKey Type) FlagOption
- func Negatable(negatable bool) FlagOption
- func NoArg(noArg bool, def any) FlagOption
- func NoConfig() FlagOption
- func NoDefault() FlagOption
- func NoEnv() FlagOption
- func NotExist() FlagOption
- func OptionalAtEnd() FlagOption
- func OptionalValue(spec string) FlagOption
- func Real() FlagOption
- func Required() FlagOption
- func Short(short string) FlagOption
- func Special(special string) FlagOption
- func Split(split string) FlagOption
- func Strftime(layout string) FlagOption
- func TypeFor[T any]() FlagOption
- func Valid[T cmp.Ordered](values ...T) FlagOption
- type FlagSet
- func (fs *FlagSet) Addr(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) AddrPort(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Array(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Base64(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) BigFloat(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) BigInt(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) BigRat(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Bool(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Byte(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Bytes(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) CIDR(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Complex64(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Complex128(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Count(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Date(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) DateTime(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Dir(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Duration(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) File(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Float32(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Float64(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Hex(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Hook(name, usage string, f any, opts ...Option) *FlagSet
- func (fs *FlagSet) Int(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Int8(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Int16(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Int32(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Int64(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Map(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Option() option
- func (fs *FlagSet) Path(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) PortRange(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Rate(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Regexp(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Rune(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Size(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Slice(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) String(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Timestamp(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) URL(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) UUID(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Uint(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Uint8(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Uint16(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Uint32(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Uint64(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Var(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) With(flags ...*Flag) *FlagSet
- type FormattedTime
- type HelpLine
- type HelpOption
- type MapConfig
- type OnErr
- type Option
- type PortRange
- type Rate
- type Rule
- type SectionMap
- type Size
- type StringWriter
- type SuggestionError
- type TextMarshalUnmarshaler
- type Type
- type Value
- type Vars
Examples ¶
- Package
- Package (ArgsTest)
- Package (Context)
- Package (DefaultVariables)
- Package (Help)
- Package (Psql)
- Package (PsqlHelp)
- Package (Sections)
- Package (Sources)
- Abbrev
- AllowPlus
- App
- Arg
- Arg (Variadic)
- ArgUsage
- Before
- Bind
- ConfigFiles
- ConfigFiles (SubCommand)
- ConfigFlag
- Context.Parse
- EnvPrefix
- FlagSet.Count
- FlagSet.Date
- FlagSet.Duration
- FlagSet.File
- FlagSet.Hook
- FlagSet.Map
- FlagSet.PortRange
- FlagSet.Size
- FlagSet.Slice
- FlagSet.URL
- From
- From (Args)
- From (Escaping)
- From (Rules)
- From (Tags)
- From (UnescapedComma)
- From (Values)
- Help
- HelpValue
- Hidden
- InheritedFlags
- Key
- LetterClusters
- Local
- NegateBools
- NewContext
- NoArg
- OnlyOneOf
- OptionalValue
- Required
- Run
- RunError
- Sections
- Size.Format
- Special
- StopAtArg
- Strftime
- Sub
- Sub (Help)
- TypeFor
- Valid
- Version
Constants ¶
const ( B = 1 KB = 1_000 MB = 1_000_000 GB = 1_000_000_000 TB = 1_000_000_000_000 PB = 1_000_000_000_000_000 EB = 1_000_000_000_000_000_000 KiB = 1_024 MiB = 1_048_576 GiB = 1_073_741_824 TiB = 1_099_511_627_776 PiB = 1_125_899_906_842_624 EiB = 1_152_921_504_606_846_976 )
Byte sizes.
Variables ¶
var ( // DefaultLookup retrieves keys from the [Context]'s config loaders. DefaultLookup = func(ctx *Context, typ ConfigType, key string) (any, error) { if ctx.Override != nil { switch v, ok, err := ctx.Override(typ, key); { case err != nil: return nil, err case ok: return v, nil } } if ctx.Loader != nil { switch v, ok, err := ctx.Loader(ctx, typ, key); { case err != nil: return nil, err case ok: return v, nil } } return nil, nil } // DefaultInterpolate is the default interpolation func. DefaultInterpolate = InterpolateVar // DefaultOps are default ops used by [InterpolateVar]. DefaultOps = map[string]func(string, string) (string, error){ "#": func(s, v string) (string, error) { return trimPattern(s, v, true, false) }, "##": func(s, v string) (string, error) { return trimPattern(s, v, true, true) }, "%": func(s, v string) (string, error) { return trimPattern(s, v, false, false) }, "%%": func(s, v string) (string, error) { return trimPattern(s, v, false, true) }, "^": func(s, v string) (string, error) { return casePattern(s, v, unicode.ToUpper, false) }, "^^": func(s, v string) (string, error) { return casePattern(s, v, unicode.ToUpper, true) }, ",": func(s, v string) (string, error) { return casePattern(s, v, unicode.ToLower, false) }, ",,": func(s, v string) (string, error) { return casePattern(s, v, unicode.ToLower, true) }, "/": func(s, v string) (string, error) { str, rep, ok := strings.Cut(v, "/") if !ok { return "", fmt.Errorf("%w %q: missing /", ErrInvalidOp, v) } re, err := regexp.Compile(str) if err != nil { return "", fmt.Errorf("%w invalid regexp %q: %w", ErrInvalidOp, str, err) } if m := re.FindStringIndex(s); m != nil { return string(slices.Replace([]byte(s), m[0], m[1], []byte(rep)...)), nil } return s, nil }, "//": func(s, v string) (string, error) { str, rep, ok := strings.Cut(v, "/") if !ok { return "", fmt.Errorf("%w %q: missing /", ErrInvalidOp, v) } re, err := regexp.Compile(str) if err != nil { return "", fmt.Errorf("%w invalid regexp %q: %w", ErrInvalidOp, str, err) } return re.ReplaceAllString(s, rep), nil }, ":": func(s, idx string) (string, error) { r := []rune(s) offStr, lenStr, hasLen := strings.Cut(idx, ":") off, ok := parseIndex(offStr) if !ok { return "", fmt.Errorf("%w offset %q", ErrInvalidOp, idx) } if off < 0 { off += len(r) } if off < 0 || len(r) < off { return "", nil } end := len(r) if hasLen { n, ok := parseIndex(lenStr) switch { case !ok: return "", fmt.Errorf("%w length %q", ErrInvalidOp, idx) case 0 <= n: end = min(off+n, len(r)) default: if end += n; end < off { return "", fmt.Errorf("%w length %q: the end is before the offset", ErrInvalidOp, idx) } } } return string(r[off:end]), nil }, ":-": func(s, v string) (string, error) { if s == "" { return v, nil } return s, nil }, "|": func(s, v string) (string, error) { f, ok := DefaultFilters[strings.TrimSpace(v)] if !ok { return "", fmt.Errorf("%w: %q", ErrInvalidFilter, v) } return f(s), nil }, "||": func(s, v string) (string, error) { if s == "" { return v, nil } return s, nil }, } // DefaultOpFormatFunc is the default op format func used by [InterpolateVar]. DefaultOpFormatFunc = func(format string, v any) (any, error) { return fmt.Sprintf(format, v), nil } // DefaultFilters are default filters used by [InterpolateVar]. DefaultFilters = map[string]func(string) string{ "lower": strings.ToLower, "upper": strings.ToUpper, "camel": strcase.ForceCamelIdentifier, "snake": strcase.ToSnake, "ident": strcase.ToIdentifier, "kebab": strcase.ToKebab, "trim": strings.TrimSpace, "base": filepath.Base, "dir": filepath.Dir, "md5": func(s string) string { b := md5.Sum([]byte(s)) return fmt.Sprintf("%x", string(b[:])) }, "sha1": func(s string) string { b := sha1.Sum([]byte(s)) return fmt.Sprintf("%x", string(b[:])) }, "sha256": func(s string) string { b := sha256.Sum256([]byte(s)) return fmt.Sprintf("%x", string(b[:])) }, "sha512": func(s string) string { b := sha512.Sum512([]byte(s)) return fmt.Sprintf("%x", string(b[:])) }, } )
var ( // DefaultContext is the default [context.Context]. DefaultContext = context.Background() // DefaultStructTagName is the default struct tag name used in // [From]/[FlagsFrom] and other funcs. DefaultStructTagName = "ox" // DefaultLayout is the default timestamp layout used for formatting and // parsing [Time] values. DefaultLayout = time.RFC3339 // DefaultStripGoTestFlags when enabled strips Go's `-test.` prefix'd // flags. DefaultStripGoTestFlags = true // DefaultWrapWidth is the default wrap width. DefaultWrapWidth = 95 // DefaultWrapTo wraps a line of text, split into sections by "\n\n", using // [Wrap], emitting the output to a writer. DefaultWrapTo = func(w io.StringWriter, s string, wrapWidth, prefixWidth int) { for i, line := range strings.Split(s, "\n\n") { if i != 0 { _, _ = w.WriteString("\n\n") _, _ = w.WriteString(strings.Repeat(" ", prefixWidth)) } _, _ = w.WriteString(Wrap(line, wrapWidth, prefixWidth)) } } // DefaultWidth returns the width of a string used by [Wrap]. DefaultWidth = func(s string) int { return len(s) } // DefaultFlagNameMapper is the default flag name mapper. DefaultFlagNameMapper = func(s string) string { return strings.ReplaceAll(strcase.CamelToSnake(s), "_", "-") } // DefaultVersionTrimPrefix is used by [DefaultVersionMapper] to trim the // `v` prefix on build version. DefaultVersionTrimPrefix = true // DefaultVersion is the default version func. DefaultVersion = func(ctx *Context) error { var name string if ctx != nil && ctx.Root != nil { name = ctx.Root.Name } var ver string switch { case ctx != nil && ctx.Exec != nil && ctx.Exec.Version != "": ver = ctx.Exec.Version case ctx != nil && ctx.Root != nil && ctx.Root.Version != "": ver = ctx.Root.Version default: ver = BuildVersion() } name, ver = DefaultVersionMapper(name, ver) var w io.Writer if ctx != nil { w = ctx.Stdout } if w == nil { w = os.Stdout } _, _ = fmt.Fprintln(w, name, ver) return ErrExit } // DefaultVersionMapper maps the passed name, version. DefaultVersionMapper = func(name, ver string) (string, string) { if name == "" { name = filepath.Base(os.Args[0]) if runtime.GOOS == "windows" && strings.HasSuffix(strings.ToLower(name), ".exe") { name = name[:len(name)-4] } } if DefaultVersionTrimPrefix && regexp.MustCompile(`^v[0-9]+\.`).MatchString(ver) { ver = strings.TrimPrefix(ver, "v") } return name, ver } // DefaultContinueHandler is the default continue handler used by // [Run]/[RunContext]. DefaultContinueHandler = func(ctx *Context) func(*Command, error) bool { var onErr OnErr if ctx != nil { onErr = ctx.OnErr } return func(cmd *Command, err error) bool { if cmd != nil { onErr = cmd.OnErr } return err == nil || onErr == OnErrContinue } } // DefaultEmitExecExitError toggles emitting captured stderr output from // [exec.ExitError] to the [Context.Stderr]. DefaultEmitExecExitError = false // DefaultErrorHandler is the default error handler used by // [Run]/[RunContext]. DefaultErrorHandler = func(ctx *Context) func(error) bool { return func(err error) bool { switch { case errors.Is(err, ErrExit): case ctx.OnErr == OnErrContinue: return false case ctx.OnErr == OnErrExit: var w io.Writer = os.Stderr if ctx.Stderr != nil { w = ctx.Stderr } code := 1 if v, ok := err.(interface{ ErrorCode() int }); ok { code = v.ErrorCode() } // build error message var sb strings.Builder _, _ = sb.WriteString(strings.TrimRightFunc(err.Error(), unicode.IsSpace)) if e, ok := asExitError(err); ok && ctx.EmitExecExitError && len(e.Stderr) != 0 { code = e.ExitCode() if b := bytes.TrimRightFunc(e.Stderr, unicode.IsSpace); len(b) != 0 { sb.WriteString(": ") sb.Write(b) } } _, _ = fmt.Fprintf(w, text.ErrorMessage, sb.String()) if v, ok := err.(interface{ ErrorDetails() string }); ok { _, _ = fmt.Fprint(w, v.ErrorDetails()) } ctx.Exit(code) case ctx.OnErr == OnErrPanic: ctx.Panic(err) } return true } } // DefaultSuggestionsEnabled sets whether command name suggestions are // given. DefaultSuggestionsEnabled = true // DefaultMaxDist is the default maximum Levenshtein distance for // suggestions and for the corrections of completion. 0 turns off the // distance match. [MaxDist] changes it for one command. DefaultMaxDist = 2 // DefaultFoldCase when true makes suggestions, and the completion of // command and flag names, compare names without case. The parse of a // command name always compares with case. Set it to false to compare // with case. DefaultFoldCase = true // DefaultNegatePrefix is the prefix of the negated form of a bool flag, // such as `--no-debug` for `--debug`, when [NegateBools] gets no prefix // and for a flag with [Negatable]. DefaultNegatePrefix = "no" // DefaultFlagWidth is the default minimum flag width. Does not include the // padding. DefaultFlagWidth = 8 // DefaultCommandWidth is the default minimum command width. DefaultCommandWidth = 6 // DefaultCompTemplates are the default completion templates. DefaultCompTemplates = templates // DefaultCompName is the name for the completion script hook. DefaultCompName = "__complete" // DefaultCompNameNoDesc is the name for the completion script hook without // descriptions. DefaultCompNameNoDesc = "__completeNoDesc" // DefaultCompEnvNoDescName is the name for the environment variable for // disabling completion descriptions. DefaultCompEnvNoDescName = "COMPLETION_DESCRIPTIONS" // DefaultCompActiveHelpSuffix is the suffix of the environment variable // that turns off ActiveHelp for a program, such as APP_ACTIVE_HELP=0. DefaultCompActiveHelpSuffix = "_ACTIVE_HELP" // DefaultCompActiveHelpMarker starts a completion that is a line of // ActiveHelp, which the completion scripts show as help and not as a // completion. See [NewActiveHelp]. DefaultCompActiveHelpMarker = "_activeHelp_ " // DefaultCompWrite is the default completion write func, that writes the // completion script from the passed template. DefaultCompWrite = func(ctx *Context, cmd *Command, noDescriptions bool, shell, templ string) error { rootName := cmd.RootName() varName := regexp.MustCompile(`[^A-Za-z0-9_]`).ReplaceAllString(rootName, "_") activeHelp := compActiveHelpVar(rootName) compName := DefaultCompName if noDescriptions { compName = DefaultCompNameNoDesc } _, _ = fmt.Fprintf( ctx.Stdout, templ, rootName, varName, compName, activeHelp, ) return ErrExit } // DefaultComp is the default completion func. DefaultComp = func(ctx *Context) error { noDescriptions := ctx.Args[0] == DefaultCompNameNoDesc for _, name := range []string{ctx.Root.Name + "_" + DefaultCompEnvNoDescName, DefaultCompEnvNoDescName} { if s := os.Getenv(name); s != "" { if b, err := asBool(s); err == nil { noDescriptions = !b } } } comps, dir, err := ctx.Comps() if err != nil { _, _ = fmt.Fprintf(ctx.Stderr, text.ErrorMessage, err) } if os.Getenv(compActiveHelpVar(ctx.Root.Name)) == "0" { comps = slices.DeleteFunc(comps, isActiveHelp) } for _, comp := range comps { if !noDescriptions && comp.Usage != "" { _, _ = fmt.Fprintln(ctx.Stdout, comp.Name+"\t"+comp.Usage) } else { _, _ = fmt.Fprintln(ctx.Stdout, comp.Name) } } _, _ = fmt.Fprintf(ctx.Stdout, ":%d\n", dir) return ErrExit } // DefaultStripTestFlags strips flags starting with `-test.` from args. DefaultStripTestFlags = func(args []string) []string { if !DefaultStripGoTestFlags { return args } var v []string for i := 0; i < len(args); i++ { switch hasPrefix := strings.HasPrefix(args[i], "-test."); { case hasPrefix && !strings.Contains(args[i], "="): i++ continue case hasPrefix: continue } v = append(v, args[i]) } return v } // DefaultSizePrec is the default [Size] display precision. DefaultSizePrec = -2 // DefaultRatePrec is the default [Rate] display precision. DefaultRatePrec = -2 // DefaultRateUnit is the default [Rate] unit used to display the rate, if // none is specified or when precision is negative. DefaultRateUnit = time.Second )
var ( // DefaultMaxPathLinks are the max symlinks to follow in [Path]. DefaultMaxPathLinks = 16 // DefaultGetwd is the func used to read the working directory by [Path]. // Normally [os.Getwd]. DefaultGetwd = os.Getwd // DefaultLstat is the func used to lstat a path by [Path]. Normally // [os.Lstat]. DefaultLstat = os.Lstat // DefaultReadlink is the func used to read a link by [Path]. Normally // [os.Readlink]. DefaultReadlink = os.Readlink )
var DefaultEnvLoader = func(_ *Context, key string) (any, bool, error) { if s, ok := os.LookupEnv(key); ok { return s, true, nil } return "", false, ErrUnknownKey }
DefaultEnvLoader is the default environment config key loader.
var DefaultKeyLoader = func(ctx *Context, key string) (any, bool, error) { var f func() (string, error) switch key { case "PWD": f = DefaultGetwd case "HOME": f = userHomeDir case "USER": f = func() (string, error) { u, err := user.Current() if err != nil { return "", err } return u.Username, nil } case "APPNAME": return ctx.Root.Name, true, nil case "APPVERSION": return ctx.Root.Version, true, nil case "CONFIG": f = userConfigDir case "APPCONFIG": f = func() (string, error) { dir, err := userConfigDir() if err != nil { return "", err } return filepath.Join(dir, ctx.Root.Name), nil } case "CACHE": f = userCacheDir case "STATE": f = UserStateDir case "APPCACHE": f = func() (string, error) { dir, err := userCacheDir() if err != nil { return "", err } return filepath.Join(dir, ctx.Root.Name), nil } case "APPSTATE": f = func() (string, error) { dir, err := UserStateDir() if err != nil { return "", err } return filepath.Join(dir, ctx.Root.Name), nil } case "NUMCPU": return strconv.Itoa(runtime.NumCPU()), true, nil case "NUMCPU2": return strconv.Itoa(runtime.NumCPU() + 2), true, nil case "NUMCPU2X": return strconv.Itoa(runtime.NumCPU() * 2), true, nil case "ARCH": return runtime.GOARCH, true, nil case "OS": return runtime.GOOS, true, nil default: return nil, false, ErrUnknownKey } s, err := f() if err != nil { return "", false, err } return s, true, nil }
DefaultKeyLoader is the default config key loader.
The following keys are recognized:
$PWD - the current working directory, taken from [os.Getwd] (ex: /some/path) $HOME - the current user's home directory, taken from [os.UserHomeDir] (ex: ~/) $USER - the current user's user name, taken from [user.Current] (ex: user) $APPNAME - the root command's name (ex: appName) $APPVERSION - the root command's version (ex: v0.1.0) $CONFIG - the current user's config directory, taken from [os.UserConfigDir] (ex: ~/.config) $APPCONFIG - the current user's config directory, with the root command's name added as a subdir (ex: ~/.config/appName) $CACHE - the current user's cache directory, taken from [os.UserCacheDir] (ex: ~/.cache) $STATE - the current user's state directory, taken from [UserStateDir] (ex: ~/.local/state) $APPCACHE - the current user's cache directory, with the root command's name added as a subdir (ex: ~/.cache/appName) $APPSTATE - the current user's state directory, with the root command's name added as a subdir (ex: ~/.local/state/appName) $NUMCPU - the value of [runtime.NumCPU] (ex: 4) $NUMCPU2 - the value of [runtime.NumCPU], plus 2 (ex: 6) $NUMCPU2X - the value of [runtime.NumCPU], times 2 (ex: 8) $ARCH - the value of [runtime.GOARCH] (ex: amd64) $OS - the value of [runtime.GOOS] (ex: windows)
var DefaultLoader = func(ctx *Context, typ ConfigType, key string) (any, bool, error) { if typ != "" { if loader, ok := loaders[typ]; ok { return loader(ctx, key) } return nil, false, ErrUnknownLoader } for _, typ := range loaderOrder { if loader, ok := loaders[typ]; ok { switch v, ok, err := loader(ctx, key); { case errors.Is(err, ErrUnknownKey), errors.Is(err, ErrInvalidKey): continue case err != nil: return nil, false, err case ok: return v, true, nil } } } return nil, false, ErrUnknownKey }
DefaultLoader is the default config loader.
Functions ¶
func AddHelpFlag ¶
AddHelpFlag recursively adds a `--help` flag for all commands in the command tree, copying the command's CommandHelp.Sort, CommandHelp.CommandSort, CommandHelp.MaxDist and CommandHelp.Column settings, and CommandHelp.InheritedFlags when it is true.
func AppFrom ¶
AppFrom runs the program that v describes, as Run does. v is a pointer to a struct, and App builds the command tree from it. AppFrom adds Defaults, so the program gets help, a version and completion. The options in opts come after.
Pass App to RunError to choose the context.Context, or to get the error.
func AppendRate ¶
AppendRate appends the formatted rate to b.
func AppendSize ¶
AppendSize appends the formatted size to b. A precision below -1 will format the value to the fixed precision then trims any trailing '.' / '0'. Formats the value based on the verb (see below). When space is true, a space will be appended between the formatted size and the suffix. A value without a suffix gets no space.
The verbs q and Q write the exact size, as Kubernetes writes a quantity. Each writes an integer with the largest suffix that divides the size, so that no byte is lost: q with a binary suffix (Ki, Mi, Gi, Ti, Pi, Ei) and Q with a decimal suffix (k, M, G, T, P, E). A size that no suffix divides has no suffix. The precision does not apply to them. For example, 1.5 GiB is 1536Mi with q, and 6,000,000,000 bytes is 6G with Q.
Supported verbs:
d/D - size in bytes (ex: 12345678) f/F - size in best fitting *B/*iB (ex: 999 B, 1.1 KiB) and always with a space z/Z - size in best fitting *B/*iB (ex: 999 B, 1.1 KiB) e/E - size in best fitting */*i (ex: 12.5G, 11.1Gi) q/Q - exact size in */*i, as a Kubernetes quantity (ex: 1536Mi, 6G) k/K - size in KB/KiB (ex: 0.9 kB, 2.3 KiB) m/M - size in MB/MiB (ex: 1.2345 MB) g/G - size in GB/GiB (ex: 1 GiB) t/T - size in TB/TiB (ex: 4.5 TiB) b/P - size in PB/PiB (ex: 4.5 PiB) -- must use b, as p is reserved for pointers s/S - same as f/F v/V - same as f/F
func ApplyPost ¶
ApplyPost applies post options to the command, then the funcs of each Extend option.
func BuildVersion ¶
func BuildVersion() string
BuildVersion returns the version of the main module from the build info, or "(devel)".
func FormatRate ¶
FormatRate formats a byte rate.
func FormatSize ¶
FormatSize formats a byte size.
func InterpolateVar ¶
InterpolateVar interpolates variables based on registered config loaders defined on the Context.
Interplates variables of the form:
$KEY
${KEY}
${KEY|filter}
${KEY||default|filter}
$TYPE{KEY}
$TYPE{KEY|filter}
$TYPE{KEY||default|filter}
${TYPE::KEY}
${TYPE::KEY|filter}
${TYPE::KEY||default|filter}
${KEY%str}
${KEY%%str}
${KEY@str}
${KEY^str}
${KEY^^str}
${KEY/str/rep}
${KEY//str/rep}
${KEY:offset}
${KEY:offset:length}
${KEY^}
${KEY^^}
${KEY,}
${KEY,,}
Where the above are:
KEY - the key name TYPE - the config loader type, or ANY for the first loader that has the key default - a default value filter - a filter defined in [DefaultFilters] str - a string rep - a replacement string offset - a offset into the string; negative values are allowed length - an end index, as in s[offset:length]; see D19
See DefaultKeyLoader for the list of specially recognized keys.
Built-in filters (see DefaultFilters):
lower - lower case upper - upper case camel - camel case snake - snake case ident - ident case kebab - kebab case trim - trim space base - file path base dir - file path dir md5 - md5 hash sha1 - sha1 hash sha256 - sha256 hash sha512 - sha512 hash
Built-in Bash-like string variable operators (see DefaultOps):
#, ## - remove the shortest or the longest prefix that matches a glob %, %% - remove the shortest or the longest suffix that matches a glob ^, ^^ - upper case the first character, or each one, that matches a glob ,, ,, - lower case the first character, or each one, that matches a glob /, // - replace the first match, or each match, of a regexp : - substring, from an offset and with a length, as in bash :-, || - a default for an empty value | - a filter
A special Go formatting operator, @, is also provided that applies Go's standard formatting. That is, a key such as `${KEY@%f}` will be interpolated as the equivalent of `fmt.Sprintf("%f", <key value>)`.
Interpolation examples:
$APPNAME
${APPNAME|upper}
$ENV{MY_VALUE|lower||default_value}
${env::MY_VALUE|lower||default_value}
$YAML{a.key.path|upper}
${yaml::a.key.path||default_value|upper}
${\$.store.book[*].author}
${APPVERSION#v}
${my_rate@%e}
${MY_VALUE//foo/bar||default_value|upper}
${env::MY_VALUE%foo|upper}
func NewCompFlags ¶
NewCompFlags adds `--completion-script-<type>` flags to a command, or hooking any existing flags with `Special == "hook:comp:<type>"`.
func NewHelpFlag ¶
NewHelpFlag adds a `--help` flag to the command, or hooks the command's flag with `Special == "hook:help"`.
func NewSuggestionError ¶
NewSuggestionError creates a suggestion error.
func NewTime ¶
NewTime returns a Value func for a FormattedTime value.
func NewVersion ¶
NewVersion adds a `version` sub command to the command.
func NewVersionFlag ¶
NewVersionFlag adds a `--version` flag to the command, or hooks the command's flag with `Special == "hook:version"`.
func ParseFlagLong ¶
ParseFlagLong parses a long flag ('--arg' '--arg v' '--arg k=v' '--arg=' '--arg=v'). With Abbrev, a unique prefix of the name of a flag gives the flag. The negated form of a bool flag ('--no-arg') sets the flag to false, and takes no value. See NegateBools.
func ParseFlagPlus ¶ added in v0.5.0
ParseFlagPlus parses the plus form of short flags ('+a' '+a v' '+av' '+abc'), as bash takes `+o name` and `+ex`. Each letter must name a flag with AllowPlus. A plain bool flag gets false, and takes no value. Any other flag takes its value as ParseFlagShort does, and its hook reads Context.IsPlus as true.
func ParseFlagShort ¶
ParseFlagShort parses short flags ('-a' '-aaa' '-av' '-a v' '-a=' '-a=v'). With LetterClusters, a letter that takes a value takes it only from the next word.
func RegisterBinaryType ¶
func RegisterBinaryType[T BinaryMarshalUnmarshaler](f func() (T, error))
RegisterBinaryType registers a new binary type.
func RegisterConfigFormat ¶
func RegisterConfigFormat(typ ConfigType, decode func([]byte) (Config, error), exts ...string)
RegisterConfigFormat registers the decoder of a config file format, for the file extensions that follow, without the dot. It also registers a config loader for typ, so that ${typ::key} reads the files of the format. The root package registers JSONT. The yaml, toml and hcl modules register YAMLT, TOMLT and HCLT.
func RegisterConfigLoader ¶
RegisterConfigLoader registers a config loader, which answers the keys of a config type in interpolation, such as ${env::HOME}. A config file format registers its loader with RegisterConfigFormat.
func RegisterConfigLoaderOrder ¶
func RegisterConfigLoaderOrder(order ...ConfigType)
RegisterConfigLoaderOrder sets the loader order.
func RegisterDoc ¶
RegisterDoc registers the doc comment of the struct type T, and the doc comment of each of its fields, by the name of the field. App and From read them. The tool `github.com/xo/ox/cmd/oxdoc` writes a call for each struct type of a program, from `go generate`, because Go keeps no doc comment in a program.
func RegisterTextType ¶
func RegisterTextType[T TextMarshalUnmarshaler](f func() (T, error))
RegisterTextType registers a new text type.
func RegisterType ¶
RegisterType registers a type.
func RegisterTypeName ¶
RegisterTypeName registers a type name.
func Run ¶
func Run(opts ...Option)
Run creates and builds the execution Context based on the passed [Option]s. Accepts any ContextOption, CommandOption or CommandFlagOption. After building a execution Context and root Command, either os.Args or the provided Args will be Parse'd and validated.
After args have been parsed and validated, Context will have its Context.Exec set to either the root command, or to the user's requested command. The determined Command.Exec will be executed, or if it was not set, then the Command.Help's will be written to the Context.Stdout.
See RunContext to pass a context.Context to the executed command, or set the DefaultContext.
Example ¶
ExampleRun builds a command by hand, with ox.Flags, and reads the values of the flags in the exec func.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("greet", "say hello"),
ox.Defaults(),
ox.Flags().
String("name", "the name to greet", ox.Short("n"), ox.Default("world")).
Int("times", "the number of greetings", ox.Short("t"), ox.Default("1")),
ox.Exec(func(ctx context.Context) error {
for range otx.Int(ctx, "times") {
fmt.Println("hello", otx.String(ctx, "name"))
}
return nil
}),
// a program leaves out Args, and ox reads os.Args
ox.Args("--name", "ken", "-t", "2"),
)
}
Output: hello ken hello ken
func RunContext ¶
RunContext creates a Context and builds a execution Context and root Command based on the passed options. Accepts any ContextOption, CommandOption or CommandFlagOption. After building a execution Context and root Command, either os.Args or the provided Args will be Parse'd and validated.
After args have been parsed and validated, Context will have its Context.Exec set to either the root command, or to the user's requested command. The determined Command.Exec will be executed, or if it was not set, then the Command.Help's will be written to the Context.Stdout.
func RunError ¶
RunError creates a Context from the options, as RunContext does, then parses, validates and runs the command. It returns the first error, and does not write it, exit or panic, whatever Context.OnErr is. So the program chooses the message and the exit status. When help, the version or a completion stops the run with ErrExit, RunError returns nil.
Example ¶
ExampleRunError runs a command and returns its error, so that the program chooses the message and the exit status.
package main
import (
"context"
"errors"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) error {
return ox.RunError(
context.Background(),
ox.Usage("greet", "say hello"),
ox.Flags().
String("name", "the name to greet", ox.Default("world")),
ox.ValidArgs(0, 0),
ox.Exec(func(ctx context.Context) error {
fmt.Println("hello", otx.String(ctx, "name"))
return nil
}),
ox.Args(args...),
)
}
fmt.Println(run("--name", "ken"))
err := run("--nam", "ken")
fmt.Println(errors.Is(err, ox.ErrUnknownFlag), err)
}
Output: hello ken <nil> true --nam: unknown flag
func UserStateDir ¶
UserStateDir returns the user's state directory.
Linux/BSD: $XDG_STATE_HOME or ~/.local/state macOS: $XDG_STATE_HOME, or ~/Library/Application Support Windows: %LOCALAPPDATA% or %USERPROFILE%\AppData\Local.
func WithContext ¶
WithContext adds a Context to the parent context.Context.
Types ¶
type Argument ¶ added in v0.2.0
type Argument struct {
// Flag holds the name, the usage, the type, the default, the validators,
// the binds and the completion of the argument, as for a flag.
Flag *Flag
// Optional is true when the command runs without the argument. An
// argument with a default is optional.
Optional bool
}
Argument is a positional argument of a command, from Arg.
func NewArgument ¶ added in v0.2.0
NewArgument creates a positional argument. It applies each ArgOption, such as Optional, to the argument, and each other option, such as a Type, Valid or Bind, to its Argument.Flag, as NewFlag does.
func (*Argument) SpecString ¶ added in v0.2.0
SpecString returns the spec of the argument in the usage line of help, such as `file`, `[file]`, `file...` or `[file...]`. The name is the Flag.Spec of the argument, or its name.
type BinaryMarshalUnmarshaler ¶
type BinaryMarshalUnmarshaler interface {
encoding.BinaryMarshaler
encoding.BinaryUnmarshaler
}
BinaryMarshalUnmarshaler is the binary marshal interface.
type Binder ¶
Binder is the interface for binding values.
func NewBindRef ¶
NewBindRef binds reflect.Value value and its set flag.
type Command ¶
type Command struct {
// Parent is the command's parent.
Parent *Command
// Exec is the command's exec func.
Exec ExecFunc
// Before is the func that runs before the exec func of the command, and
// of each sub command below it. See [Before].
Before ExecFunc
// After is the func that runs after the exec func of the command, and of
// each sub command below it. See [After].
After ExecFunc
// Name is the command's name.
Name string
// Usage is the command's usage.
Usage string
// Aliases are the command's aliases.
Aliases []string
// Suggested are the command's suggested names.
Suggested []string
// Flags are the command's flags.
Flags *FlagSet
// Commands are the command's sub commands. The completion command of
// [Comp] builds its sub commands, one for each shell, the first time
// that a method of [Command] reads them, such as [Command.Command] or
// [Command.Lookup], so that a program that does not complete builds
// none (B55). Read the sub commands with such a method.
Commands []*Command
// Args are the command's argument validation func's.
Args []func([]string) error
// OnErr indicates whether to continue, panic, or to error when
// flag/argument parsing fails.
OnErr OnErr
// Help is the command's help emitter.
Help io.WriterTo
// Section is the help section.
Section int
// Comp enables completion for the command.
Comp bool
// Hidden indicates the command is hidden from help output.
Hidden bool
// Deprecated indicates the command is deprecated.
Deprecated bool
// Special is the special value.
Special string
// Version is the version string.
Version string
// ConfigFiles are the config files to read, in order. Each path is
// interpolated. Only the root command reads them.
ConfigFiles []string
// ConfigRequired makes it an error when no config file exists.
ConfigRequired bool
// EnvPrefix is the prefix of the environment variables that fill the
// flags, such as "APP" for APP_LOG_LEVEL.
EnvPrefix string
// ValidArgs are the allowed values of the positional arguments, from
// [ValidArgs]. Completion offers them.
ValidArgs []string
// CompFunc is the func that completes the positional arguments. See
// [CompFunc].
CompFunc func(ctx *Context, toComplete string) ([]Completion, CompDirective, error)
// FlagGroups are the rules between the flags of the command, from
// [OnlyOneOf], [AllOrNoneOf] and [AtLeastOneOf].
FlagGroups []FlagGroup
// NegateBools are the prefixes of the negated forms of the bool flags of
// the command tree, such as "no" for `--no-debug`. Only the root command
// reads them. See [NegateBools].
NegateBools []string
// Positional are the command's positional arguments, in order. See
// [Arg].
Positional []*Argument
// StopAtArg makes each argument after the first positional argument of
// the command a positional argument, even one that starts with `-`. See
// [StopAtArg].
StopAtArg bool
// Abbrev lets the command line give a long flag by a unique prefix of
// its name. A sub command inherits it. See [Abbrev].
Abbrev bool
// PlusWords reads each word that starts with `+` as plus flags, and
// skips a lone `+`, as bash does. See [PlusWords].
PlusWords bool
// LetterClusters reads short letters as bash does: a letter that takes a
// value takes it only from the next word. See [LetterClusters].
LetterClusters bool
// BashLongFlags reads long flags as bash does: only before the first
// short flag, and without a value after `=`. See [BashLongFlags].
BashLongFlags bool
// contains filtered or unexported fields
}
Command is a command.
func NewCommand ¶
NewCommand creates a new command.
func Parse ¶
Parse parses flags and args into context.
A program can find the kind of a parse error with errors.Is. Parse returns an error that wraps one of these:
- ErrUnknownFlag when a flag is not defined for the command.
- ErrAmbiguousFlag when a prefix of a long flag matches more than one flag, with Abbrev.
- ErrMissingArgument when a flag that takes an argument has none.
- ErrInvalidValue when a flag cannot be set from its argument, such as a value that does not convert to the type of the flag, a value that Valid does not allow, or a value that a bound variable cannot hold.
Context.Parse also returns ErrInvalidValue when a value from the environment, a config file or a default cannot be set, and ErrInvalidConfig when a config file cannot be decoded. An error that a hook of the program returns passes through as it is, so the program finds it with errors.Is. Context.Validate, which runs after the parse, returns ErrInvalidArgCount when the command has too many or too few args for ValidArgs. These four errors stay stable, because usql depends on them. Context.Validate also returns ErrRequiredFlag for a flag with Required that has no value, and ErrOnlyOneOf, ErrAllOrNoneOf or ErrAtLeastOneOf for a group of flags that breaks its rule.
func (*Command) CommandSpecial ¶
CommandSpecial returns the sub command with the special value.
func (*Command) CompCommands ¶
func (cmd *Command) CompCommands(name string, hidden, deprecated bool) ([]Completion, CompDirective)
CompCommands returns command completions for the command.
func (*Command) CompFlags ¶
func (cmd *Command) CompFlags(name string, hidden, deprecated, short bool) ([]Completion, CompDirective)
CompFlags returns flag completions for the command. It offers the name, the aliases, the hidden aliases and the negated forms of each flag (see NegateBools), and never a deprecated alias.
func (*Command) CompPlus ¶ added in v0.5.0
func (cmd *Command) CompPlus(name string, hidden, deprecated bool) ([]Completion, CompDirective)
CompPlus returns the plus forms of the short flags of the command and of its parents that start with name, such as `+e` and `+o`. Only a flag with AllowPlus has a plus form.
func (*Command) Flag ¶
Flag finds a flag from the command or the command's parents. It does not find a local flag of a parent. See Flag.Local.
func (*Command) FlagSpecial ¶
FlagSpecial returns the flag with a special value.
func (*Command) HelpContext ¶
HelpContext adds the context to the command's help.
func (*Command) NegatedNames ¶ added in v0.3.0
NegatedNames returns the negated forms of the long name of the flag g in the command, such as "no-debug" for --debug, without the leading dashes. It returns nil when g has no negated form in the command. See NegateBools and Negatable.
func (*Command) SubSpecial ¶
SubSpecial returns the sub command with a special value.
func (*Command) Suggest ¶
Suggest returns a SuggestionError if there is a matching sub command within the command's help distance.
func (*Command) UsageString ¶
UsageString returns the help of the command, as `--help` writes it. It expands no default, because it has no Context. Write Command.HelpContext to a strings.Builder to expand them.
func (*Command) Validate ¶
Validate validates the passed args, with the funcs of Command.Args, then with the count of Command.Positional.
func (*Command) WalkFlags ¶
WalkFlags returns an iterator for all flags on the command and its parents. It skips a local flag of a parent, because the command does not inherit it. See Flag.Local.
type CommandFlagOption ¶
type CommandFlagOption = Option
CommandFlagOption are Option's that apply to either a Command or Flag.
func Aliases ¶
func Aliases(aliases ...string) CommandFlagOption
Aliases is a Command/Flag option to add aliases for the command/flag.
func CompFunc ¶
func CompFunc(f func(ctx *Context, toComplete string) ([]Completion, CompDirective, error)) CommandFlagOption
CompFunc is a Command/Flag option to set the func that completes the positional arguments of the command, or the value of the flag. f returns the completions for toComplete, the word under the cursor. ctx.Exec is the command, ctx.Vars holds the flags parsed so far, and ctx.Args holds the positional arguments before toComplete.
Completion keeps only the results that start with toComplete, unless f returns CompNoFilter. Completion corrects no result. If f returns no completions and does not return CompNoFileComp, the shell completes file names.
func Deprecated ¶
func Deprecated(deprecated bool) CommandFlagOption
Deprecated is a Command/Flag option to set the command/flag's deprecated.
func Help ¶
func Help(opts ...Option) CommandFlagOption
Help is a Command/Flag option to add help output to a root command. By default, adds a `--help` flag to all commands in the command tree including the root command.
Additionalyl, a `help` subcommand will be added to the root command if the root command has at least one other subcommand not named `help`.
Example ¶
ExampleHelp sets the banner, the usage spec, the examples and the footer of the help.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("fetch", "fetch a URL"),
ox.Defaults(
ox.Banner("fetch gets a URL, and writes the body."),
ox.Spec("[OPTION]... URL"),
ox.Example(" fetch https://example.com\n fetch -o out.html https://example.com"),
ox.Footer("Report bugs to <bugs@example.com>."),
),
ox.Flags().
String("output", "the output file", ox.Short("o"), ox.Spec("FILE")),
ox.Args("--help"),
)
}
Output: fetch gets a URL, and writes the body. Usage: fetch [OPTION]... URL Examples: fetch https://example.com fetch -o out.html https://example.com Flags: -o, --output FILE the output file -v, --version show version, then exit -h, --help show help, then exit Report bugs to <bugs@example.com>.
func Hidden ¶
func Hidden(hidden bool) CommandFlagOption
Hidden is a Command/Flag option to set the command/flag's hidden.
Example ¶
ExampleHidden hides a flag and a command from the help. A hidden or a deprecated flag still works on the command line.
package main
import (
"context"
"fmt"
"os"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
ox.Run(
ox.Usage("app", "an app"),
ox.Defaults(),
ox.Flags().
Bool("debug", "debug output", ox.Hidden(true)).
String("old-name", "use --name", ox.Deprecated(true)).
String("name", "the name"),
ox.Sub(
ox.Usage("serve", "serve files"),
),
ox.Sub(
ox.Usage("internal", "internal tools"),
ox.Hidden(true),
),
ox.Exec(func(ctx context.Context) {
fmt.Println("debug:", otx.Bool(ctx, "debug"))
fmt.Println("old-name:", otx.String(ctx, "old-name"))
}),
ox.Args(args...),
// the warning of a deprecated flag goes to standard error
ox.Pipe(os.Stdin, os.Stdout, os.Stdout),
)
}
run("--help")
run("--debug", "--old-name", "x")
}
Output: app an app Usage: app [flags] [command] [args] Available Commands: completion generate completion script for a specified shell help show help for any command serve serve files version show app version information Flags: --name string the name -h, --help show help, then exit Use "app [command] --help" for more information about a command. warning: --old-name is deprecated debug: true old-name: x
func Name ¶
func Name(name string) CommandFlagOption
Name is a Command/Flag option to set the command/flag's name.
type CommandHelp ¶
type CommandHelp struct {
// Context is the evaluation context.
Context *Context
// Command is the target command.
Command *Command
// NoBanner when true will not output the command's banner.
NoBanner bool
// Banner is the command's banner.
Banner string
// NoUsage when true will not output the command's usage.
NoUsage bool
// NoSpec when true will not output the command's usage spec.
NoSpec bool
// Spec is the command's usage spec.
Spec string
// NoCommands when true will not output the command's sub commands.
NoCommands bool
// CommandSort when true will sort commands.
CommandSort bool
// CommandSections are the command's sub command section names.
CommandSections []string
// NoAliases when true will not output the command's aliases.
NoAliases bool
// NoExample when true will not output the command's examples.
NoExample bool
// Example is the command's examples.
Example string
// NoFlags when true will not output the command's flags.
NoFlags bool
// Sort when true will sort flags.
Sort bool
// Sections are the command's flag section names.
Sections []string
// InheritedFlags when true writes the flags that the command inherits
// from its parents, in a section of their own. See [InheritedFlags].
InheritedFlags bool
// Args are the names and the usage of the command's positional
// arguments. See [ArgUsage].
Args []HelpLine
// Column is the column where each description starts. See [HelpColumn].
Column int
NoFooter bool
Footer string
// Hidden includes hidden commands/flags.
Hidden bool
// Deprecated includes deprecated commands/flags.
Deprecated bool
// MaxDist is the maximum Levenshtein distance for suggestions. 0 means
// [DefaultMaxDist], and a negative distance turns off the distance match.
MaxDist int
}
CommandHelp is command help.
func NewCommandHelp ¶
func NewCommandHelp(cmd *Command, opts ...Option) (*CommandHelp, error)
NewCommandHelp creates command help based on the passed options.
func (*CommandHelp) AddAliases ¶
func (help *CommandHelp) AddAliases(w StringWriter)
AddAliases adds the command's aliases.
func (*CommandHelp) AddArgs ¶
func (help *CommandHelp) AddArgs(w StringWriter)
AddArgs adds the usage of the command's positional arguments: each argument of Command.Positional, with its default, then each line of CommandHelp.Args.
func (*CommandHelp) AddBanner ¶
func (help *CommandHelp) AddBanner(w StringWriter)
AddBanner adds the command's banner.
func (*CommandHelp) AddCommands ¶
func (help *CommandHelp) AddCommands(w StringWriter)
AddCommands adds the command's sub commands.
func (*CommandHelp) AddExample ¶
func (help *CommandHelp) AddExample(w StringWriter)
AddExample adds the command's example.
func (*CommandHelp) AddFlags ¶
func (help *CommandHelp) AddFlags(w StringWriter)
AddFlags adds the command's flags.
func (*CommandHelp) AddFooter ¶
func (help *CommandHelp) AddFooter(w StringWriter)
AddFooter adds the command's footer.
func (*CommandHelp) AddInheritedFlags ¶ added in v0.2.0
func (help *CommandHelp) AddInheritedFlags(w StringWriter)
AddInheritedFlags adds the flags that the command inherits from its parents, in a section of their own, when CommandHelp.InheritedFlags is true.
func (*CommandHelp) AddUsage ¶
func (help *CommandHelp) AddUsage(w StringWriter)
AddUsage adds the command's usage.
func (*CommandHelp) FlagUsage ¶ added in v0.3.0
func (help *CommandHelp) FlagUsage(g *Flag) string
FlagUsage returns the usage of the flag that help writes, with the text of its default value unless Flag.NoDefault is set. A required flag gets the text of text.FlagRequired, and not its default, because a default does not count as a value. CommandHelp.Context expands the default. Without a context, the default is as the program wrote it, such as `$HOME/.apprc`.
func (*CommandHelp) SetContext ¶
func (help *CommandHelp) SetContext(ctx *Context)
SetContext sets the context on the command help.
func (*CommandHelp) SpecString ¶ added in v0.3.0
func (help *CommandHelp) SpecString() string
SpecString returns the usage spec of the command, which help writes after the names of the command and its parents, such as `[flags] [command] [args]`. It is CommandHelp.Spec, or the spec of the flags, the sub commands and the arguments of the command.
func (*CommandHelp) WriteTo ¶
func (help *CommandHelp) WriteTo(w io.Writer) (int64, error)
WriteTo satisfies the io.WriterTo interface.
type CommandOption ¶
type CommandOption = Option
CommandOption are Option's that apply to a Command.
func Abbrev ¶ added in v0.2.0
func Abbrev() CommandOption
Abbrev is a Command option to let the command line give a long flag by a unique prefix of its name, as GNU getopt_long does: `--verb` means `--verbose` when no other long flag of the command starts with `verb`. A sub command inherits it.
An exact name always wins over a prefix. A prefix that matches more than one flag fails with ErrAmbiguousFlag, and the error names the flags that it matches. A prefix matches the long names that completion offers: the name, the aliases and the hidden aliases of each flag that the command accepts, including the flags that it inherits. A prefix does not match a hidden flag, a deprecated flag or a deprecated alias, which need their exact name. A short flag needs its exact name too.
Example ¶
ExampleAbbrev takes a unique prefix of a long flag, as GNU getopt_long does. A prefix that matches more than one flag is an error.
package main
import (
"context"
"errors"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) error {
return ox.RunError(
context.Background(),
ox.Usage("app", "an app"),
ox.Abbrev(),
ox.Flags().
Bool("verbose", "write more").
Bool("version", "write the version").
String("output", "the output file"),
ox.Exec(func(ctx context.Context) {
fmt.Println("output:", otx.String(ctx, "output"))
fmt.Println("verbose:", otx.Bool(ctx, "verbose"))
}),
ox.Args(args...),
)
}
fmt.Println(run("--out", "a.txt", "--verb"))
err := run("--ver")
fmt.Println(errors.Is(err, ox.ErrAmbiguousFlag), err)
}
Output: output: a.txt verbose: true <nil> true --ver: ambiguous flag: --verbose, --version
func After ¶ added in v0.2.0
func After[F ExecType](f F) CommandOption
After is a Command option to set a func that runs after the exec func of the command, and of each sub command below it. f takes any signature that Exec takes. The after funcs run from the command that runs up to the root, also when the exec func returns an error. Each one runs, whatever an earlier one returns. The run returns the errors of the exec func and of the after funcs, joined with errors.Join. Help, the version and completion do not run it.
func AllOrNoneOf ¶ added in v0.2.0
func AllOrNoneOf(names ...string) CommandOption
AllOrNoneOf is a Command option to need each of the named flags, or none of them. When some of them get a value from the command line, the environment or a config file, and others do not, Context.Validate returns an error that wraps ErrAllOrNoneOf and names them. A default does not count. The struct tag option is `allornoneof:GROUP`.
func App ¶
func App[T *E, E any](v T) CommandOption
App is a Command option to build the command, its flags and its sub commands from v, a pointer to a struct:
- The doc comment of the struct type gives the usage and the help of the command. A section starts with a line that holds only its name and a colon. Each line after it, with one tab removed, is the text of the section, up to the next section. The sections are `Description:`, the usage of the command, `Usage:`, whose first line is the name of the command after the names of its parents, then its spec, `Aliases:`, `Section:`, `Banner:`, `Examples:`, `Sections:`, the names of the flag sections, `Command sections:`, the names of the sub command sections, and `Footer:`. A sub command without a usage line takes its name from its type, without the suffix `Command` and without the name of the type of its parent, such as `list` for `AppListCommand`.
- Each field with an `ox` tag is a flag, as From makes it. When the tag has no description, the doc comment of the field gives the usage.
- When the struct has a method `Commands() []any`, each value that it returns is a sub command, built the same way.
- When the struct has a method `Exec`, with a signature that Exec takes, such as `Exec(context.Context, []string) error`, it is the exec func of the command.
- When the struct has a method `Before` or `After`, with a signature that Exec takes, it is the func of Before or After of the command.
Go keeps no doc comment in a program, so the program registers them with RegisterDoc. The tool `github.com/xo/ox/cmd/oxdoc` writes those calls from `go generate`.
Example ¶
ExampleApp builds a command from a struct and its doc comments.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
)
func main() {
// Greet says hello.
//
// Usage:
//
// greet [flags] [NAME]
//
// Footer:
//
// See the docs.
type Greet struct {
// the greeting, such as hello, or hi
Greeting string `ox:",short:g,default:hello"`
}
// oxdoc writes this call in oxdoc_gen.go, from go generate
ox.RegisterDoc[Greet](
"Greet says hello.\n\nUsage:\n\n\tgreet [flags] [NAME]\n\nFooter:\n\n\tSee the docs.\n",
map[string]string{"Greeting": "the greeting, such as hello, or hi\n"},
)
var greet Greet
err := ox.RunError(
context.Background(),
ox.App(&greet),
ox.Help(),
ox.Args("--help"),
)
fmt.Println(err)
}
Output: greet Usage: greet [flags] [NAME] Flags: -g, --greeting string the greeting, such as hello, or hi (default: hello) -h, --help show help, then exit See the docs. <nil>
func AppNameVersion ¶
func AppNameVersion(name, version string) CommandOption
AppNameVersion is a Command option to set the root app name and version. Mostly used with AppFrom.
func Arg ¶ added in v0.2.0
func Arg(name, usage string, opts ...Option) CommandOption
Arg is a Command option to add a positional argument to the command, after the arguments that it has. opts are each ArgOption and FlagOption of NewArgument, such as a Type, Elem, Default, Valid, Bind, CompFunc, Spec or Optional.
The parse converts each argument to its type, and checks it, as for a flag. So a FileT must be a file that exists. Context.Vars holds the value by the name of the argument, so that the exec func reads it with `otx.Get`. An argument is required, unless it has a default or Optional. A required argument cannot follow an optional one. The last argument can be variadic, with the type SliceT and an Elem, and it then takes each argument that is left. Help writes each argument in the usage line and in the `Arguments:` section, and completion completes it by its type.
Example ¶
ExampleArg declares two positional arguments with a type. The second has a default, so it is optional.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
err := ox.RunError(
context.Background(),
ox.Usage("cp", "copy a file"),
ox.Arg("src", "the file to copy", ox.FileT),
ox.Arg("dst", "the directory to copy to", ox.DirT, ox.Default(".")),
ox.Exec(func(ctx context.Context) {
fmt.Println("copy", otx.String(ctx, "src"), "to", otx.String(ctx, "dst"))
}),
ox.Args(args...),
)
if err != nil {
fmt.Println(err)
}
}
run("go.mod", "docs")
run("go.mod")
run("missing.txt")
run()
run("go.mod", "docs", "more")
}
Output: copy go.mod to docs copy go.mod to . command cp: arg src: invalid value: missing.txt: does not exist command cp: missing argument: src command cp: invalid arg count: takes max 2 arg(s)
Example (Variadic) ¶
ExampleArg_variadic declares a last argument that takes each argument that is left, and writes the help.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
err := ox.RunError(
context.Background(),
ox.Usage("cat", "print files"),
ox.Arg("files", "the files to print", ox.SliceT, ox.Elem(ox.FileT), ox.Spec("FILE")),
ox.Help(),
ox.Exec(func(ctx context.Context) {
fmt.Println(otx.Slice[string](ctx, "files"))
}),
ox.Args(args...),
)
if err != nil {
fmt.Println(err)
}
}
run("go.mod", "LICENSE")
run("--help")
}
Output: [go.mod LICENSE] cat print files Usage: cat [flags] FILE... Arguments: FILE the files to print Flags: -h, --help show help, then exit
func ArgsFunc ¶
func ArgsFunc(funcs ...func([]string) error) CommandOption
ArgsFunc is a Command option to add funcs to command's argument validation funcs.
func AtLeastOneOf ¶ added in v0.2.0
func AtLeastOneOf(names ...string) CommandOption
AtLeastOneOf is a Command option to need one of the named flags at least. When none of them gets a value from the command line, the environment or a config file, Context.Validate returns an error that wraps ErrAtLeastOneOf and names them. A default does not count. The struct tag option is `atleastoneof:GROUP`.
func BashLongFlags ¶ added in v0.7.0
func BashLongFlags() CommandOption
BashLongFlags is a Command option that reads long flags as bash does. A long flag after the first short flag, or after the first plus form, is an error that wraps ErrUnknownFlag, as `bash -e --noediting` fails. A long flag with a value after `=`, such as `--norc=1` or `--rcfile=x`, is an error that wraps ErrInvalidValue, so a long flag takes its value only from the next word. `--` still ends the flags. A command reads its long flags so when it or a parent has BashLongFlags, so a sub command inherits it (D54).
func Before ¶ added in v0.2.0
func Before[F ExecType](f F) CommandOption
Before is a Command option to set a func that runs before the exec func of the command, and of each sub command below it. f takes any signature that Exec takes, and gets the same context.Context and args as the exec func. The before funcs run from the root down to the command that runs. When one returns an error, the run stops: no later before func, no exec func and no after func runs. Help, the version and completion do not run it.
Example ¶
ExampleBefore runs a func before the exec func of a command and of each sub command, and a func after it. The after func runs also when the exec func fails.
package main
import (
"context"
"errors"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
err := ox.RunError(
context.Background(),
ox.Usage("db", "a database tool"),
ox.Flags().
String("dsn", "the database to open", ox.Default("app.db")),
ox.Before(func(ctx context.Context) error {
fmt.Println("open", otx.String(ctx, "dsn"))
return nil
}),
ox.After(func(ctx context.Context) error {
fmt.Println("close", otx.String(ctx, "dsn"))
return nil
}),
ox.Sub(
ox.Usage("list", "list the rows"),
ox.Before(func() {
fmt.Println("lock the table")
}),
ox.Exec(func() error {
fmt.Println("list the rows")
return errors.New("no rows")
}),
),
ox.Args("--dsn", "test.db", "list"),
)
fmt.Println("error:", err)
}
Output: open test.db lock the table list the rows close test.db error: no rows
func CommandSort ¶
func CommandSort(commandSort bool) CommandOption
CommandSort is a Command option to set the sort for sub commands when used with a Command.
func ConfigFiles ¶
func ConfigFiles(paths ...string) CommandOption
ConfigFiles is a root Command option to add config files to read, in order. Each path is interpolated, such as "$APPCONFIG/config.yaml". A later file wins over an earlier one. A file that does not exist is skipped. The format comes from the extension of the file. See RegisterConfigFormat.
Example ¶
ExampleConfigFiles reads the flags from config files. A later file wins over an earlier one, and a file that does not exist is skipped.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
dir, err := os.MkdirTemp("", "app")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
system := filepath.Join(dir, "system.json")
user := filepath.Join(dir, "user.json")
_ = os.WriteFile(system, []byte(`{"log-level": "info", "server": {"port": 8080}, "tags": ["a", "b"]}`), 0o600)
_ = os.WriteFile(user, []byte(`{"log-level": "debug"}`), 0o600)
ox.Run(
ox.Usage("app", "an app"),
// a program uses a path such as "$APPCONFIG/config.json"
ox.ConfigFiles(system, filepath.Join(dir, "missing.json"), user),
ox.Flags().
String("log-level", "the log level", ox.Default("warn")).
Int("port", "the port", ox.Key("", "server.port")).
Slice("tags", "the tags"),
ox.Exec(func(ctx context.Context) {
fmt.Println("log-level:", otx.String(ctx, "log-level"))
fmt.Println("port:", otx.Int(ctx, "port"))
fmt.Println("tags:", otx.Slice[string](ctx, "tags"))
}),
ox.Args(),
)
}
Output: log-level: debug port: 8080 tags: [a b]
Example (SubCommand) ¶
ExampleConfigFiles_subCommand reads the key of a flag of a sub command, under the path of the command. A field of a nested struct reads the path of the field, and an inherited flag keeps the key of its command.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
dir, err := os.MkdirTemp("", "app")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "config.json")
data := `{"verbose": true, "db": {"migrate": {"steps": 3, "source": {"dir": "./up"}}}}`
_ = os.WriteFile(path, []byte(data), 0o600)
var args struct {
Steps int `ox:"the number of steps"`
Source struct {
Dir string `ox:"the folder of the migrations"`
} `ox:""`
}
ox.Run(
ox.Usage("app", "an app"),
ox.ConfigFiles(path),
ox.Flags().
Bool("verbose", "write more"),
ox.Sub(
ox.Usage("db", "the database"),
ox.Sub(
ox.Usage("migrate", "migrate the database"),
// --steps reads db.migrate.steps, and --source-dir reads
// db.migrate.source.dir
ox.From(&args),
ox.Exec(func(ctx context.Context) {
fmt.Println("verbose:", otx.Bool(ctx, "verbose"))
fmt.Println("steps:", args.Steps)
fmt.Println("dir:", args.Source.Dir)
}),
),
),
ox.Args("db", "migrate"),
)
}
Output: verbose: true steps: 3 dir: ./up
func ConfigRequired ¶
func ConfigRequired() CommandOption
ConfigRequired is a root Command option that makes it an error when no config file exists.
func Defaults ¶
func Defaults(opts ...Option) CommandOption
Defaults is a Command option to add Version, Comp, and Help options to the command. Note that the order is important.
func EnvPrefix ¶
func EnvPrefix(prefix string) CommandOption
EnvPrefix is a root Command option to fill each flag from the environment variable PREFIX_NAME, with the name of the flag in upper case and each "-" as "_", such as APP_LOG_LEVEL for --log-level. The command line wins over the environment, and the environment wins over the config files and the default. See NoEnv and EnvVar.
Example ¶
ExampleEnvPrefix fills each flag from an environment variable. EnvPrefix names the variable of each flag. EnvVar gives one flag a variable of its own, and NoEnv keeps a flag out of the environment.
package main
import (
"context"
"fmt"
"os"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
_ = os.Setenv("APP_LOG_LEVEL", "debug")
_ = os.Setenv("API_TOKEN", "secret")
_ = os.Setenv("APP_HOME", "/from/env")
defer func() { _ = os.Unsetenv("APP_LOG_LEVEL") }()
defer func() { _ = os.Unsetenv("API_TOKEN") }()
defer func() { _ = os.Unsetenv("APP_HOME") }()
ox.Run(
ox.Usage("app", "an app"),
ox.EnvPrefix("APP"),
ox.Flags().
String("log-level", "the log level", ox.Default("info")).
String("token", "the API token", ox.EnvVar("API_TOKEN")).
String("home", "the home directory", ox.NoEnv(), ox.Default("/default")),
ox.Exec(func(ctx context.Context) {
fmt.Println("log-level:", otx.String(ctx, "log-level"))
fmt.Println("token:", otx.String(ctx, "token"))
fmt.Println("home:", otx.String(ctx, "home"))
}),
ox.Args(),
)
}
Output: log-level: debug token: secret home: /default
func Extend ¶ added in v0.3.0
func Extend(name string, f func(*Command) error) CommandOption
Extend is a root Command option that runs f on the root command after each other option, so that f finds every flag and sub command, and the help, version and completion of Defaults. A package outside ox uses it to add to the command tree, as github.com/xo/ox/metadoc.Command does. The name names the option in an error.
func From ¶
func From[T *E, E any](val T) CommandOption
From is a Command option to build the command's flags from a value of type *struct using reflection. Adds flags for all exported fields of the passed value having a `ox` tag and a non-empty description.
Example:
args := struct{
MyFlag string `ox:"my flag,short:f,default:$USER"`
MyVerbosity int `ox:"my verbosity,type:count,short:v"`
MyURL *url.URL `ox:"my url,set:MyURLSet"`
MyURLSet bool
MyOtherFlag string `ox:"a long\\, long description,short:F"`
MyFloat float64 `ox:"my float,hidden,name:MYF"`
}{}
ox.Run(
ox.From(&args),
)
See FlagsFrom for more information for available tag options.
Example ¶
ExampleFrom builds the flags from the fields of a struct, with reflection.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
args := struct {
Name string `ox:"the name to greet,short:n,default:world"`
Times int `ox:"the number of greetings,short:t,default:1"`
Tags []string `ox:"a tag,short:T"`
}{}
ox.Run(
ox.Usage("greet", "say hello"),
ox.Defaults(),
ox.From(&args),
ox.Exec(func() {
fmt.Println("name:", args.Name)
fmt.Println("times:", args.Times)
fmt.Println("tags:", args.Tags)
}),
ox.Args("-n", "ken", "-T", "a,b", "-T", "c"),
)
}
Output: name: ken times: 1 tags: [a b c]
Example (Args) ¶
ExampleFrom_args makes fields positional arguments with the tag option `arg`, in the order of the fields.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
args := struct {
Verbose bool `ox:"write more,short:v"`
Src string `ox:"the file to copy,arg,type:file"`
Dsts []string `ox:"the directories to copy to,arg,optional,elem:dir"`
}{}
ox.Run(
ox.Usage("cp", "copy a file"),
ox.From(&args),
ox.Exec(func() {
fmt.Println("verbose:", args.Verbose)
fmt.Println("src:", args.Src)
fmt.Println("dsts:", args.Dsts)
}),
ox.Args("-v", "go.mod", "docs", "testdata"),
)
}
Output: verbose: true src: go.mod dsts: [docs testdata]
Example (Escaping) ¶
ExampleFrom_escaping shows how to escape a comma, a double quote and a backslash in a struct tag.
package main
import (
"github.com/xo/ox"
)
func main() {
args := struct {
File string `ox:"read a file\\, then exit"`
Listen string `ox:"host:port to listen on"`
Say string `ox:"say \"hi\"\\, loudly"`
Slash string `ox:"a back\\\\slash"`
URL string `ox:"a url,default:http://x:80/a\\,b"`
}{}
ox.Run(
ox.Usage("esc", "escapes"),
ox.Help(),
ox.From(&args),
ox.Args("--help"),
)
}
Output: esc escapes Usage: esc [flags] [args] Flags: --file string read a file, then exit --listen string host:port to listen on --say string say "hi", loudly --slash string a back\slash --url string a url (default: http://x:80/a,b) -h, --help show help, then exit
Example (Rules) ¶
ExampleFrom_rules makes a flag required, and adds rules between flags, with struct tags. The flags with the same rule and the same group name are one group.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
)
func main() {
args := struct {
Target string `ox:"the target,required"`
JSON bool `ox:"write JSON,onlyoneof:format"`
YAML bool `ox:"write YAML,onlyoneof:format"`
User string `ox:"the user,allornoneof:auth"`
Pass string `ox:"the password,allornoneof:auth"`
}{}
run := func(v ...string) error {
return ox.RunError(
context.Background(),
ox.Usage("deploy", "deploy the app"),
ox.From(&args),
ox.Exec(func() {
fmt.Println("deploy to", args.Target)
}),
ox.Args(v...),
)
}
fmt.Println(run("--target", "prod", "--json"))
fmt.Println(run("--json"))
fmt.Println(run("--target", "prod", "--json", "--yaml"))
fmt.Println(run("--target", "prod", "--pass", "secret"))
}
Output: deploy to prod <nil> command deploy: required flag: --target command deploy: only one of the flags can be set: --json, --yaml command deploy: all or none of the flags must be set: --user, --pass (missing --user)
Example (Tags) ¶
ExampleFrom_tags shows each struct tag option that sets the name, the help or the section of a flag.
package main
import (
"github.com/xo/ox"
)
func main() {
args := struct {
Host string `ox:"the host,short:H,spec:HOST,section:0"`
Port int `ox:"the port,short:p,default:5432,section:0"`
User string `ox:"the user name,name:username,section:1"`
Debug bool `ox:"debug output,hidden"`
Old string `ox:"an old flag,deprecated"`
Help bool `ox:"show this help\\, then exit,short:?,hook:help,section:1"`
Version bool `ox:"show the version\\, then exit,short:V,hook:version,section:1"`
}{}
ox.Run(
ox.Usage("db", "connect to a database"),
ox.Version(),
ox.Help(ox.Sections("Connection options", "Other options")),
ox.From(&args),
ox.Args("--help"),
)
}
Output: db connect to a database Usage: db [flags] [args] Connection options: -H, --host HOST the host -p, --port int the port (default: 5432) Other options: --username string the user name -?, --help show this help, then exit -V, --version show the version, then exit
Example (UnescapedComma) ¶
ExampleFrom_unescapedComma shows the error that a comma gives when it is not escaped.
package main
import (
"errors"
"fmt"
"github.com/xo/ox"
)
func main() {
args := struct {
File string `ox:"read a file, then exit"`
}{}
_, err := ox.NewContext(
ox.Usage("esc", "escapes"),
ox.From(&args),
)
fmt.Println(err)
fmt.Println(errors.Is(err, ox.ErrUnknownTagOption))
}
Output: From (*ox.Command): cannot build flags for *struct: field File: unknown tag option: " then exit" true
Example (Values) ¶
ExampleFrom_values shows each struct tag option that sets the type, the value or the aliases of a flag.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
args := struct {
Dir string `ox:"a directory,type:path"`
Weights map[string]string `ox:"weights,mapkey:int,elem:float64"`
Hosts []string `ox:"host addresses,elem:addr"`
Path []string `ox:"a search path,split::"`
Color string `ox:"when to use color,noarg:always,default:auto"`
Level string `ox:"a log level,set:LevelSet"`
User string `ox:"the user name,alias:login,aliases:usr|u"`
LevelSet bool
}{}
ox.Run(
ox.Usage("app", "an app"),
ox.From(&args),
ox.Exec(func() {
fmt.Println("dir:", args.Dir)
fmt.Println("weights:", args.Weights)
fmt.Println("hosts:", args.Hosts)
fmt.Println("path:", args.Path)
fmt.Println("color:", args.Color)
fmt.Println("level set:", args.LevelSet)
fmt.Println("user:", args.User)
}),
ox.Args(
"--dir", "/tmp",
"--weights", "1=0.5", "--weights", "2=1.5",
"--hosts", "10.0.0.1,10.0.0.2",
"--path", "/bin:/usr/bin",
"--color",
"--level", "debug",
"-u", "ken",
),
)
}
Output: dir: /tmp weights: map[1:0.5 2:1.5] hosts: [10.0.0.1 10.0.0.2] path: [/bin /usr/bin] color: always level set: true user: ken
func HelpColumn ¶
func HelpColumn(column int) CommandOption
HelpColumn is a Command/Help option to start each description in help after column characters, as `psql --help` does. An option or a command that does not fit before the column goes on a line of its own, and its description starts on the next line. A description is not wrapped, and each line break in it starts a new line at the column. Help also writes the aliases of each flag. Without HelpColumn, or with a column of zero or less, help uses the default layout.
func InheritedFlags ¶ added in v0.2.0
func InheritedFlags(show bool) CommandOption
InheritedFlags is a Command/Help option to show the flags that a sub command inherits from its parents in its help, after its own flags, in a section with the name of text.GlobalFlags, as cobra does. A local flag of a parent is not inherited (see Local), and a flag of a parent with the name of a flag of the sub command is not shown. When the root command has it, Help gives it to each sub command.
Example ¶
ExampleInheritedFlags writes the flags that a sub command inherits in its help, in a section of their own. A local flag is not inherited.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Defaults(ox.InheritedFlags(true)),
ox.Flags().
String("config", "the config file", ox.Short("c")).
Bool("init", "make a new config file", ox.Local()),
ox.Sub(
ox.Usage("show", "show the config"),
ox.Flags().
Bool("all", "show every key"),
),
ox.Args("show", "--help"),
)
}
Output: show show the config Usage: app show [flags] [args] Flags: --all show every key -h, --help show help, then exit Global Flags: -c, --config string the config file
func LetterClusters ¶ added in v0.6.0
func LetterClusters() CommandOption
LetterClusters is a Command option that reads short letters as bash does. A letter that takes a value takes it only from the next word, so `-oe errexit` sets e, and o takes errexit, where `getopt` gives o the value e. Each letter that takes a value takes the next word in turn. An `=` is a letter, so `-e=` is an error that wraps ErrUnknownFlag, as bash refuses it. It applies to the `+` forms too. A command reads its letters so when it or a parent has LetterClusters, so a sub command inherits it. A long flag does not change.
Example ¶
ExampleLetterClusters reads a command line as bash does: each word that starts with `+` is flags, a letter that takes a value takes the next word, and -o can be the last word, where its hook lists the options.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
)
func main() {
set := func(ctx *ox.Context, name string) {
switch {
case ctx.NoValue():
fmt.Println("list the options")
case ctx.IsPlus():
fmt.Println(name, "off")
default:
fmt.Println(name, "on")
}
}
errexit := func(ctx *ox.Context) {
set(ctx, "errexit")
}
run := func(args ...string) {
err := ox.RunError(
context.Background(),
ox.Usage("sh", "a shell"),
ox.StopAtArg(),
ox.PlusWords(),
ox.LetterClusters(),
ox.Flags().
Var("set-option", "set an option", ox.HookT, ox.Default(set), ox.Short("o"), ox.AllowPlus(), ox.OptionalAtEnd()).
Hook("errexit", "exit on an error", errexit, ox.Short("e"), ox.AllowPlus()),
ox.Exec(func() {}),
ox.Args(args...),
)
if err != nil {
fmt.Println("error:", err)
}
}
run("-oe", "nounset")
run("+", "+o", "nounset")
run("-o")
run("+z")
run("-e=")
}
Output: nounset on errexit on nounset off list the options error: +z: unknown flag errexit on error: -=: unknown flag
func MaxDist ¶
func MaxDist(maxDist int) CommandOption
MaxDist is a Command option to set the maximum Levenshtein distance of the suggestions and the corrections of the command. 0 keeps DefaultMaxDist, and a negative distance turns off the distance match for the command.
func NegateBools ¶ added in v0.3.0
func NegateBools(prefixes ...string) CommandOption
NegateBools is a root Command option to give each bool flag of the command tree a negated form, such as `--no-debug` for `--debug`. The negated form sets the flag to false, and takes no value. It counts as a value from the command line, as the flag does. Without a prefix, the prefix is DefaultNegatePrefix. Each prefix adds a form, so `NegateBools("no", "without")` gives `--no-debug` and `--without-debug`. A prefix is a word of letters, digits and hyphens, with no hyphen at either end.
Only a bool flag that the command line sets to true without a value gets a negated form. A count flag and a hook flag, such as `--help`, do not. The negated form comes from the long name of the flag. An alias and a short name get none. A flag whose name starts with a prefix and a hyphen, such as `--no-psqlrc`, gets none, so that no flag reads `--no-no-psqlrc`. Help writes the flag as `--[no-]debug`, with the first prefix, and completion offers each form.
The negated form of a hidden flag is hidden, the negated form of a local flag is local (see Local), and a sub command takes the negated form of each flag that it inherits. A negated form with the name of another flag of a command, or of its long alias, is an error when the command is built. Give one of the flags Negatable false to keep it out. The environment and the config files set the flag itself, and are not changed.
NegateBools is not one of the Defaults, because it changes how the command line parses.
Example ¶
ExampleNegateBools gives each bool flag a negated form, such as --no-color, and help writes the flag as --[no-]color.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
ox.Run(
ox.Usage("app", "an app"),
ox.Help(),
ox.NegateBools("no", "skip"),
ox.Flags().
Bool("color", "use color", ox.Default(true)).
Bool("cache", "use the cache", ox.Default(true)).
Bool("no-rc", "do not read the startup file").
Bool("force", "overwrite each file", ox.Negatable(false)),
ox.Exec(func(ctx context.Context) {
fmt.Println("color:", otx.Bool(ctx, "color"))
fmt.Println("cache:", otx.Bool(ctx, "cache"))
}),
ox.Args(args...),
)
}
run("--no-color", "--skip-cache")
run("--help")
}
Output: color: false cache: false app an app Usage: app [flags] [args] Flags: --[no-]color use color --[no-]cache use the cache --no-rc do not read the startup file --force overwrite each file -h, --help show help, then exit
func OnlyOneOf ¶ added in v0.2.0
func OnlyOneOf(names ...string) CommandOption
OnlyOneOf is a Command option to allow one of the named flags at most. When two or more of them get a value from the command line, the environment or a config file, Context.Validate returns an error that wraps ErrOnlyOneOf and names them. A default does not count. The struct tag option is `onlyoneof:GROUP`, which adds the flag to the group GROUP.
Example ¶
ExampleOnlyOneOf adds rules between the flags of a command. OnlyOneOf allows one flag of the group at most. AllOrNoneOf needs each flag of the group, or none of them. AtLeastOneOf needs one flag of the group at least.
package main
import (
"context"
"errors"
"fmt"
"github.com/xo/ox"
)
func main() {
run := func(args ...string) error {
return ox.RunError(
context.Background(),
ox.Usage("export", "export the data"),
ox.Flags().
Bool("json", "write JSON").
Bool("yaml", "write YAML").
String("user", "the user").
String("pass", "the password").
String("file", "the file to read").
String("url", "the URL to read"),
ox.OnlyOneOf("json", "yaml"),
ox.AllOrNoneOf("user", "pass"),
ox.AtLeastOneOf("file", "url"),
ox.Exec(func() {
fmt.Println("export")
}),
ox.Args(args...),
)
}
fmt.Println(run("--file", "data.csv", "--json"))
err := run("--file", "data.csv", "--json", "--yaml")
fmt.Println(errors.Is(err, ox.ErrOnlyOneOf), err)
err = run("--url", "https://example.com", "--user", "ken")
fmt.Println(errors.Is(err, ox.ErrAllOrNoneOf), err)
err = run("--json")
fmt.Println(errors.Is(err, ox.ErrAtLeastOneOf), err)
}
Output: export <nil> true command export: only one of the flags can be set: --json, --yaml true command export: all or none of the flags must be set: --user, --pass (missing --pass) true command export: at least one of the flags must be set: --file, --url
func Parent ¶
func Parent(parent *Command) CommandOption
Parent is a Command option to set the command's parent.
func PlusWords ¶ added in v0.6.0
func PlusWords() CommandOption
PlusWords is a Command option that reads each word that starts with `+` as the plus forms of short flags, as bash does, and not only a word whose first letter names a flag with AllowPlus (D52). So a letter without a plus form, such as the `z` of `+z`, is an error that wraps ErrUnknownFlag, and a lone `+` is skipped. A command takes each word so when it or a parent has PlusWords, so a sub command inherits it. A program that takes an argument such as the `+%Y` of `date` does not use it.
func Sort ¶
func Sort(sort bool) CommandOption
Sort is a Command option to set the sort for flags when used with a Command.
func StopAtArg ¶ added in v0.2.0
func StopAtArg() CommandOption
StopAtArg is a Command option to end the flags of the command at its first positional argument, as pflag's SetInterspersed(false) does. Each later argument is a positional argument, even one that starts with `-`, and a later `--` too. A wrapper command, such as `app exec cmd --its-own-flag`, uses it.
A sub command name comes before the first positional argument, so StopAtArg on a command with sub commands still finds them. A sub command does not inherit StopAtArg. A `--` before the first positional argument ends the flags, as it does without StopAtArg.
Example ¶
ExampleStopAtArg ends the flags of a command at its first positional argument, so that a wrapper command passes the rest to the command that it runs.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Bool("verbose", "write more", ox.Short("v")),
ox.Sub(
ox.Usage("exec", "run a command"),
ox.StopAtArg(),
ox.Flags().
String("dir", "the work directory", ox.Short("C")),
ox.Exec(func(ctx context.Context, args []string) {
fmt.Println("verbose:", otx.Bool(ctx, "verbose"))
fmt.Println("dir:", otx.String(ctx, "dir"))
fmt.Printf("args: %q\n", args)
}),
),
ox.Args("exec", "-v", "-C", "/src", "ls", "-l", "--all"),
)
}
Output: verbose: true dir: /src args: ["ls" "-l" "--all"]
func Sub ¶
func Sub(opts ...Option) CommandOption
Sub is a Command option to create a sub command.
Example ¶
ExampleSub builds a tree of sub commands. A sub command has aliases, and it reads the flags of its parents.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("git", "a version control tool"),
ox.Defaults(),
ox.Flags().
String("dir", "the work directory", ox.Short("C"), ox.Default(".")),
ox.Sub(
ox.Usage("remote", "manage remotes"),
ox.Sub(
ox.Usage("remove", "remove a remote"),
ox.Aliases("rm"),
ox.ValidArgs(1, 1),
ox.Exec(func(ctx context.Context, args []string) error {
fmt.Println("dir:", otx.String(ctx, "dir"))
fmt.Println("remove:", args[0])
return nil
}),
),
),
ox.Args("-C", "/src", "remote", "rm", "origin"),
)
}
Output: dir: /src remove: origin
Example (Help) ¶
ExampleSub_help writes the help of a sub command. The help command and the --help flag write the same text.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("git", "a version control tool"),
ox.Defaults(),
ox.Sub(
ox.Usage("remote", "manage remotes"),
ox.Sub(
ox.Usage("remove", "remove a remote"),
ox.Aliases("rm"),
),
ox.Sub(
ox.Usage("add", "add a remote"),
),
),
ox.Args("help", "remote"),
)
}
Output: remote manage remotes Usage: git remote [flags] [command] [args] Available Commands: add add a remote remove remove a remote Flags: -h, --help show help, then exit Use "git remote [command] --help" for more information about a command.
func Suggested ¶
func Suggested(suggested ...string) CommandOption
Suggested is a Command option to add suggested names for the command.
func ValidArgs ¶
func ValidArgs(minimum, maximum int, values ...string) CommandOption
ValidArgs is a Command option to add a argument validation func to the command that validates the range of allowed minimum/maximum argruments and allowed argument values. A minimum/maximum < 0 means no minimum/maximum. Completion offers the values at each position up to the maximum. See Command.ValidArgs.
func Version ¶
func Version() CommandOption
Version is a Command option to hook --version with version output derived from Go's build info.
Example ¶
ExampleVersion writes the version of the program. Version adds --version to a root without sub commands. It adds a version command to a root that has sub commands.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.VersionString("1.2.3"),
ox.Version(),
ox.Help(),
ox.Args("--version"),
)
}
Output: app 1.2.3
func VersionString ¶
func VersionString(version string) CommandOption
VersionString is a Command option to set the version displayed for the command.
type CompDirective ¶
type CompDirective int
CompDirective is a bit map representing the different behaviors the shell can be instructed to have once completions have been provided.
Cribbed from cobra for compatibility purposes.
const ( // CompError indicates an error occurred and completions should be ignored. CompError CompDirective = 1 << iota // CompNoSpace indicates that the shell should not add a space after the // completion even if there is a single completion provided. CompNoSpace // CompNoFileComp indicates that the shell should not provide file // completion even when no completion is provided. CompNoFileComp // CompFilterFileExt indicates that the provided completions should be used // as file extension filters. CompFilterFileExt // CompFilterDirs indicates that only directory names should be provided in // file completion. To request directory names within another directory, // the returned completions should specify the directory within which to // search. The BashCompSubdirsInDir annotation can be used to obtain the // same behavior but only for flags. CompFilterDirs // CompKeepOrder indicates that the shell should preserve the order in // which the completions are provided. CompKeepOrder // CompNoFilter indicates that ox does not keep only the completions that // start with the word to complete. A [CompFunc] returns it. ox does not // pass it to the shell. CompNoFilter // CompDefault indicates to let the shell perform its default behavior // after completions have been provided. CompDefault CompDirective = 0 )
Comp directives.
Cribbed from cobra for compatibility purposes.
func (CompDirective) String ¶
func (dir CompDirective) String() string
String satisfies the fmt.Stringer interface.
type Completion ¶
Completion is a completion.
func NewActiveHelp ¶
func NewActiveHelp(help string) Completion
NewActiveHelp creates a line of ActiveHelp, which a CompFunc returns beside its completions. The completion scripts show it as help, as cobra's scripts do. The environment variable of DefaultCompActiveHelpSuffix, such as APP_ACTIVE_HELP=0, turns it off.
func NewCompletion ¶
func NewCompletion(name, usage string, dist int) Completion
NewCompletion creates a completion.
type Config ¶
type Config interface {
// Lookup returns the value of a key, and whether the file has the key. A
// key is a dotted path, such as "server.port". A format can accept a
// syntax of its own as well, such as a YAML path that starts with "$.".
Lookup(key string) (any, bool, error)
}
Config is one decoded config file.
type ConfigType ¶
type ConfigType string
ConfigType is a config type.
const ( AnyT ConfigType = "" EnvT ConfigType = "env" JSONT ConfigType = "json" YAMLT ConfigType = "yaml" HCLT ConfigType = "hcl" TOMLT ConfigType = "toml" INIT ConfigType = "ini" )
Config types.
type Context ¶
type Context struct {
// Exit is the exit func.
Exit func(int)
// Panic is the panic func.
Panic func(any)
// Comp is the completion func.
Comp func(*Context) error
// Stdin is the standard in to use, normally [os.Stdin].
Stdin io.Reader
// Stdout is the standard out to use, normally [os.Stdout].
Stdout io.Writer
// Stderr is the standard error to use, normally [os.Stderr].
Stderr io.Writer
// Args are the arguments to parse, normally [os.Args][1:].
Args []string
// EmitExecExitError toggles emitting captured stderr output from
// [exec.ExitError] to [Context.Stderr].
EmitExecExitError bool
// OnErr is the on error handling. Used by the default Handle func.
OnErr OnErr
// Continue is the func used to decide if it should continue on an error.
Continue func(*Command, error) bool
// Handler is the func used to handle errors within [Run]/[RunContext].
Handler func(error) bool
// Override override expansion keys.
Override func(ConfigType, string) (any, bool, error)
// Root is the root command created within [Run]/[RunContext].
Root *Command
// Exec is the exec target, determined by the Root's definition and after
// Args.
Exec *Command
// Vars are the variables parsed from the flag definitions of the Root
// command and its sub-commands.
Vars Vars
// Interpolate interpolates variables based on the context.
Interpolate func(*Context, any) (any, error)
// Lookup retrieves config variables based on the context.
Lookup func(*Context, ConfigType, string) (any, error)
// Loader is the config loader func.
Loader func(*Context, ConfigType, string) (any, bool, error)
// contains filtered or unexported fields
}
Context is the execution (run) context used by Run/RunContext.
func Ctx ¶
Ctx returns the context from the context.Context.
func NewContext ¶
NewContext creates a new run context.
Example ¶
ExampleNewContext tests a command. The test builds a context with the command line to test, and a buffer for the output. The exec func writes to the Stdout of the context, so that the test reads it.
package main
import (
"context"
"fmt"
"strings"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
var stdout strings.Builder
ctx, err := ox.NewContext(
ox.Usage("greet", "say hello"),
ox.Flags().
String("name", "the name to greet", ox.Default("world")),
ox.ValidArgs(0, 0),
ox.Exec(func(ctx context.Context) error {
c, _ := ox.Ctx(ctx)
fmt.Fprintln(c.Stdout, "hello", otx.String(ctx, "name"))
return nil
}),
ox.Pipe(strings.NewReader(""), &stdout, &stdout),
ox.Args("--name", "ken"),
)
if err != nil {
fmt.Println(err)
return
}
if err := ctx.Parse(); err != nil {
fmt.Println(err)
return
}
if err := ctx.Validate(); err != nil {
fmt.Println(err)
return
}
if err := ctx.Run(context.Background()); err != nil {
fmt.Println(err)
return
}
fmt.Print(stdout.String())
}
Output: hello ken
func (*Context) Comps ¶
func (ctx *Context) Comps() ([]Completion, CompDirective, error)
Comps returns the completions for the context. The first arg is the name of the completion command, and the last arg is the word to complete.
Comps ignores each error in the args before the last arg, as cobra does. After `--`, or after the first positional argument of a command with Command.StopAtArg, it completes only positional arguments. It never offers a hidden or a deprecated flag, nor a hidden or a deprecated command.
func (*Context) Expand ¶
Expand expands a variable using Context.Interpolate. A nil context returns the variable as it is.
func (*Context) Fill ¶
Fill gives a value to each flag of cmd and of its parents that the command line did not set. Each flag takes its value from the first source that has one: the environment, the config files, then its default, which is expanded only when it wins. Fill first resolves the flag that names the config file, then reads the config files once.
func (*Context) IsPlus ¶ added in v0.5.0
IsPlus returns true while a hook runs for the plus form of its flag, such as `+o name`, and false for the `-` form. See AllowPlus.
func (*Context) NoValue ¶ added in v0.6.0
NoValue returns true while a hook runs for a flag with OptionalAtEnd that is the last word of the command line without a value, such as a lone `-o`.
func (*Context) Parse ¶
Parse parses the context args, then fills each flag that the args did not set, with Context.Fill.
Example ¶
ExampleContext_Parse checks the errors of a command line with errors.Is. Parse gives the errors of the flags. Validate gives the errors of the args. The --help flag gives ErrExit after it writes the help.
package main
import (
"errors"
"fmt"
"io"
"strings"
"github.com/xo/ox"
)
func main() {
check := func(args ...string) error {
ctx, err := ox.NewContext(
ox.Usage("greet", "say hello"),
ox.Help(),
ox.Flags().
String("name", "the name to greet"),
ox.ValidArgs(0, 0),
ox.Pipe(strings.NewReader(""), io.Discard, io.Discard),
ox.Args(args...),
)
if err != nil {
return err
}
if err := ctx.Parse(); err != nil {
return err
}
return ctx.Validate()
}
err := check("--nam", "ken")
fmt.Println(errors.Is(err, ox.ErrUnknownFlag), err)
err = check("--name")
fmt.Println(errors.Is(err, ox.ErrMissingArgument), err)
err = check("extra")
fmt.Println(errors.Is(err, ox.ErrInvalidArgCount), err)
err = check("--help")
fmt.Println(errors.Is(err, ox.ErrExit), err)
}
Output: true --nam: unknown flag true --name: missing argument true command greet: invalid arg count: takes no args true --help: exit
func (*Context) Populate ¶
Populate populates the context's vars with the command's flag's default values when not already set. When all is true, all flag values will be populated with the default or zero value. When overwrite is true, any existing flag vars will be overwritten.
func (*Context) Run ¶
Run runs the command. It runs the Command.Before funcs, the exec func, then the Command.After funcs. See Before and After.
func (*Context) Validate ¶
Validate validates the args with Command.Validate, then sets the value of each positional argument of Context.Exec in Context.Vars, then validates the flags of the command and of its parents. A flag with Required must have a value, and the flags of each FlagGroup must keep its rule. A value counts when it comes from the command line, the environment or a config file. A default does not count.
The flags are not checked when the command has no exec func, because then Context.Run writes the help, or when it has a special value, such as the help, version and completion commands that Defaults adds. A `--help` or a `--version` flag stops the parse before Validate.
type ContextOption ¶
type ContextOption = Option
ContextOption are Option's that apply to a Context.
func Args ¶
func Args(args ...string) ContextOption
Args is a Run/RunContext/Context option to set the command-line arguments.
func Interpolate ¶
func Interpolate(interpolate func(*Context, any) (any, error)) ContextOption
Interpolate is a Run/RunContext/Context option to set a interpolation func.
func Lookup ¶
func Lookup(lookup func(*Context, ConfigType, string) (any, error)) ContextOption
Lookup is a Run/RunContext/Context option to set the func that looks up a config variable.
func Override ¶
func Override(override func(ConfigType, string) (any, bool, error)) ContextOption
Override is a Run/RunContext/Context option to set a override expansion func.
func OverrideMap ¶
func OverrideMap(override map[string]string) ContextOption
OverrideMap is a Run/RunContext/Context option to override expansion variables using a map.
func Pipe ¶
func Pipe(stdin io.Reader, stdout, stderr io.Writer) ContextOption
Pipe is a Run/RunContext/Context option to set the standard in, out, and error.
type Error ¶
type Error string
Error is a package error.
const ( // ErrUsageNotSet is the usage not set error. ErrUsageNotSet Error = "usage not set" // ErrCanOnlyBeUsedWithRootCommand is the can only be used with root command error. ErrCanOnlyBeUsedWithRootCommand Error = "can only be used with root command" // ErrAppliedToInvalidType is the applied to invalid type error. ErrAppliedToInvalidType Error = "applied to invalid type" // ErrInvalidArgCount is the invalid arg count error. ErrInvalidArgCount Error = "invalid arg count" // ErrInvalidFlagName is the invalid flag name error. ErrInvalidFlagName Error = "invalid flag name" // ErrInvalidShortName is the invalid short name error. ErrInvalidShortName Error = "invalid short name" // ErrCouldNotCreateValue is the could not create value error. ErrCouldNotCreateValue Error = "could not create value" // ErrUnknownCommand is the unknown command error. ErrUnknownCommand Error = "unknown command" // ErrUnknownFlag is the unknown flag error. ErrUnknownFlag Error = "unknown flag" // ErrAmbiguousFlag is the ambiguous flag error, for a prefix of a long // flag that matches more than one flag. See [Abbrev]. ErrAmbiguousFlag Error = "ambiguous flag" // ErrUnknownLoader is the unknown loader error. ErrUnknownLoader Error = "unknown loader" // ErrUnknownKey is the unknown key error. ErrUnknownKey Error = "unknown key" // ErrMissingArgument is the missing argument error. ErrMissingArgument Error = "missing argument" // ErrInvalidType is the invalid type error. ErrInvalidType Error = "invalid type" // ErrInvalidSize is the invalid size error. ErrInvalidSize Error = "invalid size" // ErrInvalidRate is the invalid rate error. ErrInvalidRate Error = "invalid rate" // ErrInvalidPortRange is the invalid port range error of // [ParsePortRange]. ErrInvalidPortRange Error = "invalid port range" // ErrInvalidLayout is the invalid layout error of [Strftime]. ErrInvalidLayout Error = "invalid layout" // ErrUnknownSize is the unknown size error. ErrUnknownSize Error = "unknown size" // ErrUnknownTagOption is the unknown tag option error. ErrUnknownTagOption Error = "unknown tag option" // ErrInvalidValue is the invalid value error. ErrInvalidValue Error = "invalid value" // ErrInvalidArg is the invalid arg error. ErrInvalidArg Error = "invalid arg" // ErrInvalidConversion is the invalid conversion error. ErrInvalidConversion Error = "invalid conversion" // ErrInvalidOp is the invalid op error. ErrInvalidOp Error = "invalid op" // ErrInvalidKey is the invalid key error. ErrInvalidKey Error = "invalid key" // ErrInvalidFilter is the invalid filter error. ErrInvalidFilter Error = "invalid filter" // ErrTypeMismatch is the type mismatch error. ErrTypeMismatch Error = "type mismatch" // ErrNotImplemented is the not implemented error. ErrNotImplemented Error = "not implemented" // ErrInvalidConfig is the invalid config error, for a config file that // its format cannot decode. ErrInvalidConfig Error = "invalid config" // ErrConfigNotFound is the config not found error. ErrConfigNotFound Error = "config not found" // ErrExit is the exit error. ErrExit Error = "exit" // ErrDuplicateFlag is the duplicate flag error, for two flags of a // command with the same name. ErrDuplicateFlag Error = "duplicate flag" // ErrNotExist is the does not exist error of a [FileT] or a [DirT]. ErrNotExist Error = "does not exist" // ErrExist is the exists error of a path with [NotExist]. ErrExist Error = "exists" // ErrIsDir is the is a directory error of a [FileT]. ErrIsDir Error = "is a directory" // ErrNotDir is the not a directory error of a [DirT]. ErrNotDir Error = "not a directory" // ErrRequiredFlag is the required flag error of a flag with [Required] // that has no value. ErrRequiredFlag Error = "required flag" // ErrOnlyOneOf is the error of the flags of [OnlyOneOf] when two or more // of them have a value. ErrOnlyOneOf Error = "only one of the flags can be set" // ErrAllOrNoneOf is the error of the flags of [AllOrNoneOf] when some of // them have a value, and others do not. ErrAllOrNoneOf Error = "all or none of the flags must be set" // ErrAtLeastOneOf is the error of the flags of [AtLeastOneOf] when none of // them has a value. ErrAtLeastOneOf Error = "at least one of the flags must be set" )
Errors.
type ExecType ¶
type ExecType interface {
func(context.Context, []string) error |
func(context.Context, []string) |
func(context.Context) error |
func(context.Context) |
func([]string) error |
func([]string) |
func() error |
func()
}
ExecType is the interface for func's that can be used with Run, NewCommand, and Exec.
type Flag ¶
type Flag struct {
// Type is the flag's [Type].
Type Type
// MapKey is the flag's map key type when the flag is a [MapT].
MapKey Type
// Elem is the flag's element type when the flag is a [SliceT], [ArrayT] or [MapT].
Elem Type
// Name is the flag's long name (`--arg`).
Name string
// Usage is the flag's usage.
Usage string
// Short is the flag's short, single letter name (`-a`).
Short string
// Aliases are the flag's long and short aliases.
Aliases []string
// Spec is the flag's help spec.
Spec string
// Def is the flag's default value.
Def any
// NoDefault hides the "(default: ...)" text of the flag in help.
NoDefault bool
// Optional shows the flag's spec in help as an optional value, such as
// `--help[=options]`. See [OptionalValue].
Optional bool
// NoArg when true, indicates that the flag does not require an argument.
NoArg bool
// Required makes the parse fail when the flag gets no value from the
// command line, the environment or a config file. See [Required].
Required bool
// HelpValues are the values of the flag that help writes on lines of
// their own, such as `--help=commands`. See [HelpValue].
HelpValues []HelpLine
// NoArgDef is the flag's default value when no argument was passed for the
// flag.
NoArgDef any
// Binds are the bound variables that will be additionally set when the
// flag is encountered on the command-line.
Binds []Binder
// Keys are the flag's config look up keys. A key here is the whole key.
// Without one, the key is the path of the command of the flag below the
// root, then the name of the flag, such as "migrate.steps" for the flag
// --steps of the command "app migrate".
Keys map[string]string
// Section is the flag's help section.
Section int
// Hidden indicates the flag is hidden from help output.
Hidden bool
// Deprecated indicates the flag is deprecated.
Deprecated bool
// Local keeps the flag to its command. A sub command does not inherit
// it, so the command line of a sub command refuses it. See [Local].
Local bool
// Negatable gives a bool flag a negated form, such as `--no-debug`,
// without [NegateBools]. See [Negatable].
Negatable bool
// NoNegate keeps a bool flag out of [NegateBools]. See [Negatable].
NoNegate bool
// AllowPlus lets the short name of the flag take a `+`, as bash takes
// `+o name` and `+e`. See [AllowPlus].
AllowPlus bool
// OptionalAtEnd lets a flag that takes a value be the last word of the
// command line without one. See [OptionalAtEnd].
OptionalAtEnd bool
// Split is a split separator, to split values for slices/arrays/maps.
Split string
// Layout is the Go layout of a [TimestampT], [DateTimeT], [DateT] or
// [TimeT] flag, such as the layout from [Strftime]. When it is empty, the
// flag uses the layout of its type.
Layout string
// Special is the flag's special value.
Special string
// Valid are the flag's validators.
Valid []func(any) error
// Allowed are the allowed values.
Allowed []any
// EnvVar is the environment variable that fills the flag, whatever the
// prefix of the root command.
EnvVar string
// NoEnv keeps the flag out of the environment.
NoEnv bool
// NoConfig keeps the flag out of the config files.
NoConfig bool
// ConfigFile indicates that the flag names the config file.
ConfigFile bool
// HiddenAliases are the flag's long and short aliases that help does not
// write. Completion offers them.
HiddenAliases []string
// DeprecatedAliases are the flag's long and short aliases that neither
// help nor completion shows.
DeprecatedAliases []string
// Abs makes the value of a path flag absolute. See [Abs].
Abs bool
// Real resolves each symbolic link in the value of a path flag. See
// [Real].
Real bool
// Home shows a path flag's default under the home directory as `~` in
// help. See [Home].
Home bool
// NotExist makes the value of a path flag a path that must not exist.
// See [NotExist].
NotExist bool
// Exts are the file extensions that file completion offers for a path
// flag. See [Ext].
Exts []string
// CompFunc is the func that completes the flag's value. See [CompFunc].
CompFunc func(ctx *Context, toComplete string) ([]Completion, CompDirective, error)
// contains filtered or unexported fields
}
Flag is a command-line flag variable definition.
func FlagsFrom ¶
FlagsFrom creates flags for a value of type *struct using reflection. Builds flags for all exported fields with a `ox` tag, and a non-empty description.
A `ox` tag starts with the flag's description, followed by one or more options separated by `,`. If a flag description must contain a comma (`,`) it can be escaped with a double backslash (`\\`). The flag's name is determined by the result of calling DefaultFlagNameMapper, or it can be set with the `name:` option (see below).
Use the CommandOption From to add flags when creating a command with Run/RunContext/Sub/NewCommand.
Example:
args := struct{
MyFlag string `ox:"my flag,short:f,default:$USER"`
MyVerbosity int `ox:"my verbosity,type:count,short:v"`
MyURL *url.URL `ox:"my url,set:MyURLSet"`
MyURLSet bool
MyOtherFlag string `ox:"a long\\, long description,short:F"`
MyFloat float64 `ox:"my float,hidden,name:MYF"`
}{}
ox.FlagsFrom(&args)
Recognized options:
type - sets the flag's field type mapkey - sets the flag's map key type elem - sets the flag's slice/array/map element type name - sets the flag's name short - sets the flag's short (single character) name alias - adds a alias to the flag aliases - adds multiple aliases, separated by `|` to the flag hiddenaliases - adds aliases, separated by `|`, that help does not write deprecatedaliases - adds aliases, separated by `|`, that help and completion do not show spec - sets the flag's use spec default - sets the flag's default value nodefault - hides the flag's default value in help noarg - sets the flag as requiring no argument, and the default value for the flag when toggled key - sets the flag's lookup config key hook - sets the flag's special value to `hook:<type>`, and can be used to hook [Defaults]'s flags section - sets the flag's section hidden - marks the flag as hidden deprecated - marks the flag as deprecated local - keeps the flag to its command, so that a sub command does not inherit it negatable - gives a bool flag a negated form, and `negatable:false` keeps it out of [NegateBools], see [Negatable] split - set a split separator for slice/array/map values set - binds the flag's set value to a bool field in the *struct of the name required - marks the flag as required, see [Required] onlyoneof - adds the flag to a group of the name, see [OnlyOneOf] allornoneof - adds the flag to a group of the name, see [AllOrNoneOf] atleastoneof - adds the flag to a group of the name, see [AtLeastOneOf] arg - makes the field a positional argument and not a flag, in the order of the fields optional - makes a positional argument optional
From and App add each positional argument to the command, as Arg does. FlagsFrom leaves them out.
The `default:` option will be processed by Context.Interpolate when the command's flags are populated.
FlagsFrom keeps the group of the `onlyoneof`, `allornoneof` and `atleastoneof` options on each flag. From and App add the groups to the command as Command.FlagGroups.
The tag name (`ox`) can be changed by setting the DefaultStructTagName variable if necessary.
func (*Flag) SpecString ¶
SpecString returns the spec string for the flag. A hook flag shows its Flag.Spec, and shows only its name when it has no spec.
type FlagGroup ¶ added in v0.2.0
type FlagGroup struct {
// Rule is the rule between the flags.
Rule Rule
// Names are the long names of the flags.
Names []string
}
FlagGroup is a group of flags of a command, and the rule between them. A flag of the group counts when it gets a value from the command line, the environment or a config file. A default does not count.
type FlagHelpOption ¶
type FlagHelpOption = Option
type FlagOption ¶
type FlagOption = Option
FlagOption are Option's that apply to a Flag.
func Abs ¶
func Abs() FlagOption
Abs is a Flag option to make the value of a path flag absolute. A relative path is joined to the working directory.
func AllowPlus ¶ added in v0.5.0
func AllowPlus() FlagOption
AllowPlus is a Flag option that lets the short name of the flag take a `+` as well as a `-`, as bash takes `+o name` to turn an option off. The flag needs a short name, and a count refuses it. The plus form of a plain bool flag, such as `+e`, sets it to false, and takes no value. The plus form of any other flag takes its value as the `-` form does, such as `+o name`, and a hook of the flag reads the sign with Context.IsPlus. Hooks run in the order of the command line, so a program that needs the order of each `-` and `+`, as a shell does, gives each option a hook.
A word such as `+ex` is read as flags only when its first letter names a flag with AllowPlus. Each letter must then name such a flag. Any other word that starts with `+`, such as the `+%Y` of `date`, stays an argument. The struct tag option is `plus`.
Example ¶
ExampleAllowPlus takes the plus form of a short flag, as bash takes `+o name` and `+ex`. Each hook reads the sign with ctx.IsPlus, and the hooks run in the order of the command line.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
)
func main() {
options := map[string]bool{}
var order []string
set := func(ctx *ox.Context, name string) {
options[name] = !ctx.IsPlus()
order = append(order, fmt.Sprintf("%s=%t", name, options[name]))
}
letter := func(name string) func(*ox.Context) {
return func(ctx *ox.Context) {
set(ctx, name)
}
}
run := func(args ...string) {
order = nil
ox.Run(
ox.Usage("sh", "a shell"),
ox.Help(),
ox.StopAtArg(),
ox.Flags().
Var("set-option", "set an option", ox.HookT, ox.Default(set), ox.Short("o"), ox.AllowPlus(), ox.Spec("NAME")).
Hook("errexit", "exit on an error", letter("errexit"), ox.Short("e"), ox.AllowPlus()).
Hook("xtrace", "trace each command", letter("xtrace"), ox.Short("x"), ox.AllowPlus()),
ox.Exec(func(_ context.Context, args []string) {
fmt.Println(order, args)
}),
ox.Args(args...),
)
}
run("-o", "errexit", "-x", "+o", "errexit", "script.sh", "+x")
run("-ex", "+ex", "+%Y")
run("--help")
}
Output: [errexit=true xtrace=true errexit=false] [script.sh +x] [errexit=true xtrace=true errexit=false xtrace=false] [+%Y] sh a shell Usage: sh [flags] [args] Flags: -o, +o, --set-option NAME set an option -e, +e, --errexit exit on an error -x, +x, --xtrace trace each command -h, --help show help, then exit
func Bind ¶
func Bind[T *E, E any](v T) FlagOption
Bind is a Flag option to bind a variable to a flag.
Example ¶
ExampleBind binds each flag to a variable.
package main
import (
"fmt"
"net/url"
"github.com/xo/ox"
)
func main() {
var (
name string
port int
tags []string
u *url.URL
urlSet bool
)
ox.Run(
ox.Usage("serve", "serve files"),
ox.Defaults(),
ox.Flags().
String("name", "the server name", ox.Bind(&name)).
Int("port", "the port", ox.Default("8080"), ox.Bind(&port)).
Slice("tag", "a tag", ox.Bind(&tags)).
URL("upstream", "the upstream URL", ox.BindSet(&u, &urlSet)),
ox.Exec(func() {
fmt.Println("name:", name)
fmt.Println("port:", port)
fmt.Println("tags:", tags)
fmt.Println("upstream set:", urlSet)
}),
ox.Args("--name", "files", "--tag", "a", "--tag", "b"),
)
}
Output: name: files port: 8080 tags: [a b] upstream set: false
func BindRef ¶
func BindRef(value reflect.Value, set *bool) FlagOption
BindRef is a Flag option to bind a reflected value to a flag.
func BindSet ¶
func BindSet[T *E, E any](v T, set *bool) FlagOption
BindSet is a Flag option to bind a variable and a set variable to a flag.
func ConfigFlag ¶
func ConfigFlag() FlagOption
ConfigFlag is a Flag option to mark a flag whose value names the config file. When the flag has a value, its file replaces the files of ConfigFiles, and the file must exist. Its default can read the environment, such as "${env::APP_CONFIG}", and not a config file.
Example ¶
ExampleConfigFlag names the config file with a flag. The file of the flag replaces the files of ConfigFiles, and it must exist.
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/xo/ox"
)
func main() {
dir, err := os.MkdirTemp("", "app")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "other.json")
_ = os.WriteFile(path, []byte(`{"name": "from other.json"}`), 0o600)
newContext := func(args ...string) (*ox.Context, error) {
return ox.NewContext(
ox.Usage("app", "an app"),
ox.ConfigFiles("$APPCONFIG/config.json"),
ox.Flags().
String("config", "the config file", ox.Short("c"), ox.ConfigFlag()).
String("name", "the name"),
ox.Args(args...),
)
}
// the flag names a file
ctx, err := newContext("-c", path)
if err != nil {
fmt.Println(err)
return
}
if err := ctx.Parse(); err != nil {
fmt.Println(err)
return
}
fmt.Println("name:", ctx.Vars["name"])
// the flag names a file that does not exist
ctx, err = newContext("-c", filepath.Join(dir, "missing.json"))
if err != nil {
fmt.Println(err)
return
}
err = ctx.Parse()
fmt.Println(errors.Is(err, ox.ErrConfigNotFound))
}
Output: name: from other.json true
func Default ¶
func Default(def any) FlagOption
Default is a Flag option to set the flag's default value.
Special strings can be used that will be expanded when the flag is created:
$HOME - the current user's home directory
$USER - the current user's user name
$CACHE - the current user's cache directory
$STATE - the current user's state directory
$APPCACHE - the current user's cache directory, with the root command's name added as a subdir
$APPSTATE - the current user's state directory, with the root command's name added as a subdir
$ENV{KEY} - the environment value for $KEY
$CFG{[TYPE::]KEY} - the registered config file loader type and key value
For example:
ox.Default("$USER") - expands to "ken" if the user running the application is "ken"
ox.Default("$HOME") - expands to /home/$USER
ox.Default("$CACHE") - expands to /home/$USER/.cache
ox.Default("$STATE") - expands to /home/$USER/.local/state
ox.Default("$APPCACHE") - expands to /home/$USER/.cache/myApp if the root command's name is "myApp"
ox.Default("$APPSTATE") - expands to /home/$USER/.local/state/myApp if the root command's name is "myApp"
ox.Default("~/.${APPNAME|lower}rc") - expands to ~/.myapprc if the root command's name is "myApp"
ox.Default("$ENV{MY_VAR}") - expands to value of the environment var $MY_VAR
ox.Default("$CFG{yaml::a.b.c}") - expands to the registered YAML config file's key of a.b.c
ox.Default("$CFG{a.b.c}") - expands to the first registered config file that returns a non-nil value and nil error for key a.b.c
See Context.Interpolate for further details.
func DeprecatedAliases ¶
func DeprecatedAliases(aliases ...string) FlagOption
DeprecatedAliases is a Flag option to add aliases that neither help nor completion shows. A deprecated alias parses like any alias, so an old name keeps working.
func EnvVar ¶
func EnvVar(name string) FlagOption
EnvVar is a Flag option to fill the flag from the environment variable name, whatever the prefix of EnvPrefix. A hook flag is filled from the environment only with EnvVar.
func Ext ¶
func Ext(exts ...string) FlagOption
Ext is a Flag option to set the file extensions that completion offers for a path flag, such as `Ext(".yaml", ".yml")`. bash and zsh complete only the files with these extensions, and fish and PowerShell complete every file. It does not refuse a value with another extension.
func HelpValue ¶
func HelpValue(value, usage string, funcs ...func(*Context) error) FlagOption
HelpValue is a Flag option to add a value of the flag that help writes on a line of its own, with its usage, such as psql's `--help=commands`. Help writes the values after the flag, in the order of the options.
When the command line gives the flag this value, each func in funcs runs in order, in place of the flag, and the run stops as help does. The first error of a func stops the run with that error. So `--help=commands` can write a topic of its own to Context.Stdout, and `--help` still writes the help of the command. Without funcs, the flag takes the value as it takes any other value.
Example ¶
ExampleHelpValue writes a help topic of its own for a value of the help flag. Without a value, the help flag writes the help of the command.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
commands := func(ctx *ox.Context) error {
fmt.Fprintln(ctx.Stdout, `\q quit`)
fmt.Fprintln(ctx.Stdout, `\? show the commands`)
return nil
}
run := func(args ...string) {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Bool("help", "show this help, then exit", ox.Special("hook:help"), ox.OptionalValue("TOPIC"),
ox.HelpValue("commands", "list the commands, then exit", commands),
),
ox.Help(),
ox.Args(args...),
)
}
run("--help=commands")
run("--help")
}
Output: \q quit \? show the commands app an app Usage: app [flags] [args] Flags: --help[=TOPIC] show this help, then exit --help=commands list the commands, then exit
func HiddenAliases ¶
func HiddenAliases(aliases ...string) FlagOption
HiddenAliases is a Flag option to add aliases that help does not write. A hidden alias parses like any alias, and completion offers it.
func Home ¶
func Home() FlagOption
Home is a Flag option to show the default of a path flag under the home directory as `~` in help, such as `~/.config/app`. It does not change the value.
func Hook ¶
func Hook(f func(context.Context) error) FlagOption
Hook is a Flag option to set a hook for a flag. The flag takes no argument. When the flag is on the command line, the parse calls f with a context.Context that holds the Context. Read it with Ctx. The parent of that context.Context is DefaultContext, because the parse runs before Context.Run.
func Key ¶
func Key(typ, key string) FlagOption
Key is a Flag option to set the flag's config lookup key for a registered config file type.
Example ¶
ExampleKey gives a flag a config key that is not its name, for every format or for one format. NoConfig keeps a flag out of the config files.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
dir, err := os.MkdirTemp("", "app")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "config.json")
_ = os.WriteFile(path, []byte(`{"db": {"host": "db1", "port": 5433}, "password": "in-file"}`), 0o600)
ox.Run(
ox.Usage("app", "an app"),
ox.ConfigFiles(path),
ox.Flags().
String("host", "the host", ox.Key("", "db.host")).
Int("port", "the port", ox.Key("json", "db.port"), ox.Key("yaml", "database.port")).
String("password", "the password", ox.NoConfig()),
ox.Exec(func(ctx context.Context) {
fmt.Println("host:", otx.String(ctx, "host"))
fmt.Println("port:", otx.Int(ctx, "port"))
fmt.Printf("password: %q\n", otx.String(ctx, "password"))
}),
ox.Args(),
)
}
Output: host: db1 port: 5433 password: ""
func Local ¶ added in v0.2.0
func Local() FlagOption
Local is a Flag option to keep the flag to its command. A sub command does not inherit a local flag, so the command line of a sub command refuses it with ErrUnknownFlag, and completion does not offer it there. A flag that is not local works after each sub command, as before.
Local changes only the command line. The environment, a config file or the default still give the flag its value, as Context.Fill does for each flag of the command and its parents.
Example ¶
ExampleLocal keeps a flag to its command, so that a sub command refuses it. A sub command inherits every other flag of its parents.
package main
import (
"context"
"errors"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) error {
return ox.RunError(
context.Background(),
ox.Usage("app", "an app"),
ox.Flags().
String("config", "the config file").
Bool("init", "make a new config file", ox.Local()),
ox.Sub(
ox.Usage("show", "show the config"),
ox.Exec(func(ctx context.Context) {
fmt.Println("config:", otx.String(ctx, "config"))
}),
),
ox.Args(args...),
)
}
fmt.Println(run("show", "--config", "a.yaml"))
err := run("show", "--init")
fmt.Println(errors.Is(err, ox.ErrUnknownFlag), err)
}
Output: config: a.yaml <nil> true --init: unknown flag
func MapKey ¶
func MapKey(mapKey Type) FlagOption
MapKey is a Flag option to set the flag's map key type.
func Negatable ¶ added in v0.3.0
func Negatable(negatable bool) FlagOption
Negatable is a Flag option to choose whether a bool flag has a negated form, such as `--no-debug`. Negatable(false) keeps the flag out of NegateBools. Negatable(true) gives the flag a negated form without NegateBools, with the prefix of DefaultNegatePrefix. With NegateBools, the flag takes the prefixes of the root command. A flag that is not a bool flag refuses Negatable(true) with ErrAppliedToInvalidType.
func NoArg ¶
func NoArg(noArg bool, def any) FlagOption
NoArg is a Flag option to set that the flag expects no argument, and the default value to set.
Example ¶
ExampleNoArg gives a flag an optional value. Without a value, the flag takes the value of NoArg. With --flag=value, it takes that value.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
String("color", "when to use color", ox.NoArg(true, "always"), ox.Default("auto")),
ox.Exec(func(ctx context.Context, args []string) {
fmt.Println("color:", otx.String(ctx, "color"), "args:", args)
}),
ox.Args(args...),
)
}
run()
run("--color")
run("--color=never")
run("--color", "never")
}
Output: color: auto args: [] color: always args: [] color: never args: [] color: always args: [never]
func NoConfig ¶
func NoConfig() FlagOption
NoConfig is a Flag option to keep the flag out of the config files.
func NoDefault ¶
func NoDefault() FlagOption
NoDefault is a Flag option to hide the "(default: ...)" text of the flag in help. Use it when the usage of the flag already names its default.
func NoEnv ¶
func NoEnv() FlagOption
NoEnv is a Flag option to keep the flag out of the environment.
func NotExist ¶
func NotExist() FlagOption
NotExist is a Flag option to make the value of a path flag a path that must not exist yet, such as an output file.
func OptionalAtEnd ¶ added in v0.6.0
func OptionalAtEnd() FlagOption
OptionalAtEnd is a Flag option that lets a flag that takes a value be the last word of the command line without one, as bash takes a lone `-o` to list its options. The flag is set from an empty value, and its hook reads Context.NoValue as true. Anywhere else, the flag takes its value as before. A flag that takes no value refuses it with ErrAppliedToInvalidType.
func OptionalValue ¶
func OptionalValue(spec string) FlagOption
OptionalValue is a Flag option to set that the flag takes an optional value, and the spec of that value. Help writes the spec in brackets, such as `--help[=options]`. The flag takes no argument, as with NoArg, so a value must follow an `=`, such as `--help=commands`. It keeps the default that NoArg sets, and sets the empty string when there is none.
Example ¶
ExampleOptionalValue shows an optional value in the help, and writes some of its values on lines of their own.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
String("color", "when to use color", ox.OptionalValue("WHEN"),
ox.HelpValue("always", "always use color"),
ox.HelpValue("never", "never use color"),
).
Bool("quiet", "run quietly", ox.Short("q")),
ox.Help(),
ox.Args("--help"),
)
}
Output: app an app Usage: app [flags] [args] Flags: --color[=WHEN] when to use color --color=always always use color --color=never never use color -q, --quiet run quietly -h, --help show help, then exit
func Real ¶
func Real() FlagOption
Real is a Flag option to resolve each symbolic link in the value of a path flag, with Realpath. A path that does not exist is made absolute, as with Abs.
func Required ¶ added in v0.2.0
func Required() FlagOption
Required is a Flag option to make the parse fail when the flag gets no value from the command line, the environment or a config file. A default does not count. Context.Validate returns an error that wraps ErrRequiredFlag and names each flag that has no value. Help marks the flag with the text of `text.FlagRequired`. The struct tag option is `required`.
Example ¶
ExampleRequired makes a flag required. A value from the command line, the environment or a config file counts, and a default does not. Help marks the flag, and --help works without it.
package main
import (
"context"
"errors"
"fmt"
"os"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) error {
return ox.RunError(
context.Background(),
ox.Usage("deploy", "deploy the app"),
ox.Help(),
ox.EnvPrefix("DEPLOY"),
ox.Flags().
String("target", "the target", ox.Required()).
String("region", "the region", ox.Default("east")),
ox.Exec(func(ctx context.Context) {
fmt.Println("deploy to", otx.String(ctx, "target"))
}),
ox.Args(args...),
)
}
err := run()
fmt.Println(errors.Is(err, ox.ErrRequiredFlag), err)
fmt.Println(run("--target", "prod"))
_ = os.Setenv("DEPLOY_TARGET", "staging")
defer func() { _ = os.Unsetenv("DEPLOY_TARGET") }()
fmt.Println(run())
fmt.Println(run("--help"))
}
Output: true command deploy: required flag: --target deploy to prod <nil> deploy to staging <nil> deploy deploy the app Usage: deploy [flags] [args] Flags: --target string the target (required) --region string the region (default: east) -h, --help show help, then exit <nil>
func Short ¶
func Short(short string) FlagOption
Short is a Flag option to add a flag's short (single character) alias.
func Special ¶
func Special(special string) FlagOption
Special is a Flag option to set a flag's special value.
Example ¶
ExampleSpecial puts the help and version flags in a section of their own. A flag with Special("hook:help") or Special("hook:version") replaces the flag that Help or Version adds.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.VersionString("1.2.3"),
ox.Version(),
ox.Help(ox.Sections("Options", "Help options")),
ox.Flags().
String("name", "the name", ox.Section(0)).
Bool("help", "show this help, then exit", ox.Short("?"), ox.Special("hook:help"), ox.Section(1)).
Bool("version", "show the version, then exit", ox.Special("hook:version"), ox.Section(1)),
ox.Args("-?"),
)
}
Output: app an app Usage: app [flags] [args] Options: --name string the name Help options: -?, --help show this help, then exit --version show the version, then exit
func Split ¶
func Split(split string) FlagOption
Split is a Flag option to add a flag's split separator.
func Strftime ¶ added in v0.3.0
func Strftime(layout string) FlagOption
Strftime is a Flag option to read and write the time of a flag in a strftime layout, such as `%d/%m/%Y %H:%M`. A flag of type TimestampT, DateTimeT, DateT or TimeT keeps its type, and a flag of another type gets the type TimestampT. A slice, an array, a map or a hook flag refuses it.
Strftime converts the layout to a Go layout, and sets Flag.Layout. It takes only the directives that Go writes and reads in the same way:
%Y the year, such as 2006 %y the year in 2 digits, such as 06 %m the month in 2 digits, such as 01 %b the short name of the month, such as Jan %B the name of the month, such as January %d the day of the month in 2 digits, such as 02 %e the day of the month, padded with a space, such as " 2" %j the day of the year in 3 digits, such as 002 %a the short name of the day of the week, such as Mon %A the name of the day of the week, such as Monday %H the hour of 24 hours in 2 digits, such as 15 %I the hour of 12 hours in 2 digits, such as 03 %p AM or PM %M the minute in 2 digits, such as 04 %S the second in 2 digits, such as 05 %f the microseconds in 6 digits, after a . or a , %L the milliseconds in 3 digits, after a . or a , %z the offset of the zone, such as -0700 %Z the name of the zone, such as MST %T the same as %H:%M:%S %R the same as %H:%M %D the same as %m/%d/%y %F the same as %Y-%m-%d %% a %
Strftime refuses any other directive, and text between the directives that Go reads as a part of a time, such as 1 or Jan. Its error wraps ErrInvalidLayout.
Example ¶
ExampleStrftime reads a time in a strftime layout.
package main
import (
"context"
"fmt"
"time"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Var("since", "the first day", ox.Strftime("%d/%m/%Y"), ox.Default("01/11/2026")).
Var("at", "a date and time", ox.Strftime("%d %b %Y %I:%M %p")),
ox.Exec(func(ctx context.Context) {
fmt.Println("since:", otx.Get[time.Time](ctx, "since").Format(time.DateOnly))
fmt.Println("at:", otx.Time(ctx, "at"), "is", otx.TimeTime(ctx, "at").Format(time.DateTime))
}),
ox.Args("--at", "26 Nov 2026 09:30 PM"),
)
}
Output: since: 2026-11-01 at: 26 Nov 2026 09:30 PM is 2026-11-26 21:30:00
func TypeFor ¶ added in v0.2.0
func TypeFor[T any]() FlagOption
TypeFor is a Flag option that sets the type of the flag from the Go type T, as From does for the type of a field. T can be a type that reads its own text, with UnmarshalText, UnmarshalBinary or Set, or a pointer to one, and it needs no registration. Help writes the name of such a type in lower case, so a flag of type colors.Color shows `--fg color`. T can also be a type that From takes, such as int, []string or map[string]int.
ox.Flags().
Var("fg", "the foreground color", ox.TypeFor[colors.Color]())
Example ¶
ExampleTypeFor gives a flag the type slog.Level, which nothing registers. The flag reads its value with the UnmarshalText of slog.Level, and help writes its type in lower case.
package main
import (
"context"
"fmt"
"log/slog"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
ox.Run(
ox.Usage("app", "an app"),
ox.Help(),
ox.Flags().
Var("log", "the log level", ox.TypeFor[slog.Level](), ox.Default("info")),
ox.Exec(func(ctx context.Context) {
fmt.Println("log:", otx.Get[slog.Level](ctx, "log"))
}),
ox.Args(args...),
)
}
run("--log", "debug")
run("--help")
}
Output: log: DEBUG app an app Usage: app [flags] [args] Flags: --log level the log level (default: info) -h, --help show help, then exit
func Valid ¶
func Valid[T cmp.Ordered](values ...T) FlagOption
Valid is a Flag option to add a allowed value validator to a flag.
Example ¶
ExampleValid allows only some values for a flag.
package main
import (
"errors"
"fmt"
"github.com/xo/ox"
)
func main() {
ctx, err := ox.NewContext(
ox.Usage("app", "an app"),
ox.Flags().
String("format", "the output format", ox.Valid("json", "yaml")),
ox.Args("--format", "xml"),
)
if err != nil {
fmt.Println(err)
return
}
err = ctx.Parse()
fmt.Println(err)
fmt.Println(errors.Is(err, ox.ErrInvalidValue))
}
Output: --format: invalid value: "xml": allowed values: "json", "yaml" true
type FlagSet ¶
type FlagSet struct {
Flags []*Flag
}
FlagSet is a set of command-line flag definitions.
func (*FlagSet) Addr ¶
Addr adds a netip.Addr variable to the flag set.
func (*FlagSet) AddrPort ¶
AddrPort adds a netip.AddrPort variable to the flag set.
func (*FlagSet) BigFloat ¶
BigFloat adds a math/big.Float variable to the flag set.
func (*FlagSet) BigInt ¶
BigInt adds a math/big.Int variable to the flag set.
func (*FlagSet) BigRat ¶
BigRat adds a math/big.Rat variable to the flag set.
func (*FlagSet) CIDR ¶
CIDR adds a netip.Prefix variable to the flag set.
func (*FlagSet) Complex128 ¶
Complex128 adds a complex128 variable to the flag set.
func (*FlagSet) Count ¶
Count adds a count variable to the flag set.
Example ¶
ExampleFlagSet_Count counts each use of a flag, such as -vvv.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Count("verbose", "verbosity", ox.Short("v")),
ox.Exec(func(ctx context.Context) {
fmt.Println("verbose:", otx.Count(ctx, "verbose"))
}),
ox.Args("-vvv", "--verbose"),
)
}
Output: verbose: 4
func (*FlagSet) Date ¶
Date adds a time.Time variable to the flag set in the expected format of time.DateOnly.
Example ¶
ExampleFlagSet_Date reads a date, a date and time, and a timestamp.
package main
import (
"context"
"fmt"
"time"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Date("since", "the first day").
DateTime("at", "a date and time").
Timestamp("until", "an RFC 3339 timestamp"),
ox.Exec(func(ctx context.Context) {
fmt.Println("since:", otx.TimeTime(ctx, "since").Format(time.DateOnly))
fmt.Println("at:", otx.TimeTime(ctx, "at").Format(time.DateTime))
fmt.Println("until:", otx.TimeTime(ctx, "until").Format(time.RFC3339))
}),
ox.Args("--since", "2026-11-01", "--at", "2026-11-26 09:30:00", "--until", "2026-12-01T00:00:00Z"),
)
}
Output: since: 2026-11-01 at: 2026-11-26 09:30:00 until: 2026-12-01T00:00:00Z
func (*FlagSet) DateTime ¶
DateTime adds a time.Time variable to the flag set in the expected format of time.DateTime.
func (*FlagSet) Duration ¶
Duration adds a time.Duration variable to the flag set.
Example ¶
ExampleFlagSet_Duration reads a duration, such as 1m30s.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Duration("timeout", "the timeout", ox.Default("30s")),
ox.Exec(func(ctx context.Context) {
fmt.Println("timeout:", otx.Duration(ctx, "timeout"))
}),
ox.Args("--timeout", "1m30s"),
)
}
Output: timeout: 1m30s
func (*FlagSet) File ¶
File adds a variable to the flag set for a file that exists. See FileT.
Example ¶
ExampleFlagSet_File reads a file and a directory that must exist.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
run := func(args ...string) {
err := ox.RunError(
context.Background(),
ox.Usage("app", "an app"),
ox.Flags().
File("config", "the config file", ox.Ext(".yaml", ".yml")).
Dir("out", "the output directory"),
ox.Exec(func(ctx context.Context) {
fmt.Println("config:", otx.String(ctx, "config"), "out:", otx.String(ctx, "out"))
}),
ox.Args(args...),
)
if err != nil {
fmt.Println(err)
}
}
run("--config", "go.mod", "--out", "docs")
run("--config", "missing.yaml")
run("--config", "docs")
run("--out", "go.mod")
}
Output: config: go.mod out: docs --config: invalid value: missing.yaml: does not exist --config: invalid value: docs: is a directory --out: invalid value: go.mod: not a directory
func (*FlagSet) Hook ¶
Hook adds a hook to the flag set.
Example ¶
ExampleFlagSet_Hook calls a func for each use of a flag, in the order of the command line. The flag takes a value, because it has no NoArg.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
var vars []string
set := func(s string) {
vars = append(vars, s)
}
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Var("set", "set variable NAME to VALUE", ox.HookT, ox.Default(set), ox.Short("v")).
String("file", "a file", ox.Short("f")),
ox.Exec(func() {
fmt.Println("vars:", vars)
}),
ox.Args("--set", "a=1", "-f", "x.sql", "-v", "b=2", "--set=c=3"),
)
}
Output: vars: [a=1 b=2 c=3]
func (*FlagSet) Map ¶
Map adds a map variable to the flag set.
Example ¶
ExampleFlagSet_Map reads key=value pairs.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Map("label", "a label", ox.Short("l")).
Map("limit", "a limit", ox.IntT),
ox.Exec(func(ctx context.Context) {
fmt.Println("labels:", otx.Map[string, string](ctx, "label"))
fmt.Println("limits:", otx.Map[string, int](ctx, "limit"))
}),
ox.Args("-l", "a=1", "-l", "b=2,c=3", "--limit", "cpu=2"),
)
}
Output: labels: map[a:1 b:2 c:3] limits: map[cpu:2]
func (*FlagSet) Option ¶
func (fs *FlagSet) Option() option
Option returns a CommandOption for the flag set.
func (*FlagSet) PortRange ¶ added in v0.3.0
PortRange adds a PortRange variable to the flag set.
Example ¶
ExampleFlagSet_PortRange reads a port range, and a slice of port ranges.
package main
import (
"context"
"fmt"
"slices"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
PortRange("ports", "the ports to listen on", ox.Default("8000-8099")).
Slice("allow", "the ports to allow", ox.PortRangeT),
ox.Exec(func(ctx context.Context) {
ports := otx.Get[ox.PortRange](ctx, "ports")
fmt.Println("ports:", ports, ports.Lo, ports.Hi, ports.Contains(8080))
for _, r := range otx.Slice[ox.PortRange](ctx, "allow") {
fmt.Println("allow:", r, slices.Collect(r.Ports()))
}
}),
ox.Args("--ports", "8080:8081", "--allow", "22,443-445"),
)
}
Output: ports: 8080-8081 8080 8081 true allow: 22 [22] allow: 443-445 [443 444 445]
func (*FlagSet) Regexp ¶
Regexp adds a regexp.Regexp variable to the flag set.
func (*FlagSet) Size ¶
Size adds a Size variable to the flag set.
Example ¶
ExampleFlagSet_Size reads a size in bytes, and a rate in bytes per unit of time.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Size("max", "the maximum size", ox.Default("1MiB")).
Rate("limit", "the rate limit"),
ox.Exec(func(ctx context.Context) {
size := otx.Get[ox.Size](ctx, "max")
rate := otx.Get[ox.Rate](ctx, "limit")
fmt.Println("max:", size, int64(size))
fmt.Println("limit:", rate)
}),
ox.Args("--max", "1.5GiB", "--limit", "10MiB/s"),
)
}
Output: max: 1.5 GiB 1610612736 limit: 10 MiB/s
func (*FlagSet) Slice ¶
Slice adds a slice variable to the flag set.
Example ¶
ExampleFlagSet_Slice reads a flag more than one time, or a list split by a comma.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
Slice("tag", "a tag", ox.Short("t")).
Slice("port", "a port", ox.IntT).
Slice("path", "a search path", ox.Split(":")),
ox.Exec(func(ctx context.Context) {
fmt.Println("tags:", otx.Slice[string](ctx, "tag"))
fmt.Println("ports:", otx.Slice[int](ctx, "port"))
fmt.Println("path:", otx.Slice[string](ctx, "path"))
}),
ox.Args("-t", "a", "-t", "b,c", "--port", "80,443", "--path", "/bin:/usr/bin"),
)
}
Output: tags: [a b c] ports: [80 443] path: [/bin /usr/bin]
func (*FlagSet) Timestamp ¶
Timestamp adds a time.Time variable to the flag set in the expected format of time.RFC3339.
func (*FlagSet) URL ¶
URL adds a url.URL variable to the flag set.
Example ¶
ExampleFlagSet_URL reads a URL.
package main
import (
"context"
"fmt"
"github.com/xo/ox"
"github.com/xo/ox/otx"
)
func main() {
ox.Run(
ox.Usage("app", "an app"),
ox.Flags().
URL("endpoint", "the endpoint"),
ox.Exec(func(ctx context.Context) {
u := otx.URL(ctx, "endpoint")
fmt.Println("host:", u.Host)
fmt.Println("path:", u.Path)
}),
ox.Args("--endpoint", "https://example.com:8443/api"),
)
}
Output: host: example.com:8443 path: /api
type FormattedTime ¶
type FormattedTime struct {
// contains filtered or unexported fields
}
FormattedTime wraps a time value with a specific layout.
func (FormattedTime) Format ¶
func (val FormattedTime) Format(layout string) string
Format formats the time value as the provided layout.
func (FormattedTime) IsValid ¶
func (val FormattedTime) IsValid() bool
IsValid returns true when the time is not zero.
func (*FormattedTime) Set ¶
func (val *FormattedTime) Set(s string) error
Set sets parses the time value from the string.
func (FormattedTime) String ¶
func (val FormattedTime) String() string
String satisfies the fmt.Stringer interface.
type HelpLine ¶
type HelpLine struct {
// Name is the name, such as `commands` for `--help=commands`, or `DSN`.
Name string
// Usage is the usage of the name.
Usage string
// Funcs are the funcs that run when the command line gives a flag the
// value. See [HelpValue]. [ArgUsage] gives none.
Funcs []func(*Context) error
}
HelpLine is a name and its usage, which help writes on a line of its own, such as a value of a flag from HelpValue, or a positional argument from ArgUsage.
type HelpOption ¶
type HelpOption = Option
HelpOption are Option's that apply to Help.
func ArgUsage ¶
func ArgUsage(name, usage string) HelpOption
ArgUsage is a Help option to add the name and the usage of a positional argument, such as `DSN`. Help writes each one in an `Arguments:` section after the usage, in the order of the options.
Example ¶
ExampleArgUsage describes a positional argument in the help, and gets the help as a string.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
ctx, err := ox.NewContext(
ox.Usage("sql", "run SQL"),
ox.Help(
ox.Spec("[OPTION]... [DSN]"),
ox.ArgUsage("DSN", "a URL, or the name of a connection"),
),
ox.Flags().
String("command", "run one command, then exit", ox.Short("c")),
)
if err != nil {
fmt.Println(err)
return
}
fmt.Print(ctx.Root.UsageString())
}
Output: sql run SQL Usage: sql [OPTION]... [DSN] Arguments: DSN a URL, or the name of a connection Flags: -c, --command string run one command, then exit -h, --help show help, then exit
func Footer ¶
func Footer(footer string) HelpOption
Footer is a Help option to set the command/flag's footer.
func Sections ¶
func Sections(sections ...string) HelpOption
Sections is a Help option to set section names for commands when used with a Command or flag sections when used with Help.
Example ¶
ExampleSections puts the flags in sections of the help.
package main
import (
"github.com/xo/ox"
)
func main() {
ox.Run(
ox.Usage("db", "connect to a database"),
ox.Defaults(
ox.Sections("Connection options", "Output options"),
),
ox.Flags().
String("host", "the host", ox.Section(0)).
Int("port", "the port", ox.Default("5432"), ox.Section(0)).
Bool("csv", "write CSV", ox.Section(1)).
Bool("json", "write JSON", ox.Section(1)).
String("log", "the log file"),
ox.Args("--help"),
)
}
Output: db connect to a database Usage: db [flags] [args] Flags: --log string the log file -v, --version show version, then exit -h, --help show help, then exit Connection options: --host string the host --port int the port (default: 5432) Output options: --csv write CSV --json write JSON
type OnErr ¶
type OnErr uint8
OnErr is the on error handling type.
type Option ¶
type Option interface {
Option() option
}
Option is the interface for options that can be passed when creating a Context, Command, Flag, or Help.
The Option type is aliased as ContextOption, CommandOption, CommandFlagOption, FlagOption, HelpOption, FlagHelpOption and provided for ease-of-use, readibility, and categorization within documentation.
A ContextOption can be applied to a Context and passed to Run/RunContext.
A CommandOption can be applied to a Command and passed to NewCommand.
A CommandFlagOption can be applied to either a Command or Flag, and can be passed to NewCommand and NewFlag.
A FlagOption can be applied to a Flag and passed to NewFlag.
A HelpOption can be passed to Help or to NewCommandHelp.
A FlagHelpOption can be applied to a Flag, passed to NewFlag, or passed to Help.
Additionally, a OnErr and SectionMap can be used as a CommandOption or in calls to NewCommand, and a Type can be used as a FlagOption in calls to NewFlag.
type PortRange ¶ added in v0.3.0
type PortRange struct {
Lo, Hi uint16
}
PortRange is a range of TCP or UDP ports, from Lo to Hi, inclusive. A valid range has 1 <= Lo <= Hi. The zero PortRange is not valid, and it holds no port. See ParsePortRange for the text that it reads.
func ParsePortRange ¶ added in v0.3.0
ParsePortRange parses a port, such as 80, or a range of ports, such as 100-200 or 100:200. Each port is 1 to 65535, and the first port is not greater than the last. ParsePortRange refuses a sign, a space and an empty port, such as 100- or :200.
func (PortRange) Contains ¶ added in v0.3.0
Contains returns true when the range is valid and holds port.
func (PortRange) MarshalText ¶ added in v0.3.0
MarshalText satisfies the encoding.TextMarshaler interface. It writes the text of PortRange.String.
func (PortRange) Ports ¶ added in v0.3.0
Ports returns an iterator over each port of the range, in order. A range that is not valid has no port.
func (PortRange) String ¶ added in v0.3.0
String satisfies the fmt.Stringer interface. It writes 100-200, or 80 when Lo and Hi are the same. The zero PortRange writes nothing.
func (*PortRange) UnmarshalText ¶ added in v0.3.0
UnmarshalText satisfies the encoding.TextUnmarshaler interface. It reads the text of ParsePortRange. Empty text gives the zero PortRange.
type Rate ¶
Rate is a byte rate.
func NewRate ¶
func NewRate[T ~int64 | ~int32 | ~int16 | ~int8 | ~int | ~uint64 | ~uint32 | ~uint16 | ~uint8 | ~uint](size T, unit time.Duration) Rate
NewRate creates a byte rate.
func (Rate) Format ¶
Format satisfies the fmt.Formatter interface. See AppendRate for recognized verbs.
func (Rate) MarshalText ¶
MarshalText satisfies the BinaryMarshalUnmarshaler interface.
func (*Rate) UnmarshalText ¶
UnmarshalText satisfies the BinaryMarshalUnmarshaler interface.
type Rule ¶ added in v0.2.0
type Rule int
Rule is a rule between the flags of a FlagGroup.
const ( // RuleOnlyOneOf allows one flag of the group at most. See [OnlyOneOf]. RuleOnlyOneOf Rule = iota // RuleAllOrNoneOf needs each flag of the group, or none of them. See // [AllOrNoneOf]. RuleAllOrNoneOf // RuleAtLeastOneOf needs one flag of the group at least. See // [AtLeastOneOf]. RuleAtLeastOneOf )
Rules.
type SectionMap ¶
SectionMap is a Command option to apply refined sections to commands and flags.
func (SectionMap) Option ¶
func (m SectionMap) Option() option
Option satisfies the Option interface.
type Size ¶
type Size int64
Size is a byte size.
func NewSize ¶
func NewSize[T ~int64 | ~int32 | ~int16 | ~int8 | ~int | ~uint64 | ~uint32 | ~uint16 | ~uint8 | ~uint](size T) Size
NewSize creates a byte size.
func ParseSize ¶
ParseSize parses a byte size string, such as 1.5GiB, 1536Mi, 6G or 100. A suffix can follow a space. A number without a suffix can have an exponent instead, as a Kubernetes quantity can, such as 6e9 or 1E3. An integer, with or without a suffix, gives the exact number of bytes. ParseSize refuses a value that does not fit in an int64.
func (Size) Format ¶
Format satisfies the fmt.Formatter interface. See AppendSize for recognized verbs.
Example ¶
ExampleSize_Format writes a size in the exact form of a Kubernetes quantity.
package main
import (
"fmt"
"github.com/xo/ox"
)
func main() {
for _, s := range []string{"6Gi", "1.5Gi", "1500Mi", "6e9", "100"} {
size, err := ox.ParseSize(s)
if err != nil {
panic(err)
}
fmt.Printf("%s: %q % q %Q %e\n", s, size, size, size, size)
}
rate, err := ox.ParseRate("1.5Gi/s")
if err != nil {
panic(err)
}
fmt.Printf("rate: %q\n", rate)
}
Output: 6Gi: 6Gi 6 Gi 6442450944 6Gi 1.5Gi: 1536Mi 1536 Mi 1610612736 1.5Gi 1500Mi: 1500Mi 1500 Mi 1572864k 1.46Gi 6e9: 5859375Ki 5859375 Ki 6G 5.59Gi 100: 100 100 100 100 rate: 1536Mi/s
func (Size) MarshalText ¶
MarshalText satisfies the BinaryMarshalUnmarshaler interface.
func (*Size) UnmarshalText ¶
UnmarshalText satisfies the BinaryMarshalUnmarshaler interface.
type StringWriter ¶
type StringWriter interface {
io.StringWriter
Len() int
}
StringWriter extends the io.StringWriter interface with a Len() method, allowing both strings.Builder and bytes.Buffer to be used when generating help output.
func NewStringWriter ¶
func NewStringWriter(w io.Writer) StringWriter
NewStringWriter converts a writer to a StringWriter, or wraps the writer when necessary. Wraps (or directly returns) os.File, strings.Builder, bytes.Buffer, or other io.Writer.
type SuggestionError ¶
SuggestionError is a suggestion error.
func (*SuggestionError) Error ¶
func (err *SuggestionError) Error() string
Error satisfies the [error] interface.
func (*SuggestionError) ErrorDetails ¶
func (err *SuggestionError) ErrorDetails() string
ErrorDetails returns error details. Used by DefaultErrorHandler.
func (*SuggestionError) Unwrap ¶
func (err *SuggestionError) Unwrap() error
Unwrap satisfies the errors.Unwrap interface.
type TextMarshalUnmarshaler ¶
type TextMarshalUnmarshaler interface {
encoding.TextMarshaler
encoding.TextUnmarshaler
}
TextMarshalUnmarshaler is the text marshal interface.
type Type ¶
type Type string
Type is a variable type.
const ( BytesT Type = "bytes" StringT Type = "string" RunesT Type = "runes" Base64T Type = "base64" HexT Type = "hex" BoolT Type = "bool" ByteT Type = "byte" RuneT Type = "rune" Int64T Type = "int64" Int32T Type = "int32" Int16T Type = "int16" Int8T Type = "int8" IntT Type = "int" Uint64T Type = "uint64" Uint32T Type = "uint32" Uint16T Type = "uint16" Uint8T Type = "uint8" UintT Type = "uint" Float64T Type = "float64" Float32T Type = "float32" Complex128T Type = "complex128" Complex64T Type = "complex64" SizeT Type = "size" RateT Type = "rate" PortRangeT Type = "portrange" TimestampT Type = "timestamp" DateTimeT Type = "datetime" DateT Type = "date" TimeT Type = "time" DurationT Type = "duration" CountT Type = "count" PathT Type = "path" FileT Type = "file" DirT Type = "dir" BigIntT Type = "bigint" BigFloatT Type = "bigfloat" BigRatT Type = "bigrat" AddrT Type = "addr" AddrPortT Type = "addrport" CIDRT Type = "cidr" RegexpT Type = "regexp" URLT Type = "url" UUIDT Type = "uuid" SliceT Type = "slice" ArrayT Type = "array" MapT Type = "map" HookT Type = "hook" )
Types.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
_examples
|
|
|
app
command
Command app is an example of a program that ox builds from a struct and its doc comments, with ox.AppFrom.
|
Command app is an example of a program that ox builds from a struct and its doc comments, with ox.AppFrom. |
|
bind
command
_examples/bind/main.go
|
_examples/bind/main.go |
|
context
command
_examples/context/main.go
|
_examples/context/main.go |
|
embedded
command
_examples/embedded/main.go
|
_examples/embedded/main.go |
|
gen/docker
command
Command docker is a xo/ox version of `docker`.
|
Command docker is a xo/ox version of `docker`. |
|
gen/doctl
command
Command doctl is a xo/ox version of `doctl`.
|
Command doctl is a xo/ox version of `doctl`. |
|
gen/gh
command
Command gh is a xo/ox version of `gh`.
|
Command gh is a xo/ox version of `gh`. |
|
gen/helm
command
Command helm is a xo/ox version of `helm`.
|
Command helm is a xo/ox version of `helm`. |
|
gen/hugo
command
Command hugo is a xo/ox version of `hugo`.
|
Command hugo is a xo/ox version of `hugo`. |
|
gen/kubectl
command
Command kubectl is a xo/ox version of `kubectl`.
|
Command kubectl is a xo/ox version of `kubectl`. |
|
gen/omnictl
command
Command omnictl is a xo/ox version of `omnictl`.
|
Command omnictl is a xo/ox version of `omnictl`. |
|
gen/podman
command
Command podman is a xo/ox version of `podman`.
|
Command podman is a xo/ox version of `podman`. |
|
gen/psql
command
Command psql is a xo/ox version of `psql`.
|
Command psql is a xo/ox version of `psql`. |
|
gen/rclone
command
Command rclone is a xo/ox version of `rclone`.
|
Command rclone is a xo/ox version of `rclone`. |
|
gen/talosctl
command
Command talosctl is a xo/ox version of `talosctl`.
|
Command talosctl is a xo/ox version of `talosctl`. |
|
greet
command
Command greet says hello.
|
Command greet says hello. |
|
paint
command
Command paint is the struct example in the README of ox.
|
Command paint is the struct example in the README of ox. |
|
reflect
command
_examples/reflect/main.go
|
_examples/reflect/main.go |
|
test
command
Command test reads its flags from a struct with nested structs, with ox.From, and writes what it read.
|
Command test reads its flags from a struct with nested structs, with ox.From, and writes what it read. |
|
tree
command
Command tree is a small command tree for testing shell completion by hand.
|
Command tree is a small command tree for testing shell completion by hand. |
|
usql
command
Command usql is a sample of the command line of usql, built with ox as usql builds it.
|
Command usql is a sample of the command line of usql, built with ox as usql builds it. |
|
_tools
|
|
|
cobraimport
command
Command cobraimport imports the completion scripts of cobra into comp/.
|
Command cobraimport imports the completion scripts of cobra into comp/. |
|
oximport
command
Command oximport reads the command-line interface of a program and writes an ox program that has the same commands and flags.
|
Command oximport reads the command-line interface of a program and writes an ox program that has the same commands and flags. |
|
cmd
|
|
|
oxdoc
command
Command oxdoc writes the doc comments of the struct types of a Go package into a file of that package, so that ox.App and ox.From can read them when the program runs.
|
Command oxdoc writes the doc comments of the struct types of a Go package into a file of that package, so that ox.App and ox.From can read them when the program runs. |
|
color
module
|
|
|
hcl
module
|
|
|
Package ini registers the INI config file format for ox.
|
Package ini registers the INI config file format for ox. |
|
Package metadoc writes the docs of an ox command tree, as a man page or as Markdown.
|
Package metadoc writes the docs of an ox command tree, as a man page or as Markdown. |
|
Package otx provides context.Context access methods for xo/ox.
|
Package otx provides context.Context access methods for xo/ox. |
|
Package strcase provides methods to convert CamelCase to and from snake_case.
|
Package strcase provides methods to convert CamelCase to and from snake_case. |
|
Package text contains the text strings for xo/ox.
|
Package text contains the text strings for xo/ox. |
|
toml
module
|
|
|
yaml
module
|