parseargs
A fully featured argument parser for Go
Features
- Short(-s) and long(--long) options
- Positional arguments
- Bool, int, and string input types
- Variadic string arguments
- Git style sub commands
How To Use
Define a struct and assign fields tags, supported tags are
- short: A single character string, used to identify short form options
- long: An arbitrary length string, used to identify long form options
- position: A number, identifying which position(ignoring options) the argument comes from
- position: the string "...", any position not specifically assigned will be in this field
- sub: the string "t", attached to a position argument, anything appearing after will be put into the variadic string array for further parsing
All fields you wish to be assigned to must be public
Valid field types are bool, string, int, and if the position tag is set to "..." field type must be []string
an example struct could be
type MyArgs struct {
ProgName string `position:"0"`
Help bool `short:"h" long:"help"`
Version bool `long:"version"`
Count int `short:"c"`
Command string `position:"1" sub:"t"`
Vari []string `position:"..."`
}
To populate pass os.Args(or another string array), stdin, and a reference of struct to output to
Parse may return an error if invalid arguments are passed, or may panic if the struct is malformed
stdin may be omitted by passing an empty string if you wish you handle it separately
args := &MyArgs{}
stdin := ""
if (fi.Mode() & os.ModeCharDevice) == 0 {
stdinBytes, err := io.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
stdin = string(stdinBytes)
}
err := parseargs.Parse(os.Args, stdin, &args)
if err != nil {
//handle error
}
Things To Consider
- position 0 from os.Args is the name of the program, if you have a variadic field, and do not handle position 0 it WILL be inserted there
- a field can not be a position, and an option(short or long), this is not explicitly prevented, but the behaviour is undefined