Skip to content

Commit

Permalink
fix: positional array defaults should not be combined with provided v…
Browse files Browse the repository at this point in the history
…alues (#2006)
  • Loading branch information
jly36963 committed Aug 13, 2021
1 parent 5d53144 commit 832222d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/command.ts
Expand Up @@ -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]))
Expand Down
21 changes: 20 additions & 1 deletion test/command.cjs
Expand Up @@ -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..]',
Expand Down

0 comments on commit 832222d

Please sign in to comment.