cliargs

package module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2024 License: MIT Imports: 9 Imported by: 4

README

cliargs Go Reference CI Status MIT License

A library to parse command line arguments for Golang application.

This library provides the following functionalities:

  • Supports POSIX & GNU like short and long options.
    • This library supports -- option.
    • This library doesn't support numeric short option.
    • This library supports not -ofoo but -o=foo as an alternative to -o foo for short option.
  • Supports parsing with option configurations.
  • Supports parsing with a struct which stores option values and has struct tags of fields.
  • Is able to parse command line arguments including sub commands.
  • Generates help text from option configurations.

Import this package

import "github.com/sttk/cliargs"

Usage

The usage of this library is described on the overview in the go package document.

See https://pkg.go.dev/github.com/sttk/cliargs#pkg-overview

Supporting Go versions

This library supports Go 1.18 or later.

Actual test results for each Go version:
% gvm-fav
Now using version go1.18.10
go version go1.18.10 darwin/amd64
ok  	github.com/sttk/cliargs	0.907s	coverage: 97.6% of statements
ok  	github.com/sttk/cliargs/errors	1.052s	coverage: 100.0% of statements
ok  	github.com/sttk/cliargs/validators	0.553s	coverage: 100.0% of statements

Now using version go1.19.13
go version go1.19.13 darwin/amd64
ok  	github.com/sttk/cliargs	0.915s	coverage: 97.6% of statements
ok  	github.com/sttk/cliargs/errors	1.085s	coverage: 100.0% of statements
ok  	github.com/sttk/cliargs/validators	0.569s	coverage: 100.0% of statements

Now using version go1.20.14
go version go1.20.14 darwin/amd64
ok  	github.com/sttk/cliargs	0.559s	coverage: 97.6% of statements
ok  	github.com/sttk/cliargs/errors	1.065s	coverage: 100.0% of statements
ok  	github.com/sttk/cliargs/validators	1.590s	coverage: 100.0% of statements

Now using version go1.21.13
go version go1.21.13 darwin/amd64
ok  	github.com/sttk/cliargs	1.613s	coverage: 97.6% of statements
ok  	github.com/sttk/cliargs/errors	0.537s	coverage: 100.0% of statements
ok  	github.com/sttk/cliargs/validators	1.061s	coverage: 100.0% of statements

Now using version go1.22.6
go version go1.22.6 darwin/amd64
ok  	github.com/sttk/cliargs	0.607s	coverage: 97.6% of statements
ok  	github.com/sttk/cliargs/errors	1.712s	coverage: 100.0% of statements
ok  	github.com/sttk/cliargs/validators	1.160s	coverage: 100.0% of statements

Now using version go1.23.0
go version go1.23.0 darwin/amd64
ok  	github.com/sttk/cliargs	1.743s	coverage: 97.6% of statements
ok  	github.com/sttk/cliargs/errors	0.599s	coverage: 100.0% of statements
ok  	github.com/sttk/cliargs/validators	1.160s	coverage: 100.0% of statements

Back to go1.22.6
Now using version go1.22.6

License

Copyright (C) 2023-2024 Takayuki Sato

This program is free software under MIT License.
See the file LICENSE in this distribution for more details.

Documentation

Overview

Package github.com/sttk/cliargs is a library to parse command line arguments.

Parse without configurations

The Cmd struct has the method which parses command line arguments without configurations. This method automatically divides command line arguments to options and command arguments.

Command line arguments starts 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 `--`.

// os.Args = []string{"path/to/app", "--foo-bar", "hoge", "--baz", "1", "-z=2", "-xyz=3", "fuga"}
cmd := cliargs.NewCmd()
err := cmd.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")   //
cmd.OptArg("baz")       // 1
cmd.OptArg("x")         //
cmd.OptArg("y")         //
cmd.OptArg("z")         // 2
cmd.OptArgs("foo-bar")  // []
cmd.OptArgs("baz")      // [1]
cmd.OptArgs("x")        // []
cmd.OptArgs("y")        // []
cmd.OptArgs("z")        // [2 3]

