Skip to content

Commit

Permalink
feat: handle custom parser nested array for multiple flag (#568)
Browse files Browse the repository at this point in the history
@W-12165862@
  • Loading branch information
peternhale authored Dec 6, 2022
1 parent b2d8acf commit 046445c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/interfaces/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export type OptionFlagProps = FlagProps & {
multiple?: boolean;
}

export type FlagParser<T, I, P = any> = (input: I, context: any, opts: P & OptionFlag<T>) => Promise<T>
export type FlagParser<T, I, P = any> = (input: I, context: any, opts: P & OptionFlag<T>) => Promise<T | T[]>

export type FlagBase<T, I, P = any> = FlagProps & {
parse: FlagParser<T, I, P>;
Expand Down
2 changes: 1 addition & 1 deletion src/parser/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
const value = flag.parse ? await flag.parse(input, this.context, flag) : input
if (flag.multiple) {
flags[token.flag] = flags[token.flag] || []
flags[token.flag].push(value)
flags[token.flag].push(...(Array.isArray(value) ? value : [value]))
} else {
flags[token.flag] = value
}
Expand Down
16 changes: 16 additions & 0 deletions test/parser/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,22 @@ See more help with --help`)
})
expect(out.args).to.deep.include({num: '15'})
})
it('flag multiple with arguments, custom parser', async () => {
const out = await parse(
['--foo', './a.txt,./b.txt', '--foo', './c.txt', '--', '15'],
{
args: [{name: 'num'}],
flags: {foo: flags.string({
multiple: true,
parse: async input => input.split(',').map(i => i.trim()),
})},
},
)
expect(out.flags).to.deep.include({
foo: ['./a.txt', './b.txt', './c.txt'],
})
expect(out.args).to.deep.include({num: '15'})
})
})

describe('defaults', () => {
Expand Down

0 comments on commit 046445c

Please sign in to comment.