Skip to content

Commit

Permalink
Support -? as an alias for --help
Browse files Browse the repository at this point in the history
Also print errors before and after usage, like pflag.
  • Loading branch information
thockin committed Jun 8, 2024
1 parent 5e40d47 commit aa2ac24
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ func main() {

flVersion := pflag.Bool("version", false, "print the version and exit")
flHelp := pflag.BoolP("help", "h", false, "print help text and exit")
pflag.BoolVarP(flHelp, "__?", "?", false, "print help text and exit") // support -? as an alias to -h
pflag.CommandLine.MarkHidden("__?")

Check failure on line 145 in main.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `pflag.CommandLine.MarkHidden` is not checked (errcheck)
flManual := pflag.Bool("man", false, "print the full manual and exit")

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

// For whatever reason pflag hardcodes stderr for the "usage" line when
// using the default FlagSet. We tweak the output a bit anyway.
usage := func(out io.Writer, msg string) {
// When pflag parsing hits an error, it prints a message before and
// after the usage, which makes for nice reading.
if msg != "" {
fmt.Fprintln(out, msg)
}
fmt.Fprintln(out, "Usage:")
pflag.CommandLine.SetOutput(out)
pflag.PrintDefaults()
if msg != "" {
fmt.Fprintln(out, msg)
}
}
pflag.Usage = func() { usage(os.Stderr, "") }

//
// Parse and verify flags. Errors here are fatal.
//
Expand All @@ -318,8 +337,7 @@ func main() {
os.Exit(0)
}
if *flHelp {
pflag.CommandLine.SetOutput(os.Stdout)
pflag.PrintDefaults()
usage(os.Stdout, "")
os.Exit(0)
}
if *flManual {
Expand All @@ -329,7 +347,7 @@ func main() {

// Make sure we have a root dir in which to work.
if *flRoot == "" {
fmt.Fprintf(os.Stderr, "ERROR: --root must be specified\n")
usage(os.Stderr, "required flag: --root must be specified")
os.Exit(1)
}
var absRoot absPath
Expand Down Expand Up @@ -1029,6 +1047,8 @@ func handleConfigError(log *logging.Logger, printUsage bool, format string, a ..
fmt.Fprintln(os.Stderr, s)
if printUsage {
pflag.Usage()
// pflag prints flag errors both before and after usage
fmt.Fprintln(os.Stderr, s)
}
log.ExportError(s)
os.Exit(1)
Expand Down

0 comments on commit aa2ac24

Please sign in to comment.