Skip to content

Commit aa2ac24

Browse files
committed
Support -? as an alias for --help
Also print errors before and after usage, like pflag.
1 parent 5e40d47 commit aa2ac24

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

main.go

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ func main() {
141141

142142
flVersion := pflag.Bool("version", false, "print the version and exit")
143143
flHelp := pflag.BoolP("help", "h", false, "print help text and exit")
144+
pflag.BoolVarP(flHelp, "__?", "?", false, "print help text and exit") // support -? as an alias to -h
145+
pflag.CommandLine.MarkHidden("__?")
144146
flManual := pflag.Bool("man", false, "print the full manual and exit")
145147

146148
flVerbose := pflag.IntP("verbose", "v",
@@ -306,6 +308,23 @@ func main() {
306308
"DEPRECATED: use --period instead")
307309
mustMarkDeprecated("wait", "use --period instead")
308310

311+
// For whatever reason pflag hardcodes stderr for the "usage" line when
312+
// using the default FlagSet. We tweak the output a bit anyway.
313+
usage := func(out io.Writer, msg string) {
314+
// When pflag parsing hits an error, it prints a message before and
315+
// after the usage, which makes for nice reading.
316+
if msg != "" {
317+
fmt.Fprintln(out, msg)
318+
}
319+
fmt.Fprintln(out, "Usage:")
320+
pflag.CommandLine.SetOutput(out)
321+
pflag.PrintDefaults()
322+
if msg != "" {
323+
fmt.Fprintln(out, msg)
324+
}
325+
}
326+
pflag.Usage = func() { usage(os.Stderr, "") }
327+
309328
//
310329
// Parse and verify flags. Errors here are fatal.
311330
//
@@ -318,8 +337,7 @@ func main() {
318337
os.Exit(0)
319338
}
320339
if *flHelp {
321-
pflag.CommandLine.SetOutput(os.Stdout)
322-
pflag.PrintDefaults()
340+
usage(os.Stdout, "")
323341
os.Exit(0)
324342
}
325343
if *flManual {
@@ -329,7 +347,7 @@ func main() {
329347

330348
// Make sure we have a root dir in which to work.
331349
if *flRoot == "" {
332-
fmt.Fprintf(os.Stderr, "ERROR: --root must be specified\n")
350+
usage(os.Stderr, "required flag: --root must be specified")
333351
os.Exit(1)
334352
}
335353
var absRoot absPath
@@ -1029,6 +1047,8 @@ func handleConfigError(log *logging.Logger, printUsage bool, format string, a ..
10291047
fmt.Fprintln(os.Stderr, s)
10301048
if printUsage {
10311049
pflag.Usage()
1050+
// pflag prints flag errors both before and after usage
1051+
fmt.Fprintln(os.Stderr, s)
10321052
}
10331053
log.ExportError(s)
10341054
os.Exit(1)

0 commit comments

Comments
 (0)