Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(environment): Support nested options in environment variables #26

Merged
merged 1 commit into from
Apr 11, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -444,9 +444,16 @@ function parse (args, opts) {
var prefix = typeof envPrefix === 'string' ? envPrefix : ''
Object.keys(process.env).forEach(function (envVar) {
if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
var key = camelCase(envVar.substring(prefix.length))
if (((configOnly && flags.configs[key]) || !configOnly) && (!(key in argv) || flags.defaulted[key])) {
setArg(key, process.env[envVar])
// get array of nested keys and convert them to camel case
var keys = envVar.split('__').map(function (key, i) {
if (i === 0) {
key = key.substring(prefix.length)
}
return camelCase(key)
})

if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
setArg(keys.join('.'), process.env[envVar])
}
}
})
Expand Down
33 changes: 33 additions & 0 deletions test/yargs-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -1536,6 +1536,39 @@ describe('yargs-parser', function () {
result.should.have.property('truthy')
result.z.should.equal(55)
})

it('should apply all nested env vars', function () {
process.env.TEST_A = 'a'
process.env.TEST_NESTED_OPTION__FOO = 'baz'
process.env.TEST_NESTED_OPTION__BAR = 'bar'
var result = parser(['--nestedOption.foo', 'bar'], {
envPrefix: 'TEST'
})

result.should.have.property('a', 'a')
result.should.have.property('nestedOption').and.deep.equal({
foo: 'bar',
bar: 'bar'
})
})

it('should apply nested env var if argv value is using default value', function () {
process.env.TEST_A = 'a'
process.env.TEST_NESTED_OPTION__FOO = 'baz'
process.env.TEST_NESTED_OPTION__BAR = 'bar'
var result = parser([], {
envPrefix: 'TEST',
default: {
'nestedOption.foo': 'banana'
}
})

result.should.have.property('a', 'a')
result.should.have.property('nestedOption').and.deep.equal({
foo: 'baz',
bar: 'bar'
})
})
})

describe('configuration', function () {
Expand Down