Throw for author errors and improve (#1165)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Throw errors for author errors. Detect bad variadic when added. * Throw errors for author errors. Detect bad variadic when added.
authored by John Gee · committed by GitHub · parent cb84f6e · Browse files · 4 files·+18 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+18 added−78 removed
- tests:+6 added−56 removed
- other:+12 added−22 removed
Provenance
- Commit
d9ac483- Tree
fa4cbf8- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
cb84f6e
4 files changed+18 added−78 removed
modified:tests/args.variadic.test.js+4 added-12 removed
68 unmodified lines69707172737475767374798075767778798085868788818291928384858668 unmodified lines });
test('when program variadic argument not last then error', () => { const program = new commander.Command(); program .exitOverride() .arguments('<variadicArg...> [optionalArg]') .action(jest.fn);
expect(() => { program.parse(['node', 'test', 'a']); }).toThrow("error: variadic arguments must be last 'variadicArg'"); program.arguments('<variadicArg...> [optionalArg]'); }).toThrow("only the last argument can be variadic 'variadicArg'"); });
test('when command variadic argument not last then error', () => { const program = new commander.Command(); program .exitOverride() .command('sub <variadicArg...> [optionalArg]') .action(jest.fn);
expect(() => { program.parse(['node', 'test', 'sub', 'a']); }).toThrow("error: variadic arguments must be last 'variadicArg'"); program.command('sub <variadicArg...> [optionalArg]'); }).toThrow("only the last argument can be variadic 'variadicArg'"); });});modified:tests/command.executableSubcommand.lookup.test.js+2 added-2 removed
10 unmodified lines111213141515161718193 unmodified lines2324252627272829303176 unmodified lines10 unmodified lines if (process.platform === 'win32') { // Get uncaught thrown error on Windows expect(stderr.length).toBeGreaterThan(0); } else { expect(stderr).toBe('error: pm-list(1) does not exist\n'); expect(stderr).toMatch(new RegExp(/Error: 'pm-list' does not exist/)); } done(); });});3 unmodified lines if (process.platform === 'win32') { // Get uncaught thrown error on Windows expect(stderr.length).toBeGreaterThan(0); } else { expect(stderr).toBe('error: pm-list(1) does not exist\n'); expect(stderr).toMatch(new RegExp(/Error: 'pm-list' does not exist/)); } done(); });});76 unmodified linesmodified:tests/command.exitOverride.test.js-42 removed
11 unmodified lines12 expect(err.code).toBe(code);13 expect(err.message).toBe(message);14 }15 16-const testOrSkipOnWindows = (process.platform === 'win32') ? test.skip : test;17-16 describe('.exitOverride and error details', () => {17 // Use internal knowledge to suppress output to keep test output clean.18 let consoleErrorSpy;19 let writeSpy;151 unmodified lines171 expect(writeSpy).toHaveBeenCalled();172 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);173 });174 177- test('when program variadic argument not last then throw CommanderError', () => {178- // Note: this error is notified during parse, although could have been detected at declaration.179- const program = new commander.Command();180- program181- .exitOverride()182- .arguments('<myVariadicArg...> [optionalArg]')183- .action(jest.fn);184-185- let caughtErr;186- try {187- program.parse(['node', 'test', 'a']);188- } catch (err) {189- caughtErr = err;190- }191-192- expect(consoleErrorSpy).toHaveBeenCalled();193- expectCommanderError(caughtErr, 1, 'commander.variadicArgNotLast', "error: variadic arguments must be last 'myVariadicArg'");194- });195-175 test('when executableSubcommand succeeds then call exitOverride', (done) => {176 const pm = path.join(__dirname, 'fixtures/pm');177 const program = new commander.Command();178 program5 unmodified lines184 185 program.parse(['node', pm, 'silent']);186 });187 209- // Throws directly on Windows210- testOrSkipOnWindows('when executableSubcommand fails then call exitOverride', (done) => {211- // Tricky for override, get called for `error` event then `exit` event.212- const exitCallback = jest.fn()213- .mockImplementationOnce((err) => {214- expectCommanderError(err, 1, 'commander.executeSubCommandAsync', '(error)');215- expect(err.nestedError.code).toBe('ENOENT');216- })217- .mockImplementation((err) => {218- expectCommanderError(err, 0, 'commander.executeSubCommandAsync', '(close)');219- done();220- });221- const pm = path.join(__dirname, 'fixtures/pm');222- const program = new commander.Command();223- program224- .exitOverride(exitCallback)225- .command('does-not-exist', 'fail');226-227- program.parse(['node', pm, 'does-not-exist']);228- });229-188 test('when mandatory program option missing then throw CommanderError', () => {189 const optionFlags = '-p, --pepper <type>';190 const program = new commander.Command();191 program13 unmodified linesmodified:index.js+12 added-22 removed
194 unmodified lines195 * @api public196 */197 198 addCommand(cmd) {199- if (!cmd._name) throw new Error('Command passed to .AddCommand must have a name');199+ if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');200 201 // To keep things simple, block automatic name generation for deeply nested executables.202 // Fail fast and detect when adding rather than later when parsing.203 function checkExplicitNames(commandArray) {95 unmodified lines299 if (argDetails.name) {300 self._args.push(argDetails);301 }302 });303+ this._args.forEach(function(arg, i) {304+ if (arg.variadic && i < self._args.length - 1) {305+ throw new Error(`only the last argument can be variadic '${arg.name}'`);306+ }307+ });308 return this;309 };310 311 /**258 unmodified lines570 571 storeOptionsAsProperties(value) {572 this._storeOptionsAsProperties = (value === undefined) || value;573 if (this.options.length) {569- // This is for programmer, not end user.570- console.error('Commander usage error: call storeOptionsAsProperties before adding options');574+ throw new Error('call .storeOptionsAsProperties() before adding options');575 }576 return this;577 };578 160 unmodified lines739 });740 }741 proc.on('error', function(err) {742 if (err.code === 'ENOENT') {739- console.error('error: %s(1) does not exist', bin);743+ const executableMissing = `'${bin}' does not exist744+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead745+ - if the default executable name is not suitable, use the executableFile option to supply a custom name`;746+ throw new Error(executableMissing);747 } else if (err.code === 'EACCES') {741- console.error('error: %s(1) not executable', bin);748+ throw new Error(`'${bin}' not executable`);749 }750 if (!exitCallback) {751 process.exit(1);752 } else {62 unmodified lines815 this._args.forEach(function(arg, i) {816 if (arg.required && args[i] == null) {817 self.missingArgument(arg.name);818 } else if (arg.variadic) {812- if (i !== self._args.length - 1) {813- self.variadicArgNotLast(arg.name);814- }815-819 args[i] = args.splice(i);820 }821 });822 248 unmodified lines1071 this._exit(1, 'commander.unknownCommand', message);1072 };1073 1074 /**1072- * Variadic argument with `name` is not the last argument as required.1073- *1074- * @param {String} name1075- * @api private1076- */1077-1078- variadicArgNotLast(name) {1079- const message = `error: variadic arguments must be last '${name}'`;1080- console.error(message);1081- this._exit(1, 'commander.variadicArgNotLast', message);1082- };1083-1084- /**1075 * Set the program version to `str`.1076 *1077 * This method auto-registers the "-V, --version" flag1078 * which will print the version number when passed.544 unmodified lines