From 5801b79e202ed4a2e1ff8f01fa68b5bd7e266025 Mon Sep 17 00:00:00 2001 From: Benjamin Coe Date: Sat, 18 Feb 2017 09:28:28 -0800 Subject: [PATCH] fix: we should apply validation prior to executing a command's handler --- lib/command.js | 8 ++++---- test/command.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/command.js b/lib/command.js index 6c503161f..89dadc1f9 100644 --- a/lib/command.js +++ b/lib/command.js @@ -178,14 +178,14 @@ module.exports = function (yargs, usage, validation) { positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs) } - if (commandHandler.handler && !yargs._hasOutput()) { - commandHandler.handler(innerArgv) - } - // we apply validation post-hoc, so that custom // checks get passed populated positional arguments. yargs._runValidation(innerArgv, aliases, positionalMap) + if (commandHandler.handler && !yargs._hasOutput()) { + commandHandler.handler(innerArgv) + } + currentContext.commands.pop() numFiles = currentContext.files.length - numFiles if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles) diff --git a/test/command.js b/test/command.js index be19f7cdf..9396e144e 100644 --- a/test/command.js +++ b/test/command.js @@ -997,6 +997,20 @@ describe('Command', function () { return done() }) }) + + it('does not fire command if validation fails', function (done) { + var commandRun = false + yargs() + .strict() + .command('hi ', 'The hi command', function () {}, function (argv) { + commandRun = true + }) + .parse('hi ben --hello=world', function (err, argv, output) { + commandRun.should.equal(false) + err.message.should.equal('Unknown argument: hello') + return done() + }) + }) }) describe('types', function () {