Documentation ¶
Overview ¶
Package github.com/sttk/cliargs is a library to parse command line arguments.
Parse without configurations ¶
This library provides the function Parse which parses command line arguments without configurations. This function automatically divides command line arguments to options and command arguments.
Command line arguments starting with - or -- are options, and others are command arguments. If you want to specify a value to an option, follows "=" and the value after the option, like foo=123.
All command line arguments after -- are command arguments, even they starts with - or --.
// osArgs := []string{"path/to/app", "--foo-bar", "hoge", "--baz", "1", "-z=2", "-xyz=3", "fuga"} cmd, err := cliargs.Parse() cmd.Name // app cmd.Args() // [hoge fuga] cmd.HasOpt("foo-bar") // true cmd.HasOpt("baz") // true cmd.HasOpt("x") // true cmd.HasOpt("y") // true cmd.HasOpt("z") // true cmd.OptArg("foo-bar") // true cmd.OptArg("baz") // 1 cmd.OptArg("x") // true cmd.OptArg("y") // true cmd.OptArg("z") // 2 cmd.OptArgs("foo-bar") // [] cmd.OptArgs("baz") // [1] cmd.OptArgs("x") // [] cmd.OptArgs("y") // [] cmd.OptArgs("z") // [2 3]
Parse with configurations ¶
This library provides the function ParseWith which parses command line arguments with configurations. This function takes an array of option configurations: []OptCfg as the second argument, and divides command line arguments to options and command arguments with this configurations.
An option configuration has fields: StoreKey, Names, HasArg, IsArray, Defaults, Desc, and ArgInHelp.
StoreKey field is specified the key name to store the option value st the option map. If this field is not specified, the first element of Names field is set instead.
Names field is a string array and specified the option names, that are both long options and short options. The order of elements in this field is used in a help text. If you want to prioritize the output of short option name first in the help text, like `-f, --foo-bar`, but use the long option name as the key in the option map, write StoreKey and Names fields as follows: `OptCfg {StoreKey: "foo-bar", Names: []string{"f", "foo-bar"}}`.
HasArg field indicates the option requires one or more values. IsArray field indicates the option can have multiple values. Defaults field is an array of string which is used as default one or more values if the option is not specified. Desc field is a description of the option for help text. ArgInHelp field is a text which is output after option name and aliases as an option value in help text.
// osArgs := []string{"app", "--foo-bar", "hoge", "--baz", "1", "-z=2", "-x" "fuga"} optCfgs := []cliargs.OptCfg{ cliargs.OptCfg{ StoreKey: "FooBar", Names: []string{"foo-bar"}, Desc: "This is description of foo-bar.", }, cliargs.OptCfg{ Names: []string{"baz", "z"}, HasArg:true, IsArray: true, Defaults: [9,8,7], Desc:"This is description of baz.", ArgHelp:"<text>", }, cliargs.OptCfg{ Names: []string{"*"}, Desc: "(Any options are accepted)", }, } cmd, err := cliargs.ParseWith(optCfgs) cmd.Name // app cmd.Args() // [hoge fuga] cmd.HasOpt("FooBar") // true cmd.HasOpt("baz") // true cmd.HasOpt("x") // true, due to "*" config cmd.OptArg("FooBar") // true cmd.OptArg("baz") // 1 cmd.OptArg("x") // true cmd.OptArgs("FooBar") // [] cmd.OptArgs("baz") // [1 2] cmd.OptArgs("x") // []
This library provides Help struct which generates help text from a OptCfg array. The following help text is generated from the above optCfgs.
help := cliargs.NewHelp() help.AddText("This is the usage description.") help.AddOpts(optCfgs, 0, 2) help.Print() // (stdout) // This is the usage description. // --foo-bar, -f This is description of foo-bar. // --baz, -z <text> This is description of baz.
Parse for an option store with struct tags ¶
This library provides the function ParseFor which takes a pointer of a struct as the second argument, which will put option values by parsing command line arguments. This struct needs to struct tags for its fields. This function creates a Cmd instance and also an array of OptCfg which is transformed from these struct tags and is used to parse command line arguments.
The struct tags used in a option store struct are optcfg, optdesc, and optarg. optcfg is what to specify option configurations other than Desc and AtgInHelp. The format of optcfg is as follows:
`optcfg:"name"` // only name `optcfg:"name,alias1,alias2"` // with two aliases `optcfg:"name=value"` // with a default value `optcfg:"name=[value1,value2]` // with defalt values for array `optcfg:"name=:[value1:value2]` // with default values and separator is :
optdesc is what to specify a option description. And optarg is what to specify a text for an option argument value in help text.
// osArgs := []string{"app", "--foo-bar", "hoge", "--baz", "1", "-z=2", "-x", "fuga"} type Options struct { FooBar bool `optcfg:"foo-bar" optdesc:"This is description of foo-bar."` Baz []int `optcfg:"baz,z=[9,8,7]" optdesc:"This is description of baz." optarg:"<num>"` Qux bool `optcfg:"qux,x" optdesc:"This is description of qux"` } options := Options{} cmd, optCfgs, err := cliargs.ParseFor(osArgs, &options) cmd.Name // app cmd.Args() // [hoge fuga] cmd.HasOpt("FooBar") // true cmd.HasOpt("Baz") // true cmd.HasOpt("Qux") // true cmd.OptArg("FooBar") // true cmd.OptArg("Baz") // 1 cmd.OptArg("Qux") // true cmd.OptArgs("FooBar") // [] cmd.OptArgs("Baz") // [1 2] cmd.OptArgs("Qux") // [] options.FooBar // true options.Baz // [1 2] options.Qux // true optCfgs // []OptCfg{ // OptCfg{ // StoreKey: "FooBar", // Names: []string{"foo-bar"}, // Desc: "This is description of foo-bar.", // HasArg: false, // IsArray: false, // Defaults: []string(nil), // ArgInHelp: "", // }, // OptCfg{ // StoreKey: "Baz", // Aliases: []string{"baz", "z"}, // Desc: "This is description of baz.", // HasArg: true, // IsArray: true, // Defaults: []string{"9","8","7"}, // ArgInHelp: "<num>", // }, // OptCfg{ // StoreKey: "Qux", // Aliases: []string{"qux", "x"}, // Desc: "This is description of qux.", // HasArg: false, // IsArray: false, // Defaults: []string(nil), // ArgInHelp: "", // }, // }
The following help text is generated from the above optCfgs (without Help#Print but Help#Iter in this example).
help := cliargs.NewHelp() help.AddText("This is the usage description.") help.AddOpts(optCfgs, 12, 1) iter := help.Iter() for line, status := iter.Next() { fmt.Println(line) if status == cliargs.ITER_NO_MORE { break } } // (stdout) // This is the usage description. // --foo-bar This is description of foo-bar. // --baz, -z <num> // This is description of baz. // --qux This is description of qux.
Parse command line arguments including sub commands ¶
This library provides the function FindFirstArg which returns an index, an argument, an existent flag. This function can be used to parse command line arguments including sub commands, as follows:
i, arg, exists := cliargs.FindFirstArg(osArgs) if !exists { return } topCmd, topOptCfgs, err := cliargs.ParseFor(osArgs[0:i], &topOptions) if err != nil { return } switch arg { case "list": subCmd, subErr := cliargs.ParseWidth(osArgs[i:], &listOptCfgs) if subErr != nil { return } case "use": subCmd, ubErr := cliargs.ParseWidth(osArgs[i:], &useOptCfgs) if subErr != nil { return } ... }
And help text can be generated as follows:
help := cliargs.NewHelp() help.AddText("This is the usage of this command.") help.AddText("\nOPTIONS:") help.AddOpts(topOptCfgs, 12, 2) help.AddText("\nSUB COMMANDS:") help.AddText(fmt.Sprintf("%12s%s", "list", "The description of list sub-command.") help.AddOpts(listOptCfgs, 12, 2) help.AddText(fmt.Sprintf("%12s%s", "use", "The description of use sub-command.") help.AddOpts(useOptCfgs, 12, 2) ... help.Print() // (stdout) // This is the usage of this command. // // OPTIONS: // --foo The description of foo option. // ... // // SUB COMMANDS: // list The description of list sub-command. // --bar The description of bar option. // ... // // use The description of use sub-command. // --baz The description of baz option. // ...
Index ¶
- func FindFirstArg(osArgs []string) (index int, arg string, exists bool)
- func ParseFor(osArgs []string, options any) (Cmd, []OptCfg, error)
- type Cmd
- type ConfigHasDefaultsButHasNoArg
- type ConfigIsArrayButHasNoArg
- type FailToParseFloat
- type FailToParseInt
- type FailToParseUint
- type Help
- type HelpIter
- type IllegalOptionType
- type InvalidOption
- type OptCfg
- type OptionHasInvalidChar
- type OptionIsNotArray
- type OptionNameIsDuplicated
- type OptionNeedsArg
- type OptionStoreIsNotChangeable
- type OptionTakesNoArg
- type StoreKeyIsDuplicated
- type UnconfiguredOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FindFirstArg ¶
FindFirstArg is a function which returns an index, a name, a existent flag of first non option-format element in a specified string array. If non option-format element is found, a existent flag is true, but if the element is not found, the flag is false.
func ParseFor ¶
ParseFor is the function to parse command line arguments and set their values to the option store which is the second argument of this function. This function divides command line arguments to command arguments and options, then sets the options to the option store, and returns the command arguments with the generated option configurations.
The configurations of options are determined by types and struct tags of fields of the option store. If the type is bool, the option takes no argument. If the type is integer, floating point number or string, the option can takes single option argument, therefore it can appear once in command line arguments. If the type is an array, the option can takes multiple option arguments, therefore it can appear multiple times in command line arguments.
A struct tag can be specified an option names and default value(s). It has a special format like `opt:foo-bar,f=123`. This opt: is the struct tag key for the option configuration. The string following this key and rounded by double quotes is the content of the option configuration. The first part of the option configuration is an option names, which are separated by commas, and ends with "=" mark or end of string. If the option name is empty or no struct tag, the option's name becomes same with the field name of the option store.
The string after the "=" mark is default value(s). If the type of the option is a boolean, the string after "=" mark is ignored because a boolean option takes no option argument. If the type of the option is a number or a string, the whole string after "=" mark is a default value. If the type of the option is an array, the string after "=" mark have to be rounded by square brackets and separate the elements with commas, like [elem1,elem2,elem3]. The element separator can be used other than a comma by putting the separator before the open square bracket, like :[elem1:elem2:elem3]. It's useful when some array elements include commas.
NOTE: A default value of an empty string array option in a struct tag is [], like `opt:"name=[]"`, it doesn't represent an array which contains only one empty string but an empty array. If you want to specify an array which contains only one empty string, write nothing after "=" mark, like `opt:"name="`.
Example ¶
package main import ( "fmt" "github.com/sttk/cliargs" ) func main() { type MyOptions struct { FooBar bool `optcfg:"foo-bar,f" optdesc:"FooBar description."` Baz int `optcfg:"baz,b=99" optdesc:"Baz description." optarg:"<num>"` Qux []string `optcfg:"qux,q=[A,B,C]" optdesc:"Qux description." optarg:"<text>"` } options := MyOptions{} osArgs := []string{ "path/to/app", "--foo-bar", "c1", "-b", "12", "--qux", "D", "c2", "-q", "E", } cmd, optCfgs, err := cliargs.ParseFor(osArgs, &options) fmt.Printf("err = %v\n", err) fmt.Printf("cmd.Name = %v\n", cmd.Name) fmt.Printf("cmd.Args() = %v\n", cmd.Args()) fmt.Printf("optCfgs[0].StoreKey = %v\n", optCfgs[0].StoreKey) fmt.Printf("optCfgs[0].Names = %v\n", optCfgs[0].Names) fmt.Printf("optCfgs[0].HasArg = %v\n", optCfgs[0].HasArg) fmt.Printf("optCfgs[0].IsArray = %v\n", optCfgs[0].IsArray) fmt.Printf("optCfgs[0].Defaults = %v\n", optCfgs[0].Defaults) fmt.Printf("optCfgs[0].Desc = %v\n", optCfgs[0].Desc) fmt.Printf("optCfgs[1].StoreKey = %v\n", optCfgs[1].StoreKey) fmt.Printf("optCfgs[1].Names = %v\n", optCfgs[1].Names) fmt.Printf("optCfgs[1].HasArg = %v\n", optCfgs[1].HasArg) fmt.Printf("optCfgs[1].IsArray = %v\n", optCfgs[1].IsArray) fmt.Printf("optCfgs[1].Defaults = %v\n", optCfgs[1].Defaults) fmt.Printf("optCfgs[1].Desc = %v\n", optCfgs[1].Desc) fmt.Printf("optCfgs[1].ArgInHelp = %v\n", optCfgs[1].ArgInHelp) fmt.Printf("optCfgs[2].StoreKey = %v\n", optCfgs[2].StoreKey) fmt.Printf("optCfgs[2].Names = %v\n", optCfgs[2].Names) fmt.Printf("optCfgs[2].HasArg = %v\n", optCfgs[2].HasArg) fmt.Printf("optCfgs[2].IsArray = %v\n", optCfgs[2].IsArray) fmt.Printf("optCfgs[2].Defaults = %v\n", optCfgs[2].Defaults) fmt.Printf("optCfgs[2].Desc = %v\n", optCfgs[2].Desc) fmt.Printf("optCfgs[2].ArgInHelp = %v\n", optCfgs[2].ArgInHelp) fmt.Printf("options.FooBar = %v\n", options.FooBar) fmt.Printf("options.Baz = %v\n", options.Baz) fmt.Printf("options.Qux = %v\n", options.Qux) }
Output: err = <nil> cmd.Name = app cmd.Args() = [c1 c2] optCfgs[0].StoreKey = FooBar optCfgs[0].Names = [foo-bar f] optCfgs[0].HasArg = false optCfgs[0].IsArray = false optCfgs[0].Defaults = [] optCfgs[0].Desc = FooBar description. optCfgs[1].StoreKey = Baz optCfgs[1].Names = [baz b] optCfgs[1].HasArg = true optCfgs[1].IsArray = false optCfgs[1].Defaults = [99] optCfgs[1].Desc = Baz description. optCfgs[1].ArgInHelp = <num> optCfgs[2].StoreKey = Qux optCfgs[2].Names = [qux q] optCfgs[2].HasArg = true optCfgs[2].IsArray = true optCfgs[2].Defaults = [A B C] optCfgs[2].Desc = Qux description. optCfgs[2].ArgInHelp = <text> options.FooBar = true options.Baz = 12 options.Qux = [D E]
Types ¶
type Cmd ¶
type Cmd struct { Name string // contains filtered or unexported fields }
Cmd is the structure which contains a command name, command arguments, and option arguments that are parsed from command line arguments without configurations. And this provides methods to check if they are specified and to obtain them.
func Parse ¶
Parse is the function to parse command line arguments without configurations. This function divides command line arguments to command arguments, which are not associated with any options, and options, of which each has a name and option arguments. If an option appears multiple times in command line arguments, the option has multiple option arguments. Options are divided to long format options and short format options.
A long format option starts with "--" and follows multiple characters which consists of alphabets, numbers, and '-'. (A character immediately after the heading "--" allows only an alphabet.) A long format option can be followed by "=" and its option argument.
A short format option starts with "-" and follows single character which is an alphabet. Multiple short options can be combined into one argument. (For example -a -b -c can be combined into -abc.) Moreover, a short option can be followed by "=" and its option argument. In case of combined short options, only the last short option can take an option argument. (For example, -abc=3 is equal to -a -b -c=3.)
Example ¶
os.Args = []string{ "cmd", "--foo-bar=A", "-a", "--baz", "-bc=3", "qux", "-c=4", "quux", } cmd, err := cliargs.Parse() fmt.Printf("err = %v\n", err) fmt.Printf("cmd.HasOpt(\"a\") = %v\n", cmd.HasOpt("a")) fmt.Printf("cmd.HasOpt(\"b\") = %v\n", cmd.HasOpt("b")) fmt.Printf("cmd.HasOpt(\"c\") = %v\n", cmd.HasOpt("c")) fmt.Printf("cmd.HasOpt(\"foo-bar\") = %v\n", cmd.HasOpt("foo-bar")) fmt.Printf("cmd.HasOpt(\"baz\") = %v\n", cmd.HasOpt("baz")) fmt.Printf("cmd.OptArg(\"c\") = %v\n", cmd.OptArg("c")) fmt.Printf("cmd.OptArg(\"foo-bar\") = %v\n", cmd.OptArg("foo-bar")) fmt.Printf("cmd.OptArgs(\"c\") = %v\n", cmd.OptArgs("c")) fmt.Printf("cmd.OptArgs(\"foo-bar\") = %v\n", cmd.OptArgs("foo-bar")) fmt.Printf("cmd.Args() = %v\n", cmd.Args())
Output: err = <nil> cmd.HasOpt("a") = true cmd.HasOpt("b") = true cmd.HasOpt("c") = true cmd.HasOpt("foo-bar") = true cmd.HasOpt("baz") = true cmd.OptArg("c") = 3 cmd.OptArg("foo-bar") = A cmd.OptArgs("c") = [3 4] cmd.OptArgs("foo-bar") = [A] cmd.Args() = [qux quux]
func ParseWith ¶
ParseWith is the function which parses command line arguments with option configurations. This function divides command line arguments to command arguments and options. And an option consists of a name and an option argument. Options are divided to long format options and short format options. About long/short format options, since they are same with Parse function, see the comment of that function.
This function allows only options declared in option configurations. An option configuration has fields: StoreKey, Names, HasArg, IsArray, Defaults, Desc and ArgInHelp. When an option matches one of the Names in an option configuration, the option is registered into Cmd with StoreKey. If both HasArg and IsArray are true, the option can have one or multiple option argumentsr, and if HasArg is true and IsArray is false, the option can have only one option argument, otherwise the option cannot have option arguments. If Defaults field is specified and no option value is given in command line arguments, the value of Defaults is set as the option arguments.
If options not declared in option configurationsi are given in command line arguments, this function basically returns UnconfiguradOption error. However, if you want to allow other options, add an option configuration of which StoreKey or the first element of Names is "*".
Example ¶
package main import ( "fmt" "github.com/sttk/cliargs" ) func main() { osArgs := []string{ "path/to/app", "--foo-bar", "qux", "--baz", "1", "-z=2", "-X", "quux", } optCfgs := []cliargs.OptCfg{ cliargs.OptCfg{ Names: []string{"foo-bar"}, }, cliargs.OptCfg{ StoreKey: "Bazoo", Names: []string{"baz", "z"}, HasArg: true, IsArray: true, }, cliargs.OptCfg{ Names: []string{"corge"}, HasArg: true, Defaults: []string{"99"}, }, cliargs.OptCfg{ StoreKey: "*", }, } cmd, err := cliargs.ParseWith(osArgs, optCfgs) fmt.Printf("err = %v\n", err) fmt.Printf("cmd.Name = %v\n", cmd.Name) fmt.Printf("cmd.HasOpt(\"foo-bar\") = %v\n", cmd.HasOpt("foo-bar")) fmt.Printf("cmd.HasOpt(\"Bazoo\") = %v\n", cmd.HasOpt("Bazoo")) fmt.Printf("cmd.HasOpt(\"X\") = %v\n", cmd.HasOpt("X")) fmt.Printf("cmd.HasOpt(\"corge\") = %v\n", cmd.HasOpt("corge")) fmt.Printf("cmd.OptArg(\"Bazoo\") = %v\n", cmd.OptArg("Bazoo")) fmt.Printf("cmd.OptArg(\"corge\") = %v\n", cmd.OptArg("corge")) fmt.Printf("cmd.OptArgs(\"Bazoo\") = %v\n", cmd.OptArgs("Bazoo")) fmt.Printf("cmd.OptArgs(\"corge\") = %v\n", cmd.OptArgs("corge")) fmt.Printf("cmd.Args() = %v\n", cmd.Args()) }
Output: err = <nil> cmd.Name = app cmd.HasOpt("foo-bar") = true cmd.HasOpt("Bazoo") = true cmd.HasOpt("X") = true cmd.HasOpt("corge") = true cmd.OptArg("Bazoo") = 1 cmd.OptArg("corge") = 99 cmd.OptArgs("Bazoo") = [1 2] cmd.OptArgs("corge") = [99] cmd.Args() = [qux quux]
func (Cmd) Args ¶
Args is the method to get command arguments which are specified in command line arguments and are not associated with any options.
func (Cmd) HasOpt ¶
HasOpt is the method which checks if the option is specified in command line arguments.
type ConfigHasDefaultsButHasNoArg ¶ added in v0.7.0
type ConfigHasDefaultsButHasNoArg struct{ StoreKey string }
ConfigHasDefaultsButHasNoArg is the error which indicates that an option configuration contradicts that the option has default value (.Defaults != nil) but must have no option argument (.HasArg = false).
func (ConfigHasDefaultsButHasNoArg) Error ¶ added in v0.7.0
func (e ConfigHasDefaultsButHasNoArg) Error() string
Error is the method to retrieve the message of this error.
func (ConfigHasDefaultsButHasNoArg) GetOpt ¶ added in v0.7.0
func (e ConfigHasDefaultsButHasNoArg) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type ConfigIsArrayButHasNoArg ¶
type ConfigIsArrayButHasNoArg struct{ StoreKey string }
ConfigIsArrayButHasNoArg is the error which indicates that an option configuration contradicts that the option must be an array (.IsArray = true) but must have no option argument (.HasArg = false).
func (ConfigIsArrayButHasNoArg) Error ¶
func (e ConfigIsArrayButHasNoArg) Error() string
Error is the method to retrieve the message of this error.
func (ConfigIsArrayButHasNoArg) GetOpt ¶ added in v0.6.0
func (e ConfigIsArrayButHasNoArg) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type FailToParseFloat ¶
type FailToParseFloat struct { Option string Field string Input string BitSize int // contains filtered or unexported fields }
FailToParseFloat is the error which indicates that an option argument in command line arguments should be a floating point number but is invalid.
func (FailToParseFloat) Error ¶
func (e FailToParseFloat) Error() string
Error is the method to retrieve the message of this error.
func (FailToParseFloat) Unwrap ¶
func (e FailToParseFloat) Unwrap() error
Unwrap is the method to retrieve an error that caused this error.
type FailToParseInt ¶
type FailToParseInt struct { Option string Field string Input string BitSize int // contains filtered or unexported fields }
FailToParseInt is the error reaason which indicates that an option argument in command line arguments should be an integer but is invalid.
func (FailToParseInt) Error ¶
func (e FailToParseInt) Error() string
Error is the method to retrieve the message of this error.
func (FailToParseInt) Unwrap ¶
func (e FailToParseInt) Unwrap() error
Unwrap is the method to retrieve an error that caused this error.
type FailToParseUint ¶
type FailToParseUint struct { Option string Field string Input string BitSize int // contains filtered or unexported fields }
FailToParseUint is the error which indicates that an option argument in command line arguments should be an unsigned integer but is invalid.
func (FailToParseUint) Error ¶
func (e FailToParseUint) Error() string
Error is the method to retrieve the message of this error.
func (FailToParseUint) Unwrap ¶
func (e FailToParseUint) Unwrap() error
Unwrap is the method to retrieve an error that caused this error.
type Help ¶
type Help struct {
// contains filtered or unexported fields
}
Help is a struct type which holds help text blocks and help options block.
func NewHelp ¶
NewHelp is a function to create a Help instance. This function can optionally take left margin and right margin as variadic arguments.
func (*Help) AddOpts ¶
AddOpts is a method which adds OptCfg(s) to this Help instance. And this method can optionally set indent, left margin, and right margin as variadic arguments, too.
func (*Help) AddText ¶
AddText is a method which adds a text to this Help instance. And this method can optionally set indent, left margin, and right margin as variadic arguments, too.
func (*Help) AddTexts ¶
AddTexts is a method which adds an array of texts to this Help instance. And this method can optionally set indent, left margin, and right margin as variadic arguments, too.
func (Help) Iter ¶
Iter is a method which creates a HelpIter instance.
Example ¶
package main import ( "fmt" "github.com/sttk/cliargs" ) func main() { type MyOptions struct { FooBar bool `optcfg:"foo-bar,f" optdesc:"FooBar is a flag.\nThis flag is foo bar."` Baz int `optcfg:"baz,b=99" optdesc:"Baz is a integer." optarg:"<num>"` Qux string `optcfg:"=XXX" optdesc:"Qux is a string." optarg:"<text>"` Quux []string `optcfg:"quux=[A,B,C]" optdesc:"Quux is a string array."` } options := MyOptions{} optCfgs, _ := cliargs.MakeOptCfgsFor(&options) help := cliargs.NewHelp(5, 2) help.AddText("This is the usage section.") help.AddOpts(optCfgs, 10, 1) iter := help.Iter() for { line, more := iter.Next() fmt.Println(line) if !more { break } } }
Output: This is the usage section. --foo-bar, -f FooBar is a flag. This flag is foo bar. --baz, -b <num> Baz is a integer. --Qux <text> Qux is a string. --quux Quux is a string array.
func (Help) Print ¶
func (help Help) Print()
Print is a method which prints help texts to standard output.
Example ¶
package main import ( "github.com/sttk/cliargs" ) func main() { type MyOptions struct { FooBar bool `optcfg:"foo-bar,f" optdesc:"FooBar is a flag.\nThis flag is foo bar."` Baz int `optcfg:"baz,b=99" optdesc:"Baz is a integer." optarg:"<num>"` Qux string `optcfg:"=XXX" optdesc:"Qux is a string." optarg:"<text>"` Quux []string `optcfg:"quux=[A,B,C]" optdesc:"Quux is a string array."` } options := MyOptions{} optCfgs, _ := cliargs.MakeOptCfgsFor(&options) help := cliargs.NewHelp(5, 2) help.AddText("This is the usage section.") help.AddOpts(optCfgs, 10, 1) help.Print() }
Output: This is the usage section. --foo-bar, -f FooBar is a flag. This flag is foo bar. --baz, -b <num> Baz is a integer. --Qux <text> Qux is a string. --quux Quux is a string array.
type HelpIter ¶
type HelpIter struct {
// contains filtered or unexported fields
}
HelpIter is a struct type to iterate lines of help texts.
type IllegalOptionType ¶
IllegalOptionType is the error which indicates that a type of a field of the option store is neither a boolean, a number, a string, nor an array of numbers or strings.
func (IllegalOptionType) Error ¶
func (e IllegalOptionType) Error() string
Error is the method to retrieve the message of this error.
type InvalidOption ¶ added in v0.6.0
InvalidOption is the error interface which provides method declarations to retrieve an option that caused this error and an error message.
Example ¶
package main import ( "fmt" "os" "github.com/sttk/cliargs" ) func main() { optCfgs := []cliargs.OptCfg{ cliargs.OptCfg{ Names: []string{"foo"}, Defaults: []string{"123"}, HasArg: false, }, } _, e := cliargs.ParseWith(os.Args, optCfgs) ee := e.(cliargs.InvalidOption) fmt.Printf("error type: %T\n", ee) fmt.Printf("option: %s\n", ee.GetOpt()) }
Output: error type: cliargs.ConfigHasDefaultsButHasNoArg option: foo
type OptCfg ¶
type OptCfg struct { StoreKey string Names []string HasArg bool IsArray bool Defaults []string OnParsed *func([]string) error Desc string ArgInHelp string }
OptCfg is the struct that represents an option configuration. An option configuration consists of fields: StoreKey, Names, HasArg, IsArray, Defaults, Desc, and ArgInHelp.
The StoreKey field is the key to store a option value(s) in the option map. If this key is not specified or empty, the first element of Names field is used instead.
The Names field is the array for specifing the option name and the aliases. The order of the names in this array are used in a help text.
HasArg and IsArray are flags which allow the option to take option arguments. If both HasArg and IsArray are true, the option can take one or multiple option arguments. If HasArg is true and IsArray is false, the option can take only one option arguments. If both HasArg and IsArray are false, the option can take no option argument.
Defaults is the field to specified the default value for when the option is not given in command line arguments.
OnParsed is the field for a function which is called when the option has been parsed.
Desc is the field to set the description of the option.
ArgInHelp is a display of the argument of this option in a help text. The example of the display is like: -o, --option <value>.
func MakeOptCfgsFor ¶
MakeOptCfgsFor is a function to make a OptCfg array from fields of the option store which is the argument of this function.
Example ¶
package main import ( "fmt" "github.com/sttk/cliargs" ) func main() { type MyOptions struct { FooBar bool `optcfg:"foo-bar,f" optdesc:"FooBar description"` Baz int `optcfg:"baz,b=99" optdesc:"Baz description" optarg:"<number>"` Qux string `optcfg:"=XXX" optdesc:"Qux description" optarg:"<string>"` Quux []string `optcfg:"quux=[A,B,C]" optdesc:"Quux description" optarg:"<array elem>"` Corge []int } options := MyOptions{} optCfgs, err := cliargs.MakeOptCfgsFor(&options) fmt.Printf("err = %v\n", err) fmt.Printf("len(optCfgs) = %v\n", len(optCfgs)) fmt.Println() fmt.Printf("optCfgs[0].StoreKey = %v\n", optCfgs[0].StoreKey) fmt.Printf("optCfgs[0].Names = %v\n", optCfgs[0].Names) fmt.Printf("optCfgs[0].HasArg = %v\n", optCfgs[0].HasArg) fmt.Printf("optCfgs[0].IsArray = %v\n", optCfgs[0].IsArray) fmt.Printf("optCfgs[0].Defaults = %v\n", optCfgs[0].Defaults) fmt.Printf("optCfgs[0].Desc = %v\n", optCfgs[0].Desc) fmt.Println() fmt.Printf("optCfgs[1].StoreKey = %v\n", optCfgs[1].StoreKey) fmt.Printf("optCfgs[1].Names = %v\n", optCfgs[1].Names) fmt.Printf("optCfgs[1].HasArg = %v\n", optCfgs[1].HasArg) fmt.Printf("optCfgs[1].IsArray = %v\n", optCfgs[1].IsArray) fmt.Printf("optCfgs[1].Defaults = %v\n", optCfgs[1].Defaults) fmt.Printf("optCfgs[1].Desc = %v\n", optCfgs[1].Desc) fmt.Printf("optCfgs[1].ArgInHelp = %v\n", optCfgs[1].ArgInHelp) fmt.Println() fmt.Printf("optCfgs[2].StoreKey = %v\n", optCfgs[2].StoreKey) fmt.Printf("optCfgs[2].Names = %v\n", optCfgs[2].Names) fmt.Printf("optCfgs[2].HasArg = %v\n", optCfgs[2].HasArg) fmt.Printf("optCfgs[2].IsArray = %v\n", optCfgs[2].IsArray) fmt.Printf("optCfgs[2].Defaults = %v\n", optCfgs[2].Defaults) fmt.Printf("optCfgs[2].Desc = %v\n", optCfgs[2].Desc) fmt.Printf("optCfgs[2].ArgInHelp = %v\n", optCfgs[2].ArgInHelp) fmt.Println() fmt.Printf("optCfgs[3].StoreKey = %v\n", optCfgs[3].StoreKey) fmt.Printf("optCfgs[3].Names = %v\n", optCfgs[3].Names) fmt.Printf("optCfgs[3].HasArg = %v\n", optCfgs[3].HasArg) fmt.Printf("optCfgs[3].IsArray = %v\n", optCfgs[3].IsArray) fmt.Printf("optCfgs[3].Defaults = %v\n", optCfgs[3].Defaults) fmt.Printf("optCfgs[3].Desc = %v\n", optCfgs[3].Desc) fmt.Printf("optCfgs[3].ArgInHelp = %v\n", optCfgs[3].ArgInHelp) fmt.Println() fmt.Printf("optCfgs[4].StoreKey = %v\n", optCfgs[4].StoreKey) fmt.Printf("optCfgs[4].Names = %v\n", optCfgs[4].Names) fmt.Printf("optCfgs[4].HasArg = %v\n", optCfgs[4].HasArg) fmt.Printf("optCfgs[4].IsArray = %v\n", optCfgs[4].IsArray) fmt.Printf("optCfgs[4].Defaults = %v\n", optCfgs[4].Defaults) fmt.Printf("optCfgs[4].Desc = %v\n", optCfgs[4].Desc) }
Output: err = <nil> len(optCfgs) = 5 optCfgs[0].StoreKey = FooBar optCfgs[0].Names = [foo-bar f] optCfgs[0].HasArg = false optCfgs[0].IsArray = false optCfgs[0].Defaults = [] optCfgs[0].Desc = FooBar description optCfgs[1].StoreKey = Baz optCfgs[1].Names = [baz b] optCfgs[1].HasArg = true optCfgs[1].IsArray = false optCfgs[1].Defaults = [99] optCfgs[1].Desc = Baz description optCfgs[1].ArgInHelp = <number> optCfgs[2].StoreKey = Qux optCfgs[2].Names = [Qux] optCfgs[2].HasArg = true optCfgs[2].IsArray = false optCfgs[2].Defaults = [XXX] optCfgs[2].Desc = Qux description optCfgs[2].ArgInHelp = <string> optCfgs[3].StoreKey = Quux optCfgs[3].Names = [quux] optCfgs[3].HasArg = true optCfgs[3].IsArray = true optCfgs[3].Defaults = [A B C] optCfgs[3].Desc = Quux description optCfgs[3].ArgInHelp = <array elem> optCfgs[4].StoreKey = Corge optCfgs[4].Names = [Corge] optCfgs[4].HasArg = true optCfgs[4].IsArray = true optCfgs[4].Defaults = [] optCfgs[4].Desc =
type OptionHasInvalidChar ¶
type OptionHasInvalidChar struct{ Option string }
OptionHasInvalidChar is the error which indicates that an invalid character is found in the option.
func (OptionHasInvalidChar) Error ¶
func (e OptionHasInvalidChar) Error() string
Error is the method to retrieve the message of this error.
func (OptionHasInvalidChar) GetOpt ¶ added in v0.6.0
func (e OptionHasInvalidChar) GetOpt() string
GetOpt is the method to retrieve the option that caused this error.
type OptionIsNotArray ¶
type OptionIsNotArray struct{ Name, StoreKey string }
OptionIsNotArray is the error which indicates that an option is input with an option argument multiple times though its option configuration specifies the option is not an array (.IsArray = false).
func (OptionIsNotArray) Error ¶
func (e OptionIsNotArray) Error() string
Error is the method to retrieve the message of this error.
func (OptionIsNotArray) GetOpt ¶ added in v0.6.0
func (e OptionIsNotArray) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type OptionNameIsDuplicated ¶ added in v0.7.0
type OptionNameIsDuplicated struct{ Name, StoreKey string }
OptionNameIsDuplicated is the error which indicates that an option name in Names field is duplicated another among all option configurations.
func (OptionNameIsDuplicated) Error ¶ added in v0.7.0
func (e OptionNameIsDuplicated) Error() string
Error is the method to retrieve the message of this error.
func (OptionNameIsDuplicated) GetOpt ¶ added in v0.7.0
func (e OptionNameIsDuplicated) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type OptionNeedsArg ¶
type OptionNeedsArg struct{ Name, StoreKey string }
OptionNeedsArg is the error which indicates that an option is input with no option argument though its option configuration requires option argument (.HasArg = true).
func (OptionNeedsArg) Error ¶
func (e OptionNeedsArg) Error() string
Error is the method to retrieve the message of this error.
func (OptionNeedsArg) GetOpt ¶ added in v0.6.0
func (e OptionNeedsArg) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type OptionStoreIsNotChangeable ¶
type OptionStoreIsNotChangeable struct{}
OptionStoreIsNotChangeable is the error which indicates that the second argument of ParseFor function, which is set options produced by parsing command line arguments, is not a pointer.
func (OptionStoreIsNotChangeable) Error ¶
func (e OptionStoreIsNotChangeable) Error() string
Error is the method to retrieve the message of this error.
type OptionTakesNoArg ¶
type OptionTakesNoArg struct{ Name, StoreKey string }
OptionTakesNoArg is the error which indicates that an option is input with an option argument though its option configuration does not accept option arguments (.HasArg = false).
func (OptionTakesNoArg) Error ¶
func (e OptionTakesNoArg) Error() string
Error is the method to retrieve the message of this error.
func (OptionTakesNoArg) GetOpt ¶ added in v0.6.0
func (e OptionTakesNoArg) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type StoreKeyIsDuplicated ¶ added in v0.7.0
type StoreKeyIsDuplicated struct{ StoreKey string }
StoreKeyIsDuplicated is the error which indicates that a store key in an option configuration is duplicated another among all option configurations.
func (StoreKeyIsDuplicated) Error ¶ added in v0.7.0
func (e StoreKeyIsDuplicated) Error() string
Error is the method to retrieve the message of this error.
func (StoreKeyIsDuplicated) GetOpt ¶ added in v0.7.0
func (e StoreKeyIsDuplicated) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.
type UnconfiguredOption ¶
type UnconfiguredOption struct{ Name string }
UnconfiguredOption is the error which indicates that there is no configuration about the input option.
func (UnconfiguredOption) Error ¶
func (e UnconfiguredOption) Error() string
Error is the method to retrieve the message of this error.
func (UnconfiguredOption) GetOpt ¶ added in v0.6.0
func (e UnconfiguredOption) GetOpt() string
GetOpt is the method to retrieve the store key that caused this error.