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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: passed arguments should take precedence over values in config #2100

Merged
merged 12 commits into from May 14, 2022
Merged
21 changes: 19 additions & 2 deletions lib/command.ts
Expand Up @@ -593,17 +593,34 @@ export class CommandInstance {
positionalKeys.push(...parsed.aliases[key]);
});

const defaults = yargs.getOptions().default;
const {configObjects, default: defaults} = yargs.getOptions();

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, no default was set,
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
if (
// Check configObject values
!configObjects.some(config =>
Object.prototype.hasOwnProperty.call(config, key)
) &&
!configObjects.some(config =>
Object.prototype.hasOwnProperty.call(
config,
this.shim.Parser.camelCase(key)
)
) &&
// Check default values
!Object.prototype.hasOwnProperty.call(defaults, key) &&
!Object.prototype.hasOwnProperty.call(
defaults,
this.shim.Parser.camelCase(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
25 changes: 25 additions & 0 deletions test/command.cjs
Expand Up @@ -264,6 +264,31 @@ describe('Command', () => {
.parse('cmd apples cherries grapes');
});

it('does not combine config values and provided values', () => {
yargs('foo bar baz qux')
.command({
command: '$0 <arg-1> [arg-2] [arg-3..]',
desc: 'default description',
builder: yargs =>
yargs
.option('arg-1', {type: 'string'})
.option('arg-2', {type: 'string'})
.option('arg-3', {type: 'string'})
.config({
arg2: 'bar',
arg3: ['baz', 'qux'],
}),
handler: argv => {
argv.arg1.should.equal('foo');
argv.arg2.should.equal('bar');
argv.arg3.should.deep.equal(['baz', 'qux']);
argv['arg-3'].should.deep.equal(['baz', 'qux']);
},
})
.strict()
.parse();
});

it('does not overwrite options in argv if variadic and preserves falsy values', () => {
yargs
.command({
Expand Down