Skip to content

Commit

Permalink
Added HelpOrFail() method because I'm lazy.
Browse files Browse the repository at this point in the history
  • Loading branch information
Urethramancer committed Feb 9, 2024
1 parent b99636b commit 3e434ed
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion arg/option.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package arg

import "fmt"
import (
"fmt"
"os"
)

// Option definition.
type Option struct {
Expand Down Expand Up @@ -136,3 +139,21 @@ func (opt *Options) SetOption(group, short, long, help string, defaultvalue any,

return nil
}

// HelpOrFail parses the CLI arguments, then prints the help text and exits if the -h flag is set,
// or prints an error and exits with exit code 2 if something went wrong.
func (opt *Options) HelpOrFail() {
err := opt.Parse(os.Args[1:])
if err != nil {
// -h was supplied somewhere on the command line, so exit cleanly after printing help.
if err == ErrNoArgs {
opt.PrintHelp()
os.Exit(0)
}

// Some other error occurred, probably not an issue with input arguments, so just print the error and exit.
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
os.Exit(2)
}
// If we got this far, everything is fine and the program can proceed.
}

0 comments on commit 3e434ed

Please sign in to comment.