Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vorpal Commands Context

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.

like image 317
Andrea Sindico Avatar asked Apr 02 '18 08:04

Andrea Sindico


1 Answers

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()
like image 116
stdob-- Avatar answered Oct 04 '22 06:10

stdob--