Add CombinedConfig#hasKey(string).

This commit is contained in:
Jonathan Bernard 2023-05-13 07:17:43 -05:00
parent 751b3222db
commit 4bf35c336e

View File

@ -6,6 +6,12 @@ type
docopt*: Table[string, Value]
json*: JsonNode
func keyNames(key: string): tuple[arg, env, json: string] =
result = (
"--" & key,
key.replace('-', '_').toUpper,
key.replace(re"(-\w)", proc (m: RegexMatch): string = ($m)[1..1].toUpper))
template walkFieldDefs*(t: NimNode, body: untyped) =
let tTypeImpl = t.getTypeImpl
@ -52,9 +58,7 @@ proc findConfigFile*(name: string, otherLocations: seq[string] = @[]): string =
raise newException(ValueError, "could not find configuration file")
proc getVal*(cfg: CombinedConfig, key: string): string =
let argKey = "--" & key
let envKey = key.replace('-', '_').toUpper
let jsonKey = key.replace(re"(-\w)", proc (m: RegexMatch): string = ($m)[1..1].toUpper)
let (argKey, envKey, jsonKey) = keyNames(key)
if cfg.docopt.contains(argKey) and cfg.docopt[argKey]: return $cfg.docopt[argKey]
elif existsEnv(envKey): return getEnv(envKey)
@ -75,9 +79,7 @@ proc getVal*(cfg: CombinedConfig, key, default: string): string =
except: return default
proc getJson*(cfg: CombinedConfig, key: string): JsonNode =
let argKey = "--" & key
let envKey = key.replace('-', '_').toUpper
let jsonKey = key.replace(re"(-\w)", proc (m: RegexMatch): string = ($m)[1..1].toUpper)
let (argKey, envKey, jsonKey) = keyNames(key)
if cfg.docopt.contains(argKey) and cfg.docopt[argKey]: return parseJson($cfg.docopt[argKey])
elif existsEnv(envKey): return parseJson(getEnv(envKey))
@ -88,6 +90,14 @@ proc getJson*(cfg: CombinedConfig, key: string, default: JsonNode): JsonNode =
try: return getJson(cfg, key)
except: return default
proc hasKey*(cfg: CombinedConfig, key: string): bool =
let (argKey, envKey, jsonKey) = keyNames(key)
return
(cfg.docopt.contains(argKey) and cfg.docopt[argKey]) or
existsEnv(envKey) or
cfg.json.hasKey(jsonKey)
proc loadEnv*(): StringTableRef =
result = newStringTable()