UNPKG

ko

Version:
66 lines (65 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const commander_1 = require("commander"); const utils_1 = require("../utils"); var STATE; (function (STATE) { STATE[STATE["INIT"] = 0] = "INIT"; STATE[STATE["PARSE"] = 1] = "PARSE"; STATE[STATE["DONE"] = 2] = "DONE"; })(STATE || (STATE = {})); class Commander { constructor() { this.program = commander_1.program; this.STATE = STATE.INIT; this.cmdSet = {}; this.pkg = require('../../package.json'); } registerCommand({ name, description, args, options, }) { (0, utils_1.assert)(this.STATE === STATE.INIT, `register command should be called in INIT state`); (0, utils_1.assert)(!this.cmdSet[name], `command ${name} has been registered`); (0, utils_1.assert)(description, `command ${name} must have a description`); this.cmdSet[name] = { description, options, args, }; } bindAction(name, fn) { (0, utils_1.assert)(this.STATE === STATE.INIT, `bind command action should be called in INIT state`); (0, utils_1.assert)(this.cmdSet[name], `command ${name} hasn't been registered`); (0, utils_1.assert)(!this.cmdSet[name].action, `command ${name} action has been registered`); this.cmdSet[name].action = fn; } parse() { this.STATE = STATE.PARSE; this.program .description('Project Toolkit for React Applications') .version(this.pkg.version, '-v, --version') .usage('<command> [options]'); Object.keys(this.cmdSet).forEach(name => { const cmd = this.cmdSet[name]; const command = this.program.command(name); command.description(cmd.description); if (cmd.args) { cmd.args.forEach(argv => { command.argument(argv.flags, argv.description); }); } if (cmd.options) { cmd.options.forEach(option => { command.option(option.flags, option.description, option.defaultValue); }); } if (cmd.action) { command.action(cmd.action); } else { throw new Error(`command ${name} action hasn't been bind`); } }); this.program.parse(); this.STATE = STATE.DONE; } } exports.default = Commander;