diff --git a/flags/flags.go b/flags/flags.go index c9139e6..677bad3 100644 --- a/flags/flags.go +++ b/flags/flags.go @@ -53,18 +53,27 @@ func HasDashPrefix(s string) bool { return strings.HasPrefix(s, "-") } -func MissingValue(args []string, i int) bool { +// check for non-dashed value ahead in the args slice +func missingValue(args []string, i int) bool { return i+1 == len(args) || HasDashPrefix(args[i+1]) } // if no value ahead in the args, print error and exit -func ValidValueOrExit(args []string, i int) { - if MissingValue(args, i) { +func validValueOrExit(args []string, i int) { + if missingValue(args, i) { log.Printf("um: %s needs a value assignment\n", args[i]) log.Fatal("try: um [cmd] --help") } } +// 1. validate a Flag[string] by looking ahead in args, if missing, os.Exit(1) +// 2. increment the i to skip that value and return +// 3. fetch that value and return +func ValidateIncrementFetchOrExit(args []string, i int) (int, string) { + validValueOrExit(args, i) + return i + 1, args[i+1] +} + // print out help string by reflecting over fields of provided opts struct // and os.Exit(0) func Help(subcmd string, opts any) { diff --git a/sort/sort.go b/sort/sort.go index 7d21ec7..109ab46 100644 --- a/sort/sort.go +++ b/sort/sort.go @@ -34,13 +34,9 @@ func parseArgs(args []string) options { arg := args[i] switch { case arg == opts.Source.Long || arg == opts.Source.Short: - flags.ValidValueOrExit(args, i) - opts.Source.Val = args[i+1] - i++ + i, opts.Source.Val = flags.ValidateIncrementFetchOrExit(args, i) case arg == opts.Key.Long || arg == opts.Key.Short: - flags.ValidValueOrExit(args, i) - opts.Key.Val = args[i+1] - i++ + i, opts.Key.Val = flags.ValidateIncrementFetchOrExit(args, i) case arg == opts.Write.Long || arg == opts.Write.Short: opts.Write.Val = true case arg == opts.Help.Long || arg == opts.Help.Short: diff --git a/tag/tag.go b/tag/tag.go index f3bd616..4173486 100644 --- a/tag/tag.go +++ b/tag/tag.go @@ -32,9 +32,7 @@ func parseArgs(args []string) options { case arg == opts.Invert.Long || arg == opts.Invert.Short: opts.Invert.Val = true case arg == opts.Date.Long || arg == opts.Date.Short: - flags.ValidValueOrExit(args, i) - opts.Date.Val = args[i+1] - i++ + i, opts.Date.Val = flags.ValidateIncrementFetchOrExit(args, i) case arg == opts.Help.Long || arg == opts.Help.Short: flags.Help("tag", opts) default: