Skip to content

Commit

Permalink
fix: support environment variables for boolean flags (#488) (#490)
Browse files Browse the repository at this point in the history
fixes #487

I am happy to contribute to the docs if this is accepted.

Co-authored-by: Justin Wyer <justin@wyer.dev>
  • Loading branch information
mdonnalley and justinwyer committed Sep 8, 2022
1 parent 29f76fe commit 506945c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 11 deletions.
15 changes: 10 additions & 5 deletions src/parser/parse.ts
Expand Up @@ -198,13 +198,18 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
for (const k of Object.keys(this.input.flags)) {
const flag = this.input.flags[k]
if (flags[k]) continue
if (flag.type === 'option' && flag.env) {
if (flag.env) {
const input = process.env[flag.env]
if (input) {
this._validateOptions(flag, input)
if (flag.type === 'option') {
if (input) {
this._validateOptions(flag, input)

// eslint-disable-next-line no-await-in-loop
flags[k] = await flag.parse(input, this.context, flag)
// eslint-disable-next-line no-await-in-loop
flags[k] = await flag.parse(input, this.context, flag)
}
} else if (flag.type === 'boolean') {
// eslint-disable-next-line no-negated-condition
flags[k] = input !== undefined ? ['true', 'TRUE', '1', 'yes', 'YES', 'y', 'Y'].includes(input) : false
}
}

Expand Down
44 changes: 38 additions & 6 deletions test/parser/parse.test.ts
Expand Up @@ -860,13 +860,45 @@ See more help with --help`)
})

describe('env', () => {
it('accepts as environment variable', async () => {
process.env.TEST_FOO = '101'
const out = await parse([], {
flags: {foo: flags.string({env: 'TEST_FOO'})},
describe('string', () => {
it('accepts as environment variable', async () => {
process.env.TEST_FOO = '101'
const out = await parse([], {
flags: {foo: flags.string({env: 'TEST_FOO'})},
})
expect(out.flags.foo).to.equal('101')
delete process.env.TEST_FOO
})
expect(out.flags.foo).to.equal('101')
delete process.env.TEST_FOO
})

describe('boolean', () => {
const truthy = ['true', 'TRUE', '1', 'yes', 'YES', 'y', 'Y']
for (const value of truthy) {
it(`accepts '${value}' as a truthy environment variable`, async () => {
process.env.TEST_FOO = value
const out = await parse([], {
flags: {
foo: flags.boolean({env: 'TEST_FOO'}),
},
})
expect(out.flags.foo).to.be.true
delete process.env.TEST_FOO
})
}

const falsy = ['false', 'FALSE', '0', 'no', 'NO', 'n', 'N']
for (const value of falsy) {
it(`accepts '${value}' as a falsy environment variable`, async () => {
process.env.TEST_FOO = value
const out = await parse([], {
flags: {
foo: flags.boolean({env: 'TEST_FOO'}),
},
})
expect(out.flags.foo).to.be.false
delete process.env.TEST_FOO
})
}
})
})

Expand Down

0 comments on commit 506945c

Please sign in to comment.