Parses with configurations

The Cmd struct has the method ParseWith which parses command line arguments with configurations.

This method takes an array of option configurations: OptCfg, and divides command line arguments to options and command arguments according to this configurations.

An option configuration has fields: StoreKey, Names, HasArg, IsArray, Defaults, Desc, ArgInHelp, and Validator.

StoreKey field is specified the key name to store the option value to the option map in the Cmd instance. If this field is not specified, the first element of Names field is used 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 option arguments if the option is not specified. Desc 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.

Validator field is to set a function pointer which validates an option argument. This module provides several validators that validate whether an option argument is in a valid numeric format.

In addition,the help printing for an array of OptCfg is generated with Help.

// os.Args = []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 := cliars.NewCmd()
err := cmd.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")        // []

help := cliargs.NewHelp()
help.AddText("This is the usage description.")
help.AddOptsWithMargins(optCfgs, 2, 0)
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 a OptStore struct

The Cmd struct has the method ParseFor which parses command line arguments and set their option values to the option store which is passed as an argument.

This method divides command line arguments to command arguments and options, then sets each option value to a curresponding field of the option store.

Within this method, a array of OptCfg is made from the fields of the option store. This OptCfg array is set to the public field: OptCfgs of the Cmd instance. If you want to access this option configurations, get them from this field.

An option configuration corresponding to each field of an option store is determined by its type and its struct tags. 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.

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.

NOTE: A default value of empty string array option in the struct tag is `[]`, like: `optcfg:"name=[]"`, but it doesn't represent an array which contains only one empty string. If you want to specify an array which contains only one emtpy string, write nothing after `=` symbol, like `optcfg:"name="`.

// os.Args = []string{"app", "--foo-bar", "hoge", "--baz", "1", "-z=2", "-x", "fuga"}

type MyOptions 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 := MyOptions{}

