yargs / yargs-parser

:muscle: the mighty option parser used by yargs
http://yargs.js.org/
ISC License
493 stars 119 forks source link

array w/ default breaks requiresArg #445

Open JC3 opened 2 years ago

JC3 commented 2 years ago

yargs 17.5.1

when an array option is given a default value, requiresArg no longer works.

example

console.log(
    yargs(['-s'])
        .option('s', { type: 'array', default: ['turtles'], requiresArg: true })
        .argv
);

expected: failure due to not enough args following -s.

actual: success, default value assigned to -s.

more complete example

import yargs from 'yargs';

let SECTION = msg => console.log(`\n======${msg?` ${msg} `:''}======\n`);

// should fail, and does
SECTION('array + requiresArg');
try {
    console.log(
        yargs(['-s'])
            .option('s', { type: 'array', requiresArg: true })
            .exitProcess(false)
            .argv
    );
} catch { }

// should fail, and does
SECTION('string + default + requiresArg');
try {
    console.log(
        yargs(['-s'])
            .option('s', { type: 'string', default: 'turtles', requiresArg: true })
            .exitProcess(false)
            .argv
    );
} catch { }

// should fail, but doesn't
SECTION('array + default + requiresArg (missing arg)');
console.log(
    yargs(['-s'])
        .option('s', { type: 'array', default: ['turtles'], requiresArg: true })
        .argv
);

// should succeed, and does
SECTION('array + default + requiresArg (with arg)');
console.log(
    yargs(['-s', 'stank', 'bread'])
        .option('s', { type: 'array', default: ['turtles'], requiresArg: true })
        .argv
);

output:

====== array + requiresArg ======

Options:
      --help     Show help                                             [boolean]
      --version  Show version number                                   [boolean]
  -s                                                                     [array]

Not enough arguments following: s

====== string + default + requiresArg ======

Options:
      --help     Show help                                             [boolean]
      --version  Show version number                                   [boolean]
  -s                                               [string] [default: "turtles"]

Not enough arguments following: s

====== array + default + requiresArg (missing arg) ======

{ _: [], s: [ 'turtles' ], '$0': 'yargteststuff.js' }

====== array + default + requiresArg (with arg) ======

{ _: [], s: [ 'stank', 'bread' ], '$0': 'yargteststuff.js' }
bcoe commented 2 years ago

@JC3 thank you for the bug report 👍