commanding
Version:
A simple yet practical command-Line application framework, written in TypeScript.
84 lines (83 loc) • 3.26 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = __importDefault(require("lodash"));
const parser_1 = require("./helpers/parser");
const CommandHasNoHandler_1 = require("./errors/CommandHasNoHandler");
class Command {
constructor(commandName) {
this.commandName = commandName;
this.argRequirements = [];
this.optionRequirements = [];
this.currentArgPosition = 0;
}
getDescrption() {
return this.commandDescription;
}
description(description) {
this.commandDescription = description;
return this;
}
getArgRequirements() {
return this.argRequirements;
}
getOptionRequirements() {
return this.optionRequirements;
}
argument(name, inputDetails) {
const details = inputDetails ? inputDetails : {};
const requirement = {
name,
position: this.currentArgPosition,
required: lodash_1.default.defaultTo(details.required, false),
description: lodash_1.default.defaultTo(details.description, undefined),
defaultValue: lodash_1.default.defaultTo(details.default, undefined),
sanitizer: lodash_1.default.defaultTo(details.sanitizer, undefined),
};
this.argRequirements.push(requirement);
this.currentArgPosition++;
return this;
}
option(fullName, inputDetails) {
const details = inputDetails ? inputDetails : {};
const normalizedNames = parser_1.normalizeOptionNames(fullName);
const requirement = {
sign: normalizedNames.fullName,
shorthand: normalizedNames.shorthand,
longhand: normalizedNames.longhand,
name: lodash_1.default.get(details, 'name'),
csv: lodash_1.default.defaultTo(details.csv, false),
repeatable: lodash_1.default.defaultTo(details.repeatable, false),
required: lodash_1.default.defaultTo(details.required, false),
description: lodash_1.default.defaultTo(details.description, undefined),
defaultValue: lodash_1.default.defaultTo(details.default, undefined),
sanitizer: lodash_1.default.defaultTo(details.sanitizer, undefined),
};
this.optionRequirements.push(requirement);
return this;
}
handle(handler) {
this.handler = handler;
return this;
}
match(name) {
return this.commandName === name;
}
getName() {
return this.commandName;
}
async execute(parsedArgs, parsedOptions, presenter, logger) {
const mappedArgs = parser_1.mapArguments(parsedArgs, this.argRequirements);
const mappedOptions = parser_1.mapOptions(parsedOptions, this.optionRequirements);
if (this.handler === undefined) {
throw new CommandHasNoHandler_1.CommandHasNoHandler(this);
}
return await this.handler(mappedArgs, mappedOptions, logger);
}
showHelp(executable, presenter) {
presenter.renderCommandHelp(executable, this);
}
}
exports.Command = Command;