I’m writing a command line tool using Go, and am using the standard flag package. My tool will take a series of flag (-X=Y) arguments, and then some string value arguments, e.g.:
myTool [options] requiredArg1 requiredArg2
Easy: you use the flag package to specify and parse the options; once it’s done, flag.Args() will have the two required arguments.
But! how do I handle errors, especially those flag doesn’t see? I want an error to produce something like the following:
I can produce the <Option listing> with flag.PrintDefaults(), and if there’s a problem with an unknown flag then flag will print an error message and usage line. But, what if there’s a problem with the required argument count? How do I output my own error message, and then get flag to print usage and the option listing? What if a string flag value doesn’t match my own predicate; how do I complain? If I do it explicitly in my own, and the user has both an unknown flag and the wrong number of arguments, how do I avoid printing it all out twice? Or, if I decide to do all the error output myself, how do I keep flag from outputting its own messages?
I’ve RTFM’d, but the doc is pretty poor, jumping straight from “just flags” to “customizing your own flag types”; it never talks about the rest of argument parsing that most command line tools will need to do.