Skip to content

Commit

Permalink
fix(command): subcommands via commandDir() now supported for parse(ms…
Browse files Browse the repository at this point in the history
…g, cb) (#678)

* fix: context must be reset or nested sub-commands fail on second invocation

* fix(command): splice context.files when popping context.commands

so context is maintained for multiple command executions
  • Loading branch information
bcoe authored and nexdrew committed Oct 19, 2016
1 parent 02c0970 commit 6b85cc6
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/command.js
Expand Up @@ -134,6 +134,7 @@ module.exports = function (yargs, usage, validation) {
var commandHandler = handlers[command] || handlers[aliasMap[command]]
var innerArgv = argv
var currentContext = yargs.getContext()
var numFiles = currentContext.files.length
var parentCommands = currentContext.commands.slice()
currentContext.commands.push(command)
if (typeof commandHandler.builder === 'function') {
Expand Down Expand Up @@ -168,6 +169,8 @@ module.exports = function (yargs, usage, validation) {
commandHandler.handler(innerArgv)
}
currentContext.commands.pop()
numFiles = currentContext.files.length - numFiles
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
return innerArgv
}

Expand Down
1 change: 1 addition & 0 deletions test/fixtures/cmddir/deep/within-a-dream.js
Expand Up @@ -12,6 +12,7 @@ module.exports = {
},
handler: function (argv) {
var factor = 7
if (argv.context) argv.context.counter++ // keep track of how many times we've invoked this handler.
if (argv.extract) {
if (!argv.withKick) factor -= 2
if (!chancesLevel2(factor)) throw new Error('Something went wrong at level 2! Check your options for increased chance of success.')
Expand Down
15 changes: 15 additions & 0 deletions test/yargs.js
Expand Up @@ -954,6 +954,21 @@ describe('yargs dsl tests', function () {
argv.what.should.equal(true)
})

it('allows nested sub-commands to be invoked multiple times', function () {
var context = {counter: 0}

checkOutput(function () {
var parser = yargs()
.commandDir('fixtures/cmddir')

parser.parse('dream within-a-dream --what', {context: context}, function (_err, argv, _output) {})
parser.parse('dream within-a-dream --what', {context: context}, function (_err, argv, _output) {})
parser.parse('dream within-a-dream --what', {context: context}, function (_err, argv, _output) {})
})

context.counter.should.equal(3)
})

it('overwrites the prior context object, when parse is called multiple times', function () {
var argv = null
var parser = yargs()
Expand Down

0 comments on commit 6b85cc6

Please sign in to comment.