summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdrien Hopkins <adrien.p.hopkins@gmail.com>2023-09-15 10:17:09 -0500
committerAdrien Hopkins <adrien.p.hopkins@gmail.com>2023-09-15 10:17:09 -0500
commit58e9305753f41c401c248bfebc37b68fdd9ebe73 (patch)
tree23f4824ed166400614e0706757c564c7796239cc
parent018c8c53238449217b825d30487d253a26aa60bd (diff)
Improve cmdline argument parsing
Two related changes: - Improve code readability of argument parsing - Add extra error cases for arguments (elaborate on some errors, like the case of parsing the radix)
-rw-r--r--args.go49
1 files changed, 32 insertions, 17 deletions
diff --git a/args.go b/args.go
index 3b2bbdd..fbb4cf0 100644
--- a/args.go
+++ b/args.go
@@ -50,30 +50,45 @@ func parseArgs() (args, error) {
return args{}, errors.New("You cannot use both -t and -c at the same time.")
} else if a.DigitMapOnly && (a.TotativeDigits || a.ExactMTCLarge) {
return args{}, errors.New("You cannot use both -d and -t or -m at the same time.")
+ } else if flag.NArg() < 1 {
+ return args{}, errors.New("Please provide an argument (radix to study).")
+ } else if flag.NArg() > 1 {
+ return args{}, errors.New("Too many arguments provided.")
+ }
+
+ radix, err := strconv.ParseUint(flag.Arg(0), 0, 0)
+ if err != nil {
+ return args{}, uintParsingError(flag.Arg(0), err)
+ } else if radix < 2 {
+ return args{}, errors.New("Cannot use 0 or 1 as radices.")
+ }
+
+ a.Radix = uint(radix)
+ return a, nil
+}
+
+// uintParsingError determines what error to show the user if radix parsing fails.
+// parsed is the radix string that was parsed and uintErr is the resulting error.
+func uintParsingError(parsed string, uintErr error) error {
+ _, floatErr := strconv.ParseFloat(parsed, 64)
+ if floatErr != nil {
+ return fmt.Errorf("Error parsing radix: %w", uintErr)
+ }
+
+ var parsingErr *strconv.NumError
+ if !errors.As(uintErr, &parsingErr) {
+ return fmt.Errorf("Error parsing radix: %w", uintErr)
+ } else if errors.Is(parsingErr.Err, strconv.ErrRange) {
+ return fmt.Errorf("Radix is too large. Please use something smaller.")
} else {
- if flag.NArg() == 1 {
- if radix, err := strconv.ParseUint(flag.Arg(0), 0, 0); err == nil {
- if radix > 1 {
- a.Radix = uint(radix)
- return a, nil
- } else {
- return args{}, errors.New("Radix must be an integer above 1.")
- }
- } else {
- return args{}, fmt.Errorf(
- "Argument must be an integer above 1 [%w].", err)
- }
- } else if flag.NArg() < 1 {
- return args{}, errors.New("Please provide an argument (radix to study).")
- } else {
- return args{}, errors.New("Too many arguments provided.")
- }
+ return fmt.Errorf("Radix must be an unsigned integer.")
}
}
func printHelp() {
fmt.Println("Get important information about a radix.")
fmt.Println("You must provide one argument, which is the radix to get information about.")
+ fmt.Println("The radix must be an unsigned integer above 1.")
fmt.Println("Usage: radix_info [flags...] <radix>")
fmt.Println("Options:")
flag.PrintDefaults()