@auttam/easycli
Version:
A quick and easy way of creating cli for your npm package.
218 lines (217 loc) • 9.58 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RuntimeContext = exports.RuntimeStates = void 0;
const program_args_1 = require("./program-args");
const settings_1 = require("../settings");
const Help = __importStar(require("../help"));
var RuntimeStates;
(function (RuntimeStates) {
RuntimeStates["CREATED"] = "created";
RuntimeStates["READY"] = "ready";
RuntimeStates["RUNNING"] = "running";
RuntimeStates["ERROR"] = "error";
})(RuntimeStates = exports.RuntimeStates || (exports.RuntimeStates = {}));
class RuntimeContext {
constructor(_program) {
this._program = _program;
this._id = Date.now() + Math.random();
this._state = RuntimeStates.CREATED;
this._progArgs = new program_args_1.ProgramArgs();
this._requestedCommand = '';
this._commandIteration = 0;
this._maxCommandIteration = 2;
}
get state() {
return this._state;
}
get contextId() {
return this._id;
}
get requestedCommand() {
return this._requestedCommand;
}
get helpRequested() {
if (this._progArgs.containsOption(['help', 'h']) && settings_1.SettingStore.enableHelpOption)
return true;
if (this._requestedCommand.toLowerCase() == 'help' && settings_1.SettingStore.enableHelpCommand)
return true;
return false;
}
get versionRequested() {
if (this._progArgs.containsOption(['version', 'ver', 'v']) && settings_1.SettingStore.enableVersionOption)
return true;
return false;
}
mapOptions(optionCollection, commandName) {
return __awaiter(this, void 0, void 0, function* () {
var options;
try {
options = yield this._progArgs.createOptionsMap(optionCollection);
}
catch (ex) {
if (settings_1.SettingStore.showHelpOnInvalidOptions) {
return Help.optionInfo(this._program.config, this.requestedCommand, ex.data, ex.message);
}
throw ex;
}
return options;
});
}
mapParams(paramCollection, commandName) {
return __awaiter(this, void 0, void 0, function* () {
var params;
try {
params = yield this._progArgs.createParamsMap(paramCollection);
}
catch (ex) {
if (settings_1.SettingStore.showHelpOnInvalidParams) {
return Help.paramInfo(this._program.config, this.requestedCommand, ex.data, ex.message);
}
throw ex;
}
return params;
});
}
createMethodArgs(collection, $params, $options) {
var args = [];
for (var param of collection.getItems()) {
if ($params.$has(param.propName)) {
args[param.$idx] = $params[param.propName];
}
}
if (collection.indexParamsParam > -1) {
args[collection.indexParamsParam] = $params;
}
if (collection.indexOptionsParam > -1) {
args[collection.indexOptionsParam] = $options;
}
if (collection.indexSpreadParam > -1 && args[collection.indexSpreadParam]) {
var spread = args[collection.indexSpreadParam];
args.splice(collection.indexSpreadParam, 1);
args.splice(collection.indexSpreadParam, 0, ...spread);
}
return args;
}
callDefaultCommand() {
if (settings_1.SettingStore.defaultCommandMethod && this._program[settings_1.SettingStore.defaultCommandMethod]) {
return this.call(settings_1.SettingStore.defaultCommandMethod);
}
}
validateProgram() {
if (!this._program) {
throw new TypeError('Context not initialized');
}
}
init() {
this._state = RuntimeStates.READY;
this._progArgs.read();
this._requestedCommand = this._progArgs.getCommandName();
}
call(methodName, ...details) {
if (this._program && this._program[methodName] && typeof this._program[methodName] == 'function') {
return this._program[methodName].apply(this._program, details);
}
}
runProgram() {
return __awaiter(this, void 0, void 0, function* () {
this.validateProgram();
if (this._state != RuntimeStates.READY) {
throw new TypeError('Cannot run program due to incorrect program state');
}
if (!settings_1.SettingStore.enableCommands) {
if (this._progArgs.isEmpty() && this._program.config.params.containsRequired()) {
return this._program.showHelp();
}
if (settings_1.SettingStore.mainMethod && this._program[settings_1.SettingStore.mainMethod]) {
var $params = yield this.mapParams(this._program.config.params);
var $options = yield this.mapOptions(this._program.config.options);
if (!$params || !$options)
return;
return this.call(settings_1.SettingStore.mainMethod, ...this.createMethodArgs(this._program.config.params, $params, $options));
}
return;
}
if (settings_1.SettingStore.enableCommands) {
if (this._progArgs.isEmpty()) {
if (settings_1.SettingStore.showHelpOnNoCommand) {
return this._program.showHelp();
}
return this.callDefaultCommand();
}
if (!this._requestedCommand) {
return this.callDefaultCommand();
}
if (!this._program.config.commands.length) {
return this.callDefaultCommand();
}
if (this._program.config.options.length && settings_1.SettingStore.prioritizeProgramOptions === true) {
var progOption = yield this.mapOptions(this._program.config.options);
if (!progOption)
return;
if (Object.keys(progOption).length > 1) {
return this.call('onProgramOption', progOption);
}
}
return this.runCommand(this._requestedCommand);
}
});
}
runCommand(reqCommandName) {
return __awaiter(this, void 0, void 0, function* () {
this._commandIteration++;
if (!reqCommandName)
new TypeError('Cannot run command, command name missing');
this.validateProgram();
var command = this._program.config.commands.getByName(reqCommandName);
if (!command) {
if (this._program['onInvalidCommand'] && this._commandIteration <= this._maxCommandIteration) {
return this.call('onInvalidCommand', reqCommandName);
}
return this._program.showHelp(reqCommandName);
}
var $params = yield this.mapParams(command.params);
var $options = yield this.mapOptions(command.options);
if (!$params || !$options)
return;
return this.call(command.propName, ...this.createMethodArgs(command.params, $params, $options));
});
}
exitProgram(error, executionResult, exitCode = 0) {
this.validateProgram();
if (typeof exitCode != 'undefined') {
process.exitCode = exitCode;
}
if (error && !this._program['onExit'])
throw error;
return this.call('onExit', error, executionResult);
}
}
exports.RuntimeContext = RuntimeContext;