Skip to content

Commit

Permalink
feat: add ability to use multiple env prefixes
Browse files Browse the repository at this point in the history
  • Loading branch information
KuznetsovRoman committed Apr 2, 2024
1 parent 6bdffce commit 6bc5412
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
14 changes: 13 additions & 1 deletion lib/locator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
23 changes: 23 additions & 0 deletions test/locator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
3 changes: 2 additions & 1 deletion typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ declare module "gemini-configparser" {
export type Parser<T> = (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;
};

Expand Down

0 comments on commit 6bc5412

Please sign in to comment.