I've written a reimplementation of the redis-benchmark in Go and part of that is parsing options from the command line. I evaluated several libraries but nothing I found seem to do what I had in mind.
Here is the code:
// ParseArguments parses a string array and returns a populated Options struct func ParseArguments(arguments []string) Options { options := defaultOptions args := arguments[1:] var errOptions Options for i := 0; i < len(args); i++ { if args[i] == "--help" || args[i] == "-h" { return Options{ShowHelp: true, HelpText: helpText} } else if args[i] == "--host" || args[i] == "-H" { i++ if i >= len(args) { return buildHelp("Error: Incorrect parameters specified") } options.Host = args[i] } else if args[i] == "--requests" || args[i] == "-n" { options.Requests, errOptions = parseNumber(args, &i) if errOptions.ShowHelp { return errOptions } } else if args[i] == "--clients" || args[i] == "-c" { options.Connections, errOptions = parseNumber(args, &i) if errOptions.ShowHelp { return errOptions } } else if args[i] == "--tests" || args[i] == "-t" { i++ if i >= len(args) { return buildHelp("Error: Incorrect parameters specified") } options.Tests = strings.Split(args[i], ",") for i := range options.Tests { options.Tests[i] = strings.ToUpper(options.Tests[i]) } } else if args[i] == "--port" || args[i] == "-p" { options.Port, errOptions = parseNumber(args, &i) if errOptions.ShowHelp { return errOptions } } else { return buildHelp(fmt.Sprintf("Error: Invalid parameter: %v", args[i])) } } return options }
(For more context, the rest of the file is on github).
When gocyclo is run over the code the function gets a complexity of 20. I'm interested in suggestions that could reduce this to below the threshold of 10.
flag
from the standard library?\$\endgroup\$struct
with typed fields. Will look at it again.\$\endgroup\$