Skip to content
This repository has been archived by the owner on Aug 22, 2023. It is now read-only.

Commit

Permalink
feat: added env to flags
Browse files Browse the repository at this point in the history
  • Loading branch information
jdx committed Feb 3, 2018
1 parent 1121b66 commit 56be8c8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
4 changes: 4 additions & 0 deletions src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export type IFlagBase<T, I> = {
description?: string
hidden?: boolean
required?: boolean
/**
* also accept an environment variable as input
*/
env?: string
parse(input: I): T
}

Expand Down
17 changes: 11 additions & 6 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,17 @@ 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.default) continue
if (typeof flag.default === 'function') {
flags[k] = flag.default({options: flag, flags})
} else {
flags[k] = flag.default
if (flags[k] || flag.type !== 'option') continue
if (flag.env) {
let input = process.env[flag.env]
if (input) flags[k] = flag.parse(input)
}
if (!flags[k] && flag.default) {
if (typeof flag.default === 'function') {
flags[k] = flag.default({options: flag, flags})
} else {
flags[k] = flag.default
}
}
}
return flags
Expand Down
11 changes: 11 additions & 0 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,4 +371,15 @@ See more help with --help`)
}).to.throw('Expected invalidopt to be one of: myopt, myotheropt')
})
})

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

0 comments on commit 56be8c8

Please sign in to comment.