diff --git a/lib/locator.js b/lib/locator.js index 63f8207..5e7aaf0 100644 --- a/lib/locator.js +++ b/lib/locator.js @@ -17,10 +17,22 @@ function parseArgv(argv, cliPrefix) { module.exports = function({options, env, argv, envPrefix = '', cliPrefix = '--'}) { const parsedArgv = parseArgv(argv, cliPrefix); + function getEnvName(prefixes, subKey) { + if (typeof prefixes === 'string') { + return prefixes + subKey; + } + + const relatedEnvPrefixIndex = prefixes.findIndex((prefix => Object.hasOwnProperty.call(env, prefix + subKey))); + const envPrefix = relatedEnvPrefixIndex >= 0 ? prefixes[relatedEnvPrefixIndex] : prefixes[0]; + + return envPrefix + subKey; + } + function getNested(option, {namePrefix, envPrefix, cliPrefix}) { return (subKey) => { - const envName = envPrefix + _.snakeCase(subKey); + const envSubKey = _.snakeCase(subKey); const cliFlag = cliPrefix + _.kebabCase(subKey); + const envName = getEnvName(envPrefix, envSubKey); const argIndex = parsedArgv.lastIndexOf(cliFlag); const subOption = _.get(option, subKey); diff --git a/test/locator.js b/test/locator.js index 8cd49d5..d7b8102 100644 --- a/test/locator.js +++ b/test/locator.js @@ -216,4 +216,27 @@ describe('locator', () => { assert.propertyVal(childPointer, 'envVar', 'env value'); assert.propertyVal(childPointer, 'cliOption', 'cli value'); }); + + it('should support multiple envPrefix values', () => { + const pointer = locatorWithEnv( + {'bar_some_option': 'env value'}, + {envPrefix: ['foo_', 'bar_']} + ); + const childPointer = pointer.nested('someOption'); + + assert.propertyVal(childPointer, 'envVar', 'env value'); + }); + + it('should use first existing envPrefix value', () => { + const pointer = locatorWithEnv( + { + 'bar_some_option': 'another env value', + 'foo_some_option': 'some env value' + }, + {envPrefix: ['foo_', 'bar_']} + ); + const childPointer = pointer.nested('someOption'); + + assert.propertyVal(childPointer, 'envVar', 'some env value'); + }); }); diff --git a/typings/index.d.ts b/typings/index.d.ts index d7c2439..5cc1035 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -9,7 +9,8 @@ declare module "gemini-configparser" { export type Parser = (locator: Locator, config: PartialConfig) => T; type RootPrefixes = { - envPrefix: string; + // If defined as an array and multiple prefixes match, first defined in the array will be used + envPrefix: string | string[]; cliPrefix: string; };