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

fix: support environment variables for boolean flags #488

Merged
merged 1 commit into from Sep 8, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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