I'm using the "flag" package to parse command line arguments for my
tiny app "addinclude" [1], which is my very first application written
in Go.
However, I can't find an elegant way to check for long and short
versions of arguments (like "-v" and "--version").
This is what I ended up with in the latest version (I was parsing
flag.Args() myself in earlier versions):
nofix_text := "don't change the include text"
top_text := "add the include at the top"
version_text := "show the current version"
help_text := "this brief help"
test_text := "perform self testing"
var nofix_long *bool = flag.Bool("nofix", false, nofix_text)
var nofix_short *bool = flag.Bool("n", false, nofix_text)
var top_long *bool = flag.Bool("top", false, top_text)
var top_short *bool = flag.Bool("t", false, top_text)
var version_long *bool = flag.Bool("version", false, version_text)
var version_short *bool = flag.Bool("v", false, version_text)
var help_long *bool = flag.Bool("help", false, help_text)
var help_short *bool = flag.Bool("h", false, help_text)
var test_long *bool = flag.Bool("test", false, test_text)
flag.Parse()
nofix := *nofix_long || *nofix_short
top := *top_long || *top_short
version := *version_long || *version_short
help := *help_long || *help_short
test := *test_long
I don't find this particularly elegant, but I stuck to what felt most
like "the blessed way of parsing arguments in Go".
Is there a better or more elegant way of doing this in Go?
Here's the app:
1. http://addinclude.roboticoverlords.org/
Thanks.
Best regards,
Alexander Rødseth
> However, I can't find an elegant way to check for long and short
> versions of arguments (like "-v" and "--version").
(...)
> var nofix_long *bool = flag.Bool("nofix", false, nofix_text)
> var nofix_short *bool = flag.Bool("n", false, nofix_text)
Try this:
var nofix = flag.Bool("nofix", false, "help")
func init() {
flag.BoolVar(nofix, "n", false, "help")
}
With some work you can probably define an Alias function to do this
automatically.
--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/blog
http://niemeyer.net/twitter
I believe that others have written more GNU-like
command line flag parsers.
Russ
https://github.com/droundy/goopt
Its API is still a bit rough, but it works for the things I've wanted
to do with it (including generating man pages, for instance).
David
--
David Roundy