Skip to content

Commit

Permalink
fix: ignore escaped delimiters
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed Jul 26, 2024
1 parent 501c4e9 commit 2b90c21
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/parser/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,17 +412,27 @@ export class Parser<

// multiple with custom delimiter
if (fws.inputFlag.flag.type === 'option' && fws.inputFlag.flag.delimiter && fws.inputFlag.flag.multiple) {
// regex that will identify unescaped delimiters
const makeDelimiter = (delimiter: string) => new RegExp(`(?<!\\\\)${delimiter}`)
return {
...fws,
valueFunction: async (i) =>
(
await Promise.all(
(i.tokens ?? [])
.flatMap((token) => token.input.split((i.inputFlag.flag as OptionFlag<any>).delimiter ?? ','))
.flatMap((token) =>
token.input.split(makeDelimiter((i.inputFlag.flag as OptionFlag<any>).delimiter ?? ',')),
)
// trim, and remove surrounding doubleQuotes (which would hav been needed if the elements contain spaces)
.map((v) =>
v
.trim()
// remove escaped characters from delimiter
// example: --opt="a\,b,c" -> ["a,b", "c"]
.replaceAll(
new RegExp(`\\\\${(i.inputFlag.flag as OptionFlag<any>).delimiter}`, 'g'),
(i.inputFlag.flag as OptionFlag<any>).delimiter ?? ',',
)
.replace(/^"(.*)"$/, '$1')
.replace(/^'(.*)'$/, '$1'),
)
Expand Down
8 changes: 8 additions & 0 deletions test/parser/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,14 @@ See more help with --help`)
expect(error.message).to.include('Expected --foo=b c to be one of: a a, b b')
}
})
it('does not split on escaped delimiter', async () => {
const out = await parse(['--foo', 'a\\,b,c'], {
flags: {
foo: Flags.string({multiple: true, delimiter: ','}),
},
})
expect(out.flags).to.deep.include({foo: ['a,b', 'c']})
})
})
})

Expand Down

0 comments on commit 2b90c21

Please sign in to comment.