From 7af0acce68002040e7f60c3dcc5fbbd807e74680 Mon Sep 17 00:00:00 2001 From: Jonathan Bernard Date: Sat, 13 May 2023 07:07:56 -0500 Subject: [PATCH] Add config helper function to find config files in a standardized manner. --- cliutils.nimble | 2 +- cliutils/config.nim | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cliutils.nimble b/cliutils.nimble index 4d4db62..6d09488 100644 --- a/cliutils.nimble +++ b/cliutils.nimble @@ -1,6 +1,6 @@ # Package -version = "0.8.0" +version = "0.8.1" author = "Jonathan Bernard" description = "Helper functions for writing command line interfaces." license = "MIT" diff --git a/cliutils/config.nim b/cliutils/config.nim index e4e51c2..f11ce2a 100644 --- a/cliutils/config.nim +++ b/cliutils/config.nim @@ -1,4 +1,5 @@ -import docopt, json, nre, os, strtabs, strutils +import std/[json, nre, os, sequtils, strtabs, strutils] +import docopt type CombinedConfig* = object @@ -34,6 +35,22 @@ template walkFieldDefs*(t: NimNode, body: untyped) = # cfgType.walkFieldDefs: # 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 = let argKey = "--" & key let envKey = key.replace('-', '_').toUpper