Subcommands return ExitSuccess when handling --help and -h flags. (#43)
The flags package handles top-level `--help` and `-h` flags by printing
usage info and then exiting with status 0.
Subcommands should handle these help flags similarly, by treating them
as success.
With this changes, we can correctly distinguish between the following
calls:
```
$ cmd subcommand --help # treated as a successful call
$ cmd subcommand --bogus # treated as a usage error
```
diff --git a/subcommands.go b/subcommands.go
index bbc5f0f..078ddac 100644
--- a/subcommands.go
+++ b/subcommands.go
@@ -203,7 +203,17 @@
f := flag.NewFlagSet(name, flag.ContinueOnError)
f.Usage = func() { cdr.ExplainCommand(cdr.Error, cmd) }
cmd.SetFlags(f)
- if f.Parse(cdr.topFlags.Args()[1:]) != nil {
+ if err := f.Parse(cdr.topFlags.Args()[1:]); err != nil {
+ if err == flag.ErrHelp {
+ // For top-level flags, `flags.Parse()` will handle
+ // `--help` and `-h` flags by printing usage information
+ // and exiting with status 0 (success).
+ //
+ // For consistency, we return ExitSuccess here so that
+ // calling a subcommand with `--help` or `-h` will also be
+ // treated as success.
+ return ExitSuccess
+ }
return ExitUsageError
}
return cmd.Execute(ctx, f, args...)