diff --git a/confutils.nim b/confutils.nim index 16ae972..da95dd7 100644 --- a/confutils.nim +++ b/confutils.nim @@ -129,7 +129,7 @@ when defined(nimscript): 100000 else: - template appInvocation: string = + proc appInvocation: string = try: getAppFilename().splitFile.name except OSError: @@ -1043,7 +1043,12 @@ when hasSerialization: func constructEnvKey*(prefix: string, key: string): string {.raises: [].} = ## Generates env. variable names from keys and prefix following the ## IEEE Open Group env. variable spec: https://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html - (prefix & "_" & key).toUpperAscii.multiReplace(("-", "_"), (" ", "_")) + let fullKey = + if prefix.len > 0: + prefix & "_" & key + else: + key + fullKey.toUpperAscii.multiReplace(("-", "_"), (" ", "_")) # On Posix there is no portable way to get the command # line from a DLL and thus the proc isn't defined in this environment. @@ -1051,6 +1056,11 @@ func constructEnvKey*(prefix: string, key: string): string {.raises: [].} = when not declared(commandLineParams): proc commandLineParams(): seq[string] = discard +proc defaultEnvVarsPrefix(): string = + result = appInvocation() + if result.len == 0: + result = "_" + proc loadImpl[C, SecondarySources]( Configuration: typedesc[C], cmdLine = commandLineParams(), @@ -1063,7 +1073,7 @@ proc loadImpl[C, SecondarySources]( secondarySources: proc ( config: Configuration, sources: ref SecondarySources ) {.gcsafe, raises: [ConfigurationError].} = nil, - envVarsPrefix = appInvocation(), + envVarsPrefix = defaultEnvVarsPrefix(), termWidth = 0 ): Configuration {.raises: [ConfigurationError].} = ## Loads a program configuration by parsing command-line arguments @@ -1349,7 +1359,7 @@ template load*( quitOnFailure = true, ignoreUnknown = false, secondarySources: untyped = nil, - envVarsPrefix = appInvocation(), + envVarsPrefix = defaultEnvVarsPrefix(), termWidth = 0): untyped = block: let secondarySourcesRef = generateSecondarySources(Configuration) diff --git a/tests/test_envvar.nim b/tests/test_envvar.nim index a02d1bf..4f87b25 100644 --- a/tests/test_envvar.nim +++ b/tests/test_envvar.nim @@ -64,4 +64,9 @@ proc testEnvvar() = check conf.somObject.name.string == "helloObject" check conf.somObject.isNice.bool == true + test "env vars no prefix": + putEnv("DATA_DIR", "ENV VAR DATADIR") + let conf = TestConf.load(envVarsPrefix="") + check conf.dataDir.string == "ENV VAR DATADIR" + testEnvvar()