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

Commit

Permalink
fix: add context fo parse
Browse files Browse the repository at this point in the history
  • Loading branch information
jdx committed Feb 3, 2018
1 parent 50bf003 commit 85c1e06
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export type IFlagBase<T, I> = {
* also accept an environment variable as input
*/
env?: string
parse(input: I): T
parse(input: I, context: any): T
}

export type IBooleanFlag<T> = IFlagBase<T, boolean> & {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export type ParserInput<TFlags extends flags.Output> = {
export function parse<TFlags, TArgs extends {[name: string]: string}>(argv: string[], options: ParserInput<TFlags>): ParserOutput<TFlags, TArgs> {
const input = {
argv,
context,
context: options.context,
args: (options.args || []).map((a: any) => deps.args.newArg(a as any)),
flags: {
color: deps.flags.defaultFlags.color,
Expand Down
6 changes: 3 additions & 3 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,13 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
} else {
flags[token.flag] = true
}
flags[token.flag] = flag.parse(flags[token.flag])
flags[token.flag] = flag.parse(flags[token.flag], this.context)
} else {
const input = token.input
if (flag.options && !flag.options.includes(input)) {
throw new Errors.FlagInvalidOptionError(flag, input)
}
const value = flag.parse ? flag.parse(input) : input
const value = flag.parse ? flag.parse(input, this.context) : input
if (flag.multiple) {
flags[token.flag] = flags[token.flag] || []
flags[token.flag].push(value)
Expand All @@ -178,7 +178,7 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
if (flags[k] || flag.type !== 'option') continue
if (flag.env) {
let input = process.env[flag.env]
if (input) flags[k] = flag.parse(input)
if (input) flags[k] = flag.parse(input, this.context)
}
if (!flags[k] && flag.default) {
if (typeof flag.default === 'function') {
Expand Down
12 changes: 12 additions & 0 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,4 +382,16 @@ See more help with --help`)
delete process.env.TEST_FOO
})
})

describe('flag context', () => {
it('accepts context in parse', () => {
const out = parse(['--foo'], {
context: {a: 101},
flags: {foo: flags.boolean({
parse: (_: any, ctx: any) => ctx.a
})},
})
expect(out.flags.foo).to.equal(101)
})
})
})

0 comments on commit 85c1e06

Please sign in to comment.