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: setting default: undefined causes implies to throw #2335

Closed
Closed
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
14 changes: 9 additions & 5 deletions lib/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ export function validation(
return implied;
};

function keyExists(argv: Arguments, val: any): any {
function keyDefined(argv: Arguments, val: any): any {
// convert string '1' to number 1
const num = Number(val);
val = isNaN(num) ? val : num;
Expand All @@ -339,10 +339,14 @@ export function validation(
} else if (val.match(/^--no-.+/)) {
// check if key/value doesn't exist
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
val =
!Object.prototype.hasOwnProperty.call(argv, val) ||
argv[val] === undefined;
} else {
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
val =
Object.prototype.hasOwnProperty.call(argv, val) &&
argv[val] !== undefined;
}
return val;
}
Expand All @@ -355,8 +359,8 @@ export function validation(
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
key = keyDefined(argv, key);
value = keyDefined(argv, value);

if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
Expand Down
13 changes: 13 additions & 0 deletions test/validation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,19 @@ describe('validation tests', () => {
failCalled.should.equal(true);
});

it("doesn't fail if implied key exists with value undefined", () => {
yargs()
.option('foo', {
type: 'string',
default: undefined,
})
.implies('foo', 'bar')
.fail(() => {
expect.fail();
})
.parse();
});

it("doesn't fail if implied key exists with value 0", () => {
yargs('--foo --bar 0')
.implies('foo', 'bar')
Expand Down