UNPKG

@2fd/command

Version:

Modular command line tool

94 lines (93 loc) 3.52 kB
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var proxy_1 = require('./proxy'); var params_1 = require('./params'); var command_1 = require('./command'); var utils_1 = require('./utils'); var ExecutorCommand = (function (_super) { __extends(ExecutorCommand, _super); function ExecutorCommand() { _super.apply(this, arguments); this._commands = {}; this._hasToConsume = true; this.version = '0.0.0'; this.description = ''; this.flags = []; this.params = new params_1.Param('[COMMAND]'); } ExecutorCommand.prototype.addCommand = function (name, exec) { var command; var typeOf = typeof exec; if (typeOf === 'string') { command = new proxy_1.StringCommandProxy(exec); } else if (typeOf === 'function') { command = new proxy_1.QuickCommandProxy(exec); } else if (typeOf === 'object' && exec !== null && !Array.isArray(exec)) { command = exec; } else { throw new TypeError("Unexpected type " + utils_1.toString(exec) + " in command " + name); } this._commands[name] = command; return this; }; ExecutorCommand.prototype.addCommands = function (commandList) { var _this = this; Object .keys(commandList) .forEach(function (name) { return _this.addCommand(name, commandList[name]); }); return this; }; ExecutorCommand.prototype.addCommadsNS = function (ns, commandList) { var _this = this; Object .keys(commandList) .forEach(function (name) { return _this.addCommand(ns + ':' + name, commandList[name]); }); return this; }; ExecutorCommand.prototype.action = function (input, output) { var params = input.params; if (this._commands[params.COMMAND]) { var Input = input.constructor; var subInput = new Input(input.argv, input.exec); this._commands[params.COMMAND].handle(subInput, output); } else { this.help(input, output); } }; ExecutorCommand.prototype.hasToConsume = function (input, output) { return !input.params.COMMAND && _super.prototype.hasToConsume.call(this, input, output); }; /** * Return command description */ ExecutorCommand.prototype.helpDescription = function () { return this.description + ' [v' + this.version + ']\n'; }; /** * */ ExecutorCommand.prototype.helpOptions = function () { var _this = this; var commands = Object.keys(this._commands); var max = Math.max.apply(Math, commands.map(function (command) { return command.length; })); var helpCommands = commands .sort(utils_1.commandSort) .map(function (command) { var space = utils_1.repeat(' ', max - command.length + utils_1.TAB_SIZE); return [command + space, _this._commands[command].description]; }); return [ [this.params.definition + ':'] ].concat(helpCommands, _super.prototype.helpOptions.call(this)); }; return ExecutorCommand; }(command_1.SoftCommand)); exports.ExecutorCommand = ExecutorCommand;