Extensions to go's built-in flag parsing. For when you want a little bit more, but not too much.
Run:
go get github.com/jeffh/flageThis package can use a struct for easy parsing using go's flag package. Supported types are:
- types supported by the
flagpackage - any type that supports the
flag.Valueinterface - any type that supports
encoding.TextMarshalerandencoding.TextUnmarshalerinterfaces
Example:
type Example struct {
Bool bool
Str string
U uint
U64 uint64
I int
I64 int64
F64 float64
D time.Duration
}
var opt Example
StructVar(&opt, nil) // this nil can be an optional flagset, otherwise, assumes flag.CommandLine
flag.Parse()
// opt will be populatedThe argument names are the field names, lower-cased. You can add flage tags to customize them:
type Example struct {
Bool bool `flage:"yes"`
}The tag is comma separated with the following format:
{FlagName},{DefaultValue},{DocString}
FlagName = optional, use "-" to ignore it, leave blank to use lowercase field name behavior
DefaultValue = default value, parsed as if it was an argument flag. Causes panics on failure to parse
DocString = docstring for when -help is used. Commas are accepted.
Finally, you can use structs to create flagsets via FlagSetStruct.
This package provides types that allow them to be used multiple time to build a slice:
var args flage.StringSlice
flag.Var(&args, "arg", "additional arguments to pass. Can be used multiple times")
// ...
flag.Parse()
fmt.Printf("args are: %s", strings.Join(args, ", "))
// slices can be "reset" to clear them
flage.Reset(&args)
fmt.Printf("args are: %s", strings.Join(args, ", "))
// usage: myprogram -arg 1 -arg 2
// output:
// args are: 1, 2
// args are:The following slices are supported:
StringSlicefor slices of stringsFloatSlicefor slices of float64Int64Slicefor slices of int64Uint64Slicefor slices of uint64
These slices also support calling Reset on them to clear those slices, which can be useful
if you're reusing them in flagsets.
This feature is WIP and subject to change.
Sometimes using a bunch of flags is laborious and it would be nice to save to a file. flage provides some helpers to do this:
type Example struct {
Config string
Bool bool
Str string
U uint
U64 uint64
I int
I64 int64
F64 float64
D time.Duration
}
var opt Example
StructVar(&opt, nil)
flag.Parse()
if opt.Config != "" {
args, err := flage.ReadConfigFile(opt.Config)
if err != nil {
// ...
}
flag.CommandLine.Parse(args)
}The above code will allow -config <file> to point to a file that looks like:
# this is a comment and is ignored, # must be at the start of the line (ignoring only whitespace)
-bool
-str "str"
-u 1 -u64 2This is the same as passing in arguments to the command line argument (except
for -config) with a couple of differences:
#are single lined comments- Newlines are converted to spaces