cmd := cliargs.NewCmd()
err := cliargs.ParseFor(&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: "",
           //   },
           // }

help := cliargs.NewHelp()
help.AddText("This is the usage description.")
help.AddOptsWithIndentAndMargins(optCfgs, 12, 1, 0)
iter := help.Iter()
for {
    line, exists := iter.Next() {
    if !exists { break }
    fmt.Println(line)
}

// (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 command

This module provides methods Cmd#parseUntilSubCmd, Cmd#parseUntilSubCmdWith, and Cmd#parseUntilSubCmdFor for parsing command line arguments including sub commands.

These methods correspond to Cmd#parse, Cmd#parseWith, and Cmd#parseFor, respectively, and behave the same except that they stop parsing before the first command argument (= sub command) and return a Cmd instance containing the arguments starting from the the sub command.

The folowing is an example code using Cmd#parse_until_sub_cmd:

// os.Args = []string{"path/to/app", "--foo-bar", "hoge", "--baz", "1", "-z=2", "-xyz=3", "fuga"}
cmd := cliargs.NewCmd()
subCmd, err := cmd.ParseUntilSubCmd()
errSub := subCmd.Parse()

cmd.Name                // app
cmd.Args                // []
cmd.HasOpt("foo-bar")   // true
cmd.HasOpt("baz")       // false
cmd.HasOpt("x")         // false
cmd.HasOpt("y")         // false
cmd.HasOpt("z")         // false
cmd.OptArg("foo-bar")   //
cmd.OptArg("baz")       //
cmd.OptArg("x")         //
cmd.OptArg("y")         //
cmd.OptArg("z")         //
cmd.OptArgs("foo-bar")  // []
cmd.OptArgs("baz")      // []
cmd.OptArgs("x")        // []
cmd.OptArgs("y")        // []
cmd.OptArgs("z")        // []

subCmd.Name                // hoge
subCmd.Args                // [fuga]
subCmd.HasOpt("foo-bar")   // false
subCmd.HasOpt("baz")       // true
subCmd.HasOpt("x")         // true
subCmd.HasOpt("y")         // true
subCmd.HasOpt("z")         // true
subCmd.OptArg("foo-bar")   //
subCmd.OptArg("baz")       // 1
subCmd.OptArg("x")         //
subCmd.OptArg("y")         //
subCmd.OptArg("z")         // 2
subCmd.OptArgs("foo-bar")  // []
subCmd.OptArgs("baz")      // [1]
subCmd.OptArgs("x")        // []
subCmd.OptArgs("y")        // []
subCmd.OptArgs("z")        // [2 3]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cmd

type Cmd struct {
	Name    string
	Args    []string
	OptCfgs []OptCfg
	// contains filtered or unexported fields
}

Cmd is the structure that parses command line arguments and stores them. The results of parsing are stored by separating into command name, command arguments, options, and option arguments. And this provides methods to check if they are specified and to retrieve them.

func NewCmd added in v0.8.0

func NewCmd() Cmd

NewCmd is the function that creates a Cmd instance iwth command line arguments obtained from os.Args.

func (Cmd) HasOpt

func (cmd Cmd) HasOpt(name string) bool

HasOpt is the method that checks whether an option with the specified name exists.

func (Cmd) OptArg

func (cmd Cmd) OptArg(name string) string

OptArg is the method that returns the option argument with the specified name. If the option has multiple arguments, this method returns the first argument. If the option is a boolean flag, the method returns an empty string. If the option is not specified in the command line arguments, the return value of this method is an empty string.

func (Cmd) OptArgs

func (cmd Cmd) OptArgs(name string) []string

OptArgs is the method that returns the option arguments with the specified name. If the option has one or multiple arguments, this method returns an array of the arguments. If the option is a boolean flag, the method returns an empty slice. If the option is not specified in the command line arguments, the return value of this method is a nil slice.

func (*Cmd) Parse added in v0.8.0

func (cmd *Cmd) Parse() error

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
Output:

err = <nil>
cmd.Name = app
cmd.Args = [qux quux]
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]

func (*Cmd) ParseFor added in v0.8.0

func (cmd *Cmd) ParseFor(optStore any) error

ParseFor is the method to parse command line arguments and set their values to the option store which is passed as an argument.

This method divides command line arguments to command arguments and options, then sets the options to the option store.

Within this method, a slice of OptCfg is made from the fields of the option store. This OptCfg array is set to the public field `OptCfgs` of this Cmd instance.

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
Output:

err = <nil>
cmd.Name = app
cmd.Args = [c1 c2]
cmd.HasOpt("FooBar") = true
cmd.HasOpt("Baz") = true
cmd.HasOpt("Qux") = true
cmd.OptArgs("FooBar") = []
cmd.OptArgs("Baz") = [12]
cmd.OptArgs("Qux") = [D E]
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]

func (*Cmd) ParseUntilSubCmd added in v0.8.0

func (cmd *Cmd) ParseUntilSubCmd() (Cmd, error)

ParseUntilSubCmd is the method that parses command line arguments without configurations but stops parsing when encountering first command argument.

This method creates and returns a new Cmd instance that holds the command line arguments starting from the first command argument.

This method parses command line arguments in the same way as the Cmd#parse method, except that it only parses the command line arguments before the first command argument.

Example
Output:

err = <nil>
cmd.Name = app
cmd.Args = []
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]
cmd.OptArgs("foo-bar") = [A]
errSub = <nil>
subCmd.Name = qux
subCmd.Args = [quux]
subCmd.HasOpt("c") = true
subCmd.OptArg("c") = 4
subCmd.OptArgs("c") = [4]

func (*Cmd) ParseUntilSubCmdFor added in v0.8.0

func (cmd *Cmd) ParseUntilSubCmdFor(optStore any) (Cmd, error)

ParseUntilSubCmdFor is the method to parse command line arguments until the first command argument and set their option values to the option store which is passed as an argument.

