Skip to content

Commit

Permalink
Improved graceful handling of flags and arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
Steven Xie committed Aug 12, 2018
1 parent 7758fbd commit de05293
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
4 changes: 3 additions & 1 deletion args.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ func parseArgs(args []string) (str string, reps int) {

if nargs == 0 {
// Quit if no arguments were received.
fmt.Fprintln(os.Stderr, "Did not receive any arguments! Exiting.")
fmt.Printf("Warning: Did not receive any arguments!\n\n")
showHelp()

os.Exit(2)
}
if nargs > 2 {
Expand Down
34 changes: 24 additions & 10 deletions flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,44 @@ import (
"os"
)

// Opts are flag-enabled options for dgen.
var Opts struct {
// Stats will show statistics at the end of the string dump.
Stats bool `short:"s" long:"stats" description:"Show statistics after string dump."`
var (
// Opts are flag-enabled options for dgen.
Opts struct {
// Stats will show statistics at the end of the string dump.
Stats bool `short:"s" long:"stats" description:"Show statistics after string dump."`
}

fparser = flags.NewParser(&Opts, flags.Default)
)

func showHelp() {
fparser.WriteHelp(os.Stdout)
}

func parseFlags() (args []string) {
args, err := flags.Parse(&Opts)
args, err := fparser.Parse()

if err != nil {
if flagerr, ok := err.(*flags.Error); ok {
switch flagerr.Type {
// Ignore minor parsing errors.
case flags.ErrDuplicatedFlag, flags.ErrInvalidChoice:
fmt.Printf("Warning: Caught a discrepancy while parsing flags: %v. "+
"Proceeding anyways...\n", err)
fmt.Println("Warning: Caught a discrepancy while parsing flags; " +
"proceeding anyways...")
return args

// Friendly exit if help flag was triggered.
// Friendly exit if help flag was triggered.
case flags.ErrHelp:
os.Exit(0)

case flags.ErrUnknownFlag:
fmt.Print("\n")
showHelp()
os.Exit(4)

default:
fmt.Fprintf(os.Stderr, "Failed to parse flags: %v (error type: %s)\n",
err, flagerr.Type)
fmt.Fprintln(os.Stderr, "Encountered flag parsing error of type:",
flagerr.Type)
os.Exit(4)
}
}
Expand Down

0 comments on commit de05293

Please sign in to comment.