I am working on a command line application based on Vorpal (http://vorpal.js.org/) and thus NodeJs.
I was wondering whether there was a way to allow (and list in the help) commands depending on a context.
For instance I might want to have the possibility to execute commands A and B on context 1 and commands C and D on context 2. I would then have a command to switch context which should always be valid.
You need to combine the function show
and redefine the exit
function for the context. Simplified implementation example:
var Vorpal = require('vorpal')
var mainDelimiter = 'main'
var main = new Vorpal().delimiter(mainDelimiter + '>')
var contexts = [
{
name: 'context1', help: 'context1 help',
init: function (instance) {
instance
.command('A', 'A help')
.action(function (args, cb) {
this.log('A...')
cb()
})
instance
.command('B', 'B help')
.action(function (args, cb) {
this.log('B...')
cb()
})
}
},
{
name: 'context2', help: 'context2 help',
init: function (instance) {
instance
.command('C', 'C help')
.action(function (args, cb) {
this.log('C...')
cb()
})
instance
.command('D', 'D help')
.action(function (args, cb) {
this.log('D...')
cb()
})
}
}
]
contexts.forEach(function (ctx, i) {
var instance = new Vorpal().delimiter(mainDelimiter + '/' + ctx.name + '>')
ctx.init(instance)
// Override the function "exit" for the context
instance.find('exit').remove()
instance
.command('exit', 'Exit context')
.action(function (args, cb) {
// Switch to the main context
main.show()
cb()
})
main
.command(ctx.name, ctx.help)
.action(function (args, cb) {
// Switch to the selected context
instance.show()
cb()
})
})
main.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With