This method creates and returns a new Cmd instance that holds the command line arguments starting from the first command argument.

This method parses command line arguments in the same way as the Cmd#parse_for method, except that it only parses the command line arguments before the first command argument.

Example
Output:

err = <nil>
cmd.Name = app
cmd.Args = []
cmd.HasOpt("FooBar") = true
cmd.HasOpt("Baz") = true
cmd.HasOpt("Qux") = true
cmd.OptArgs("FooBar") = []
cmd.OptArgs("Baz") = [99]
cmd.OptArgs("Qux") = [A B C]
errSub = <nil>
subCmd.Name = c1
subCmd.Args = [12 D c2 E]
subCmd.HasOpt("b") = true
subCmd.HasOpt("qux") = true
subCmd.HasOpt("q") = true
subCmd.OptArgs("b") = []
subCmd.OptArgs("qux") = []
subCmd.OptArgs("q") = []
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 = 99
options.Qux = [A B C]

func (*Cmd) ParseUntilSubCmdWith added in v0.8.0

func (cmd *Cmd) ParseUntilSubCmdWith(optCfgs []OptCfg) (Cmd, error)

ParseUntilSubCmdWith is the method which parses command line arguments with option configurations but stops parsing when encountering first command argument.

This method creates and returns a new Cmd instance that holds the command line arguments starting from the first command argument.

This method parses command line arguments in the same way as the Cmd#parse_with method, except that it only parses the command line arguments before the first command argument.

The option configurations used to parsing are set into this Cmd instance, and it can be retrieved from its field: Cmd#OptCfgs.

Example
Output:

err = <nil>
cmd.Name = app
cmd.Args = []
cmd.HasOpt("foo-bar") = true
cmd.HasOpt("Bazoo") = false
cmd.HasOpt("X") = false
cmd.HasOpt("corge") = true
len(cmd.OptArg("Bazoo")) = 0
cmd.OptArg("corge") = 99
cmd.OptArgs("Bazoo") = []
cmd.OptArgs("corge") = [99]
errSub = <nil>
subCmd.Name = qux
subCmd.Args = [1 quux]
subCmd.HasOpt("baz") = true
subCmd.HasOpt("z") = true
subCmd.HasOpt("X") = true
len(subCmd.OptArg("baz")) = 0
subCmd.OptArg("z") = 2
len(subCmd.OptArg("X")) = 0
subCmd.OptArgs("baz") = []
subCmd.OptArgs("z") = [2]
subCmd.OptArgs("X") = []

func (*Cmd) ParseWith added in v0.8.0

func (cmd *Cmd) ParseWith(optCfgs []OptCfg) error

ParseWith is the method which parses command line arguments with option configurations. This method divides command line arguments to command arguments and options.

And an option consists of a name and an option argument. Options are separated to long format options and short format options. About long/short format options, since they are same with Parse method, see the comment of that method.

This method allows only options declared in option configurations, basically. An option configuration has fields: StoreKey, Names, HasArg, IsArray, Defaults, Desc, ArgInHelp, and Validator.

When an option matches one of the Names in the option configurations, the option is registered into Cmd with StoreKey. If both HasArg and IsArray are true, the option can have one or multiple option arguments, 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 configurations are given in command line arguments, this method 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 "*".

The option configurations used to parsing are set into this Cmd instance, and it can be retrieved from its field: Cmd#OptCfgs.

Example
Output:

err = <nil>
cmd.Name = app
cmd.Args = [qux quux]
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]

func (Cmd) String added in v0.8.0

func (cmd Cmd) String() string

String is the method that returns the string which represents the content of this instance.

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

func NewHelp() Help

NewHelp is a function to construct a Help instance.

func NewHelpWithMargins added in v0.8.0

func NewHelpWithMargins(marginLeft, marginRight int) Help

NewHelpWithMargins is a function to construct a Help instance with setting left and right margins.

func (*Help) AddOpts

