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

feat: handle custom parser nested array for multiple flag #568

Merged
merged 1 commit into from Dec 6, 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
2 changes: 1 addition & 1 deletion src/interfaces/parser.ts
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[]>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add alternative T[] return value (would be the nested array returned by flag.parse)


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
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]))
peternhale marked this conversation as resolved.
Show resolved Hide resolved
} else {
flags[token.flag] = value
}
Expand Down
16 changes: 16 additions & 0 deletions test/parser/parse.test.ts
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