Add config helper function to find config files in a standardized manner.

This commit is contained in:
Jonathan Bernard 2023-05-13 07:07:56 -05:00
parent b1cc4fbe51
commit 7af0acce68
2 changed files with 19 additions and 2 deletions

View File

@ -1,6 +1,6 @@
# Package # Package
version = "0.8.0" version = "0.8.1"
author = "Jonathan Bernard" author = "Jonathan Bernard"
description = "Helper functions for writing command line interfaces." description = "Helper functions for writing command line interfaces."
license = "MIT" license = "MIT"

View File

@ -1,4 +1,5 @@
import docopt, json, nre, os, strtabs, strutils import std/[json, nre, os, sequtils, strtabs, strutils]
import docopt
type type
CombinedConfig* = object CombinedConfig* = object
@ -34,6 +35,22 @@ template walkFieldDefs*(t: NimNode, body: untyped) =
# cfgType.walkFieldDefs: # cfgType.walkFieldDefs:
# let valLookup = quote do: `getVal`( # let valLookup = quote do: `getVal`(
proc initCombinedConfig*(
filename: string,
docopt: Table[string, Value] = initTable[string, Value]()
): CombinedConfig =
result = CombinedConfig(docopt: docopt, json: parseFile(filename))
proc findConfigFile*(name: string, otherLocations: seq[string] = @[]): string =
let cfgLocations = @[
$getEnv(name.strip(chars = {'.'}).toUpper()),
$getEnv("HOME") / name ] & otherLocations
result = cfgLocations.foldl(if fileExists(b): b else: a, "")
if result == "" or not fileExists(result):
raise newException(ValueError, "could not find configuration file")
proc getVal*(cfg: CombinedConfig, key: string): string = proc getVal*(cfg: CombinedConfig, key: string): string =
let argKey = "--" & key let argKey = "--" & key
let envKey = key.replace('-', '_').toUpper let envKey = key.replace('-', '_').toUpper