add value check prior to parsing

This commit is contained in:
Daylin Morgan 2024-11-13 09:07:54 -06:00
parent b21a889a8d
commit 88572a6ce4
Signed by: daylin
GPG key ID: 950D13E9719334AD

View file

@ -569,13 +569,21 @@ func generateCliHelperProc(cfg: CliCfg, printHelpName: NimNode): NimNode =
styles = `styles`, styles = `styles`,
))) )))
proc preParseCheck(key: string, val: string) =
if val == "":
hwylCliError(
"expected value for flag: [b]" & key
)
proc parse*(p: OptParser, key: string, val: string, target: var bool) = proc parse*(p: OptParser, key: string, val: string, target: var bool) =
target = true target = true
proc parse*(p: OptParser, key: string, val: string, target: var string) = proc parse*(p: OptParser, key: string, val: string, target: var string) =
preParseCheck(key, val)
target = val target = val
proc parse*(p: OptParser, key: string, val: string, target: var int) = proc parse*(p: OptParser, key: string, val: string, target: var int) =
preParseCheck(key, val)
try: try:
target = parseInt(val) target = parseInt(val)
except: except:
@ -591,15 +599,17 @@ macro enumNames(a: typed): untyped =
result.add newLit ai.strVal result.add newLit ai.strVal
proc parse*[E: enum](p: OptParser, key: string, val: string, target: var E) = proc parse*[E: enum](p: OptParser, key: string, val: string, target: var E) =
preParseCheck(key, val)
try: try:
target = parseEnum[E](val) target = parseEnum[E](val)
except: except:
let choices = enumNames(E).join(",") let choices = enumNames(E).join(",")
hwylCliError( hwylCliError(
"failed to parse value for [b]" & key & "[/] as enum: [b]" & val & "[/], expected one of: " & choices "failed to parse value for [b]" & key & "[/] as enum: [b]" & val & "[/] expected one of: " & choices
) )
proc parse*(p: OptParser, key: string, val: string, target: var float) = proc parse*(p: OptParser, key: string, val: string, target: var float) =
preParseCheck(key, val)
try: try:
target = parseFloat(val) target = parseFloat(val)
except: except:
@ -608,6 +618,7 @@ proc parse*(p: OptParser, key: string, val: string, target: var float) =
) )
proc parse*[T](p: OptParser, key: string, val: string, target: var seq[T]) = proc parse*[T](p: OptParser, key: string, val: string, target: var seq[T]) =
preParseCheck(key, val)
var parsed: T var parsed: T
parse(p, key, val, parsed) parse(p, key, val, parsed)
target.add parsed target.add parsed