go command line option parser
Clone or download
jessevdk Merge pull request #192 from XenoPhex/master
Allow passing value starting with - to custom option
Latest commit c0795c8 Dec 21, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples Show how to exit(0) on --help in example Nov 4, 2016
.travis.yml Remove checking support for 1.7.x and 1.8.x Oct 29, 2018
LICENSE Added license Aug 31, 2012
README.md Update README.md Dec 18, 2018
arg.go Add specification of required rest arg range Aug 25, 2016
arg_test.go Add specification of required rest arg range Aug 25, 2016
assert_test.go Clarify that an error was expected but did not occur Sep 26, 2018
check_crosscompile.sh Added darwin and freebsd in checking cross compile Mar 6, 2013
closest.go Use dynamic programming for Levenshtein distance. Aug 22, 2014
command.go Rename canCli to showInHelp Sep 23, 2018
command_test.go move tests for PassAfterNonOption with commands to command_test Sep 27, 2018
completion.go Add trailing slash when completing single directory Sep 23, 2018
completion_test.go Add trailing slash when completing single directory Sep 23, 2018
convert.go Allow custom flags to read '-' if they are a value validator Oct 29, 2018
convert_test.go Make wrapText newline aware Oct 18, 2015
error.go Do not allow default tag on boolean flags Feb 27, 2016
example_test.go Fix various linting warnings May 22, 2016
flags.go Explain how to use choices Aug 29, 2018
group.go Fix issue #273 Sep 24, 2018
group_test.go Add FindOptionByLongName and FindOptionByShortName Oct 28, 2015
help.go fix #278 Oct 1, 2018
help_test.go fix #278 Oct 1, 2018
ini.go Do not clear isSet before parsing ini Feb 12, 2017
ini_test.go Make falsy tag strings behave intuitively May 21, 2017
long_test.go Move tests into the flags package Dec 18, 2013
man.go formatting fixes Oct 29, 2018
marshal_test.go Run go fmt Aug 25, 2016
multitag.go Explicitly check for newline errors in tag values Dec 18, 2013
option.go Allow custom flags to read '-' if they are a value validator Oct 29, 2018
options_test.go move tests for PassAfterNonOption with commands to command_test Sep 27, 2018
optstyle_other.go Allow forcing posix style flags on Windows Sep 2, 2016
optstyle_windows.go Allow forcing posix style flags on Windows Sep 2, 2016
parser.go Allow custom flags to read '-' if they are a value validator Oct 29, 2018
parser_test.go Allow custom flags to read '-' if they are a value validator Oct 29, 2018
pointer_test.go Initialize custom marshaler pointer as needed Feb 12, 2017
short_test.go Make falsy tag strings behave intuitively May 21, 2017
tag_test.go Run go fmt Dec 19, 2013
termsize.go Fix termsize in wasm arch Sep 6, 2018
termsize_nosysioctl.go Merge branch 'master' into feature/support-windows-console-width-dete… Sep 23, 2018
termsize_windows.go Support windows console width detection May 20, 2018
tiocgwinsz_bsdish.go Do not use unsafe syscall when appengine constraint is set Feb 12, 2017
tiocgwinsz_linux.go Do not use unsafe syscall when appengine constraint is set Feb 12, 2017
tiocgwinsz_other.go Do not use unsafe syscall when appengine constraint is set Feb 12, 2017
unknown_test.go Move tests into the flags package Dec 18, 2013

README.md

go-flags: a go library for parsing command line arguments

GoDoc Build Status Coverage Status

This library provides similar functionality to the builtin flag library of go, but provides much more functionality and nicer formatting. From the documentation:

Package flags provides an extensive command line option parser. The flags package is similar in functionality to the go builtin flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.

Supported features:

  • Options with short names (-v)
  • Options with long names (--verbose)
  • Options with and without arguments (bool v.s. other type)
  • Options with optional arguments and default values
  • Multiple option groups each containing a set of options
  • Generate and print well-formatted help message
  • Passing remaining command line arguments after -- (optional)
  • Ignoring unknown command line options (optional)
  • Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
  • Supports multiple short options -aux
  • Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
  • Supports same option multiple times (can store in slice or last option counts)
  • Supports maps
  • Supports function callbacks
  • Supports namespaces for (nested) option groups

The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and concise specification of your application options. For example:

type Options struct {
	Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}

This specifies one option with a short name -v and a long name --verbose. When either -v or --verbose is found on the command line, a 'true' value will be appended to the Verbose field. e.g. when specifying -vvv, the resulting value of Verbose will be {[true, true, true]}.

Example:

var opts struct {
	// Slice of bool will append 'true' each time the option
	// is encountered (can be set multiple times, like -vvv)
	Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`

	// Example of automatic marshalling to desired type (uint)
	Offset uint `long:"offset" description:"Offset"`

	// Example of a callback, called each time the option is found.
	Call func(string) `short:"c" description:"Call phone number"`

	// Example of a required flag
	Name string `short:"n" long:"name" description:"A name" required:"true"`

	// Example of a flag restricted to a pre-defined set of strings
	Animal string `long:"animal" choice:"cat" choice:"dog"`

	// Example of a value name
	File string `short:"f" long:"file" description:"A file" value-name:"FILE"`

	// Example of a pointer
	Ptr *int `short:"p" description:"A pointer to an integer"`

	// Example of a slice of strings
	StringSlice []string `short:"s" description:"A slice of strings"`

	// Example of a slice of pointers
	PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`

	// Example of a map
	IntMap map[string]int `long:"intmap" description:"A map from string to int"`
}

// Callback which will invoke callto:<argument> to call a number.
// Note that this works just on OS X (and probably only with
// Skype) but it shows the idea.
opts.Call = func(num string) {
	cmd := exec.Command("open", "callto:"+num)
	cmd.Start()
	cmd.Process.Release()
}

// Make some fake arguments to parse.
args := []string{
	"-vv",
	"--offset=5",
	"-n", "Me",
	"--animal", "dog", // anything other than "cat" or "dog" will raise an error
	"-p", "3",
	"-s", "hello",
	"-s", "world",
	"--ptrslice", "hello",
	"--ptrslice", "world",
	"--intmap", "a:1",
	"--intmap", "b:5",
	"arg1",
	"arg2",
	"arg3",
}

// Parse flags from `args'. Note that here we use flags.ParseArgs for
// the sake of making a working example. Normally, you would simply use
// flags.Parse(&opts) which uses os.Args
args, err := flags.ParseArgs(&opts, args)

if err != nil {
	panic(err)
}

fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Name: %s\n", opts.Name)
fmt.Printf("Animal: %s\n", opts.Animal)
fmt.Printf("Ptr: %d\n", *opts.Ptr)
fmt.Printf("StringSlice: %v\n", opts.StringSlice)
fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
fmt.Printf("Remaining args: %s\n", strings.Join(args, " "))

// Output: Verbosity: [true true]
// Offset: 5
// Name: Me
// Ptr: 3
// StringSlice: [hello world]
// PtrSlice: [hello world]
// IntMap: [a:1 b:5]
// Remaining args: arg1 arg2 arg3

More information can be found in the godocs: http://godoc.org/github.com/jessevdk/go-flags