Documentation ¶
Overview ¶
Package ox is a minimal dependency Go (and TinyGo compatible) command-line flag and argument parsing library.
Example ¶
Example is a quick example demonstrating 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 provides an example for 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 (Help) ¶
Example_help shows 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:L,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), // this is used to override the expansion parameters ox.Override(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 -L, --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 (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.
Index ¶
- Constants
- Variables
- func AddHelpFlag(cmd *Command) error
- 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 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 ParseFlagShort(ctx *Context, cmd *Command, s string, args []string) ([]string, error)
- func RegisterBinaryType[T BinaryMarshalUnmarshaler](f func() (T, error))
- func RegisterConfig(typ string, h ConfigValueDecoder)
- func RegisterConfigLoader(typ string, handler func(...any) (ConfigLoader, error))
- 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 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 WithContext(parent context.Context, ctx *Context) context.Context
- func Wrap(s string, width, prefixWidth int) string
- 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) 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) Path() []string
- func (cmd *Command) RootName() string
- func (cmd *Command) Sub(opts ...Option) error
- func (cmd *Command) Suggest(args ...string) error
- func (cmd *Command) Tree() []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
- type CommandHelp
- func (help *CommandHelp) AddAliases(sb *strings.Builder)
- func (help *CommandHelp) AddBanner(sb *strings.Builder)
- func (help *CommandHelp) AddCommands(sb *strings.Builder)
- func (help *CommandHelp) AddExample(sb *strings.Builder)
- func (help *CommandHelp) AddFlags(sb *strings.Builder)
- func (help *CommandHelp) AddFooter(sb *strings.Builder)
- func (help *CommandHelp) AddUsage(sb *strings.Builder)
- func (help *CommandHelp) SetContext(ctx *Context)
- func (help *CommandHelp) WriteTo(w io.Writer) (int64, error)
- type CommandOption
- func ArgsFunc(funcs ...func([]string) error) CommandOption
- func CommandSort(commandSort bool) CommandOption
- func Comp() CommandOption
- func Defaults(opts ...Option) CommandOption
- func Exec[F ExecType](f F) CommandOption
- func From[T *E, E any](val T) CommandOption
- func Help(opts ...Option) CommandOption
- func MaxDist(maxDist int) CommandOption
- func Parent(parent *Command) CommandOption
- func Sort(sort bool) CommandOption
- func Sub(opts ...Option) CommandOption
- func Suggested(suggested ...string) CommandOption
- func UserConfigFile() CommandOption
- func ValidArgs(minimum, maximum int, values ...string) CommandOption
- func Version() CommandOption
- type CompDirective
- type Completion
- type ConfigLoader
- type ConfigValueDecoder
- type Context
- func (ctx *Context) Comps() ([]Completion, CompDirective, error)
- func (ctx *Context) Expand(v any) (string, error)
- 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
- type Error
- type ExecFunc
- type ExecType
- type Flag
- type FlagHelpOption
- type 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 Default(def any) FlagOption
- func Elem(elem Type) FlagOption
- func Hook(f func(context.Context) error) FlagOption
- func Key(typ, key string) FlagOption
- func MapKey(mapKey Type) FlagOption
- func NoArg(noArg bool, def any) FlagOption
- func Short(short string) FlagOption
- func Special(special string) FlagOption
- func Split(split string) 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) Color(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Complex128(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Complex64(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) Duration(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) Glob(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) 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) Int8(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) 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) 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) Uint8(name, usage string, opts ...Option) *FlagSet
- func (fs *FlagSet) Var(name, usage string, opts ...Option) *FlagSet
- type FormattedTime
- type HelpOption
- type OnErr
- type Option
- type Rate
- type SectionMap
- type Size
- type SuggestionError
- type TextMarshalUnmarshaler
- type Type
- type Value
- type Vars
Examples ¶
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 ( // DefaultContext is the default [context.Context]. DefaultContext = context.Background() // DefaultStructTagName is the default struct tag name used in [FromFlags] // and related func's. 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 // DefaultWrap wraps sections of text (separated by "\n\n") using [Wrap]. DefaultWrap = func(s string, wrapWidth, prefixWidth int) string { sb := new(strings.Builder) for i, line := range strings.Split(s, "\n\n") { if i != 0 { _, _ = sb.WriteString("\n\n") _, _ = sb.WriteString(strings.Repeat(" ", prefixWidth)) } _, _ = sb.WriteString(Wrap(line, wrapWidth, prefixWidth)) } return sb.String() } // DefaultWidth returns the width of a string used by [Wrap]. DefaultWidth = func(s string) int { return len(s) } // DefaultFlagNameMaper is the default flag name mapper. DefaultFlagNameMapper = func(s string) string { return strings.ReplaceAll(strcase.CamelToSnake(s), "_", "-") } // DefaultVersionString is the default version string. DefaultVersionString = "0.0.0-dev" // 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 { ver := BuildVersion() var name string if ctx != nil && ctx.Root != nil { name = ctx.Root.Name } 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 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 } } // 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 } fmt.Fprintf(w, text.ErrorMessage, err) if v, ok := err.(interface{ ErrorDetails() string }); ok { fmt.Fprint(w, v.ErrorDetails()) } code := 1 if v, ok := err.(interface{ ErrorCode() int }); ok { code = v.ErrorCode() } 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 distance for suggestions. DefaultMaxDist = 2 // 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 active help suffix. DefaultCompActiveHelpSuffix = "_ACTIVE_HELP" // 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 := strings.ToUpper(varName) + DefaultCompActiveHelpSuffix 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 { ctx.Handler(err) ctx.Exit(1) } for _, comp := range comps { if !noDescriptions { _, _ = fmt.Fprintln(ctx.Stdout, comp.Name+"\t"+comp.Usage) } else { _, _ = fmt.Fprintln(ctx.Stdout, comp.Name) } } _, _ = fmt.Fprintf(ctx.Stdout, ":%d\n", dir) _, _ = fmt.Fprintf(ctx.Stderr, "COMP ENDED: %s\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 // DefaultRateUnit is the default [Rate] unit. DefaultRateUnit = time.Second )
Functions ¶
func AddHelpFlag ¶
AddHelpFlag recursively adds a `--help` flag for all commands in the command tree, copying the command's [CommandHelp.Sort], [CommandHelp.CommandSort], and [CommandHelp.MaxDist] settings.
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.
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 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) p/P - size in PB/PiB (ex: 4.5 PiB) s/S - same as f/F v/V - same as f/F
func BuildVersion ¶
func BuildVersion() string
BuildVersion returns the Go build version, or DefaultVersionString.
func FormatRate ¶
FormatRate formats a byte rate.
func FormatSize ¶
FormatSize formats a byte size.
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').
func ParseFlagShort ¶
ParseFlagShort parses short flags ('-a' '-aaa' '-av' '-a v' '-a=' '-a=v').
func RegisterBinaryType ¶
func RegisterBinaryType[T BinaryMarshalUnmarshaler](f func() (T, error))
RegisterBinaryType registers a new binary type.
func RegisterConfigLoader ¶
func RegisterConfigLoader(typ string, handler func(...any) (ConfigLoader, error))
RegisterConfigLoader registers a config file type.
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.
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 WithContext ¶
WithContext adds a Context to the parent context.Context.
Types ¶
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 // 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. 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 // Comp enables completion for the command. Comp bool // Section is the help section. Section int // 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 }
Command is a command.
func NewCommand ¶
NewCommand creates a new command.
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.
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) Suggest ¶
Suggest returns a SuggestionError if there is a matching sub command within the command's help distance.
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 Deprecated ¶
func Deprecated(deprecated bool) CommandFlagOption
Deprecated is a Command/Flag option to set the command/flag's deprecated.
func Hidden ¶
func Hidden(hidden bool) CommandFlagOption
Hidden is a Command/Flag option to set the command/flag's hidden.
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 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. 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(sb *strings.Builder)
AddAliases adds the command's aliases.
func (*CommandHelp) AddBanner ¶
func (help *CommandHelp) AddBanner(sb *strings.Builder)
AddBanner adds the command's banner.
func (*CommandHelp) AddCommands ¶
func (help *CommandHelp) AddCommands(sb *strings.Builder)
AddCommands adds the command's sub commands.
func (*CommandHelp) AddExample ¶
func (help *CommandHelp) AddExample(sb *strings.Builder)
AddExample adds the command's example.
func (*CommandHelp) AddFlags ¶
func (help *CommandHelp) AddFlags(sb *strings.Builder)
AddFlags adds the command's flags.
func (*CommandHelp) AddFooter ¶
func (help *CommandHelp) AddFooter(sb *strings.Builder)
AddFooter adds the command's footer.
func (*CommandHelp) AddUsage ¶
func (help *CommandHelp) AddUsage(sb *strings.Builder)
AddUsage adds the command's usage.
func (*CommandHelp) SetContext ¶
func (help *CommandHelp) SetContext(ctx *Context)
SetContext sets the context on the command help.
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 ArgsFunc ¶
func ArgsFunc(funcs ...func([]string) error) CommandOption
ArgsFunc is a Command option to add funcs to command's argument validation funcs.
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 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 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 of the available tag options.
func Help ¶
func Help(opts ...Option) CommandOption
Help is a Command option to add help output to a root command. By default, it adds a `--help` flag to all commands in the command tree. The root command will have a `help` sub command added if there are any other defined sub commands.
func MaxDist ¶
func MaxDist(maxDist int) CommandOption
MaxDist is a Command option to set the maximum Levenshtein for flags when used with a Command.
func Parent ¶
func Parent(parent *Command) CommandOption
Parent is a Command option to set the command's parent.
func Sort ¶
func Sort(sort bool) CommandOption
Sort is a Command option to set the sort for flags when used with a Command.
func Suggested ¶
func Suggested(suggested ...string) CommandOption
Suggested is a Command option to add suggested names for the command.
func UserConfigFile ¶
func UserConfigFile() CommandOption
UserConfigFile is a Command option to load a config file from the user's config directory.
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.
func Version ¶
func Version() CommandOption
Version is a Command option to hook --version with version output.
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 // 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 NewCompletion ¶
func NewCompletion(name, usage string, dist int) Completion
NewCompletion creates a completion.
type ConfigLoader ¶
ConfigLoader is the interface for configuration decoders.
type ConfigValueDecoder ¶
ConfigGetter
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 // 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 are overriding expansions. Override map[string]string // 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 }
Context is a Run/RunContext execution context.
func Ctx ¶
Ctx returns the context from the context.Context.
func NewContext ¶
NewContext creates a new run context.
func (*Context) Comps ¶
func (ctx *Context) Comps() ([]Completion, CompDirective, error)
Comps returns the completions for the context.
func (*Context) Expand ¶
Expand expands variables in v, where any variable can be the following:
$HOME - the current user's home directory (ex: ~/) $USER - the current user's user name (ex: user) $APPNAME - the root command's name (ex: appName) $CONFIG - the current user's config directory (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 (ex: ~/.cache) $APPCACHE - the current user's cache directory, with the root command's name added as a subdir (ex: ~/.cache/appName) $NUMCPU - the value of [runtime.NumCPU] (ex: 4) $ARCH - the value of [runtime.GOARCH] (ex: amd64) $OS - the value of [runtime.GOOS] (ex: windows) $ENV{KEY} - the environment value for $KEY $CONFIG_TYPE{KEY} - the registered config file loader type and key value, for example: `$YAML{my_key}`, `$TOML{my_key}`
TODO: finish implementation for $CONFIG_TYPE, expand anywhere in string
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 Override ¶
func Override(override map[string]string) ContextOption
Override is a Run/RunContext/Context option to override expansion variables.
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" // 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" // 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" // ErrTypeMismatch is the type mismatch error. ErrTypeMismatch Error = "type mismatch" // ErrExit is the exit error. ErrExit Error = "exit" )
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 // NoArg when true, indicates that the flag does not require an argument. NoArg bool // 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. 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 // Split is a split separator, to split values for slices/arrays/maps. Split string // Special is the flag's special value. Special string }
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 spec - sets the flag's use spec default - sets the flag's default value 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 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
The `default:` option will be expanded by Context.Expand when the command's flags are populated.
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.
type FlagHelpOption ¶
type FlagHelpOption = Option
type FlagOption ¶
type FlagOption = Option
FlagOption are Option's that apply to a Flag.
func Bind ¶
func Bind[T *E, E any](v T) FlagOption
Bind is a Flag option to add a bound variable to a flag.
func BindRef ¶
func BindRef(value reflect.Value, set *bool) FlagOption
BindRef is a Flag option to add 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 add a bound variable to a flag.
func Default ¶
func Default(def any) FlagOption
Default is a Flag option to set the flag's default value.
Special strings can be used are 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 $APPCACHE - the current user's cache 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 on most Unix systems ox.Default("$CACHE") - expands to /home/$USER/.cache on most Unix systems ox.Default("$APPCACHE") - expands to /home/$USER/.cache/myApp if the root command's name is "myApp" on most Unix systems 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 for key a.b.c
See Context.Expand for more expansion details.
func Hook ¶
func Hook(f func(context.Context) error) FlagOption
Hook is a Flag option to set a hook for a flag.
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.
func MapKey ¶
func MapKey(mapKey Type) FlagOption
MapKey is a Flag option to set the flag's map key type.
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.
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.
func Split ¶
func Split(split string) FlagOption
Split is a Flag option to add a flag's split separator.
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) Date ¶
Date adds a time.Time variable to the flag set in the expected format of time.DateOnly.
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.
func (*FlagSet) Option ¶
func (fs *FlagSet) Option() option
Option returns a CommandOption for the flag set.
func (*FlagSet) Regexp ¶
Regexp adds a regexp.Regexp variable to the flag set.
func (*FlagSet) Timestamp ¶
Timestamp adds a time.Time variable to the flag set in the expected format of time.RFC3339.
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 HelpOption ¶
type HelpOption = Option
HelpOption are Option's that apply to Help.
func Footer ¶
func Footer(footer string) HelpOption
Footer is a Help option to set the command/flag's footer.
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 Rate ¶
Rate is 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 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 (Size) Format ¶
Format satisfies the fmt.Formatter interface. See AppendSize for recognized verbs.
func (Size) MarshalText ¶
MarshalText satisfies the BinaryMarshalUnmarshaler interface.
func (*Size) UnmarshalText ¶
UnmarshalText satisfies the BinaryMarshalUnmarshaler interface.
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" TimestampT Type = "timestamp" DateTimeT Type = "datetime" DateT Type = "date" TimeT Type = "time" DurationT Type = "duration" CountT Type = "count" PathT Type = "path" 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" ColorT Type = "color" GlobT Type = "glob" SliceT Type = "slice" ArrayT Type = "array" MapT Type = "map" HookT Type = "hook" )
Types.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Command gen parses and generates xo/ox style run entries for well-known, commmon commands `docker`, `doctl`, `gh`, `helm`, `hugo`, `kubectl`, `podman`, `psql`, `du`, `cp`, `tar`.
|
Command gen parses and generates xo/ox style run entries for well-known, commmon commands `docker`, `doctl`, `gh`, `helm`, `hugo`, `kubectl`, `podman`, `psql`, `du`, `cp`, `tar`. |
bind
_examples/bind/main.go
|
_examples/bind/main.go |
context
_examples/context/main.go
|
_examples/context/main.go |
gen/docker
Command docker is a xo/ox version of `+docker`.
|
Command docker is a xo/ox version of `+docker`. |
gen/doctl
Command doctl is a xo/ox version of `+doctl`.
|
Command doctl is a xo/ox version of `+doctl`. |
gen/gh
Command gh is a xo/ox version of `+gh`.
|
Command gh is a xo/ox version of `+gh`. |
gen/helm
Command helm is a xo/ox version of `+helm`.
|
Command helm is a xo/ox version of `+helm`. |
gen/hugo
Command hugo is a xo/ox version of `+hugo`.
|
Command hugo is a xo/ox version of `+hugo`. |
gen/kubectl
Command kubectl is a xo/ox version of `+kubectl`.
|
Command kubectl is a xo/ox version of `+kubectl`. |
gen/podman
Command podman is a xo/ox version of `+podman`.
|
Command podman is a xo/ox version of `+podman`. |
gen/psql
Command psql is a xo/ox version of `+psql`.
|
Command psql is a xo/ox version of `+psql`. |
reflect
_examples/reflect/main.go
|
_examples/reflect/main.go |
Package color provides a color type for ox.
|
Package color provides a color type for ox. |
Package glob provides a ox type for glob processing.
|
Package glob provides a ox type for glob processing. |
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. |
Package toml provides a toml config reader for ox.
|
Package toml provides a toml config reader for ox. |
Package uuid provides a ox type for uuid processing.
|
Package uuid provides a ox type for uuid processing. |
Package yaml provides a yaml config reader for ox.
|
Package yaml provides a yaml config reader for ox. |