func (help *Help) AddOpts(optCfgs []OptCfg)

AddOpts is a method which adds OptCfg(s) to this Help instance.

func (*Help) AddOptsWithIndent added in v0.8.0

func (help *Help) AddOptsWithIndent(optCfgs []OptCfg, indent int)

AddOptsWithIndent is a method which adds OptCfg(s) with indent size to this Help instance.

func (*Help) AddOptsWithIndentAndMargins added in v0.8.0

func (help *Help) AddOptsWithIndentAndMargins(
	optCfgs []OptCfg, indent, marginLeft, marginRight int,
)

AddOptsWithIndentAndMargins is a method which adds OptCfg(s) with indent size, left and right margins to this Help instance.

func (*Help) AddOptsWithMargins added in v0.8.0

func (help *Help) AddOptsWithMargins(optCfgs []OptCfg, marginLeft, marginRight int)

AddOptsWithMargins is a method which adds OptCfg(s) with left and right margins to this Help instance.

func (*Help) AddText

func (help *Help) AddText(text string)

AddText is a method which adds a text to this Help instance.

func (*Help) AddTextWithIndent added in v0.8.0

func (help *Help) AddTextWithIndent(text string, indent int)

AddTextWithIndent is a method which adds a text with indent size to this Help instance.

func (*Help) AddTextWithIndentAndMargins added in v0.8.0

func (help *Help) AddTextWithIndentAndMargins(text string, indent, marginLeft, marginRight int)

AddTextWithIndnetAndMargins is a method which adds a text with indent size and left and right mergins to this Help instance.

func (*Help) AddTextWithMargins added in v0.8.0

func (help *Help) AddTextWithMargins(text string, marginLeft, marginRight int)

AddTextWithMargins is a method which adds a text with left and right mergins to this Help instance.

func (*Help) AddTexts

func (help *Help) AddTexts(texts []string)

AddTexts is a method which adds an array of texts to this Help instance.

func (*Help) AddTextsWithIndent added in v0.8.0

func (help *Help) AddTextsWithIndent(texts []string, indent int)

AddTextsWithIndent is a method which adds an array of texts with indent size to this Help instance.

func (*Help) AddTextsWithIndentAndMargins added in v0.8.0

func (help *Help) AddTextsWithIndentAndMargins(
	texts []string, indent, marginLeft, marginRight int,
)

AddTextsWithIndnetAndMargins is a method which adds an array of texts with indent size and left and right mergins to this Help instance.

func (*Help) AddTextsWithMargins added in v0.8.0

func (help *Help) AddTextsWithMargins(texts []string, marginLeft, marginRight int)

AddTextsWithMargins is a method which adds an array of texts with left and right mergins to this Help instance.

func (Help) Iter

func (help Help) Iter() HelpIter

Iter is a method which creates a HelpIter instance.

Example
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
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.

func (*HelpIter) Next

func (iter *HelpIter) Next() (string, bool)

Next is a method that returns a line of a help text and a flag which indicates the line is not end.

type OptCfg

type OptCfg struct {
	StoreKey  string
	Names     []string
	HasArg    bool
	IsArray   bool
	Defaults  []string
	Validator *func(string, string, string) error
	Desc      string
	ArgInHelp string
	// contains filtered or unexported fields
}

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

func MakeOptCfgsFor(options any) ([]OptCfg, error)

MakeOptCfgsFor is a function to make a OptCfg array from fields of the option store which is the argument of this function.

Example
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 = []
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 = []
optCfgs[4].HasArg = true
optCfgs[4].IsArray = true
optCfgs[4].Defaults = []
optCfgs[4].Desc =

Directories

Path Synopsis
Package errors contains the error structures that can occur during command line argument parsing.
Package errors contains the error structures that can occur during command line argument parsing.
Package validators contains valiators that checks the number format of the string specified as an option argument in command line arguments.
Package validators contains valiators that checks the number format of the string specified as an option argument in command line arguments.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL