flags.ValidateIncrementFetchOrExit to handle value expecting Flag[string]

This commit is contained in:
bth 2026-01-19 11:37:01 -08:00
commit 03d38b4ba7
3 changed files with 15 additions and 12 deletions

View file

@ -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) {

View file

@ -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:

View file

@ -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: