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

fix: positional array defaults should not be combined with provided values #2006

Merged
merged 1 commit into from Aug 13, 2021
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
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