diff --git a/index.js b/index.js index bddca73af..202de0c10 100644 --- a/index.js +++ b/index.js @@ -461,21 +461,26 @@ Command.prototype.normalize = function(args){ */ Command.prototype.parseArgs = function(args, unknown){ - var cmds = this.commands - , len = cmds.length + var cmdTriggered = false , name; + // If there were a command named args[0], + // then we notify args and unknown options to it. if (args.length) { name = args[0]; if (this.listeners(name).length) { this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); + cmdTriggered = true; + } else if (this.listeners('*').length) { + this.emit('*', args, unknown); + cmdTriggered = true; } - } else { + } + + if (!cmdTriggered) { outputHelpIfNecessary(this, unknown); - - // If there were no args and we have unknown options, + + // If we have unknown options, // then they are extraneous and we need to error. if (unknown.length > 0) { this.unknownOption(unknown[0]); diff --git a/test/test.options.args.unknown.js b/test/test.options.args.unknown.js new file mode 100644 index 000000000..2dc64f6f2 --- /dev/null +++ b/test/test.options.args.unknown.js @@ -0,0 +1,42 @@ +/** + * Module dependencies. + */ + +var program = require('../') + , should = require('should'); + +program + .version('0.0.1') + .option('-f, --foo', 'add some foo') + .option('-b, --bar', 'add some bar'); + +// Make sure we still catch errors with required values for options +var exceptionOccurred = false; +var oldProcessExit = process.exit; +var oldConsoleError = console.error; +process.exit = function() { exceptionOccurred = true; throw new Error(); }; +console.error = function() {}; + +try { + program.parse(['node', 'test', '--foo', '--unknown']); +} catch (ex) { +} +exceptionOccurred.should.be.true; +exceptionOccurred = false; + +try { + program.parse(['node', 'test', '--foo', '-u', 'args1']); +} catch (ex) { +} +exceptionOccurred.should.be.true; +exceptionOccurred = false; + +try { + program.parse(['node', 'test', '--foo', '--unknown', 'args1', 'args2']); +} catch (ex) { +} +exceptionOccurred.should.be.true; +exceptionOccurred = false; + +process.exit = oldProcessExit; +console.error = oldConsoleError;