From 832222d7777da49e5c9da6c5801c2dd90d7fa6a2 Mon Sep 17 00:00:00 2001 From: Landon Yarrington <33426811+jly36963@users.noreply.github.com> Date: Fri, 13 Aug 2021 14:48:45 -0600 Subject: [PATCH] fix: positional array defaults should not be combined with provided values (#2006) --- lib/command.ts | 4 +++- test/command.cjs | 21 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/command.ts b/lib/command.ts index 99f0724bb..19d8053c6 100644 --- a/lib/command.ts +++ b/lib/command.ts @@ -593,15 +593,17 @@ export class CommandInstance { positionalKeys.push(...parsed.aliases[key]); }); + const defaults = yargs.getOptions().default; Object.keys(parsed.argv).forEach(key => { if (positionalKeys.includes(key)) { // any new aliases need to be placed in positionalMap, which // is used for validation. if (!positionalMap[key]) positionalMap[key] = parsed.argv[key]; // Addresses: https://github.com/yargs/yargs/issues/1637 - // If both positionals/options provided, + // If both positionals/options provided, no default was set, // and if at least one is an array: don't overwrite, combine. if ( + !Object.prototype.hasOwnProperty.call(defaults, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key])) diff --git a/test/command.cjs b/test/command.cjs index 984481cf4..189a16596 100644 --- a/test/command.cjs +++ b/test/command.cjs @@ -245,7 +245,26 @@ describe('Command', () => { .parse('--foods apples cherries grapes'); }); - it('does not overwrite options in argv if variadic and preserves falsey values', () => { + it('does not combine positional default and provided values', () => { + yargs() + .command({ + command: 'cmd [foods..]', + desc: 'cmd desc', + builder: yargs => + yargs.positional('foods', { + desc: 'foods desc', + type: 'string', + default: ['pizza', 'wings'], + }), + handler: argv => { + argv.foods.should.deep.equal(['apples', 'cherries', 'grapes']); + argv.foods.should.not.include('pizza'); + }, + }) + .parse('cmd apples cherries grapes'); + }); + + it('does not overwrite options in argv if variadic and preserves falsy values', () => { yargs .command({ command: '$0 [numbers..]',