node-cmdln icon indicating copy to clipboard operation
node-cmdln copied to clipboard

the shortcut pattern doesn't run the subcommand Cmdln instances `.init` method

Open trentm opened this issue 8 years ago • 0 comments

There is a pattern in some cmdln usage of mine where, e.g., triton packages ... is a shortcut for triton package list .... Currently I implement that like this:

// lib/do_packages.js
var targ = require('./do_package/do_list');

function do_packages(subcmd, opts, args, callback) {
    this.handlerFromSubcmd('package').dispatch({
        subcmd: 'list',
        opts: opts,
        args: args
    }, callback);
}

do_packages.help = 'A shortcut for "triton package list".\n' + targ.help;
do_packages.synopses = targ.synopses;
do_packages.options = targ.options;
do_packages.completionArgtypes = targ.completionArgtypes;

do_packages.aliases = ['pkgs'];
do_packages.hidden = true;

module.exports = do_packages;

The problem here is that we call .dispatch(...) on the PackageCli instance that is returned from this.handlerFromSubcmd('package') but the PackageCli.init(...) method doesn't get called. That means that triton packages ... runs in a different state to triton package list ..., which isn't the intent.

The current way the cmdln module works is that it is up to the caller of this.handlerFromSubcmd to call init themself before calling dispatch if this is a Cmdln subclass instance rather than a simple handler function. There is some ceremony in calling and handling init. It would be nice to have a way to avoid having to do that ceremony. The current use case is for having a shortcut or alternative command call some other command. However a possibly more general use case is to be able to lookup and call a handler properly.

Thinking out loud, what about a smarter this.dispatch

function do_packages(subcmd, opts, args, callback) {
    this.dispatch({
        subcmd: ['package', 'list'],
        opts: opts,
        args: args
    }, callback);
}
// ...

That still requires one to know all the attributes to copy for the shortcut. Perhaps we'd also want some sugar for a shortcut.

trentm avatar Nov 29 '17 18:11 trentm