@devmn/cloud-cli
Version:
CLI tool for Intelligo Cloud.
242 lines • 10.5 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const fs_extra_1 = require("fs-extra");
const fs_1 = require("fs");
const yaml = require("js-yaml");
const inquirer = require("inquirer");
const Constants_1 = require("../utils/Constants");
const StdOutUtil_1 = require("../utils/StdOutUtil");
var ParamType;
(function (ParamType) {
ParamType[ParamType["Config"] = 0] = "Config";
ParamType[ParamType["CommandLine"] = 1] = "CommandLine";
ParamType[ParamType["Question"] = 2] = "Question";
ParamType[ParamType["Env"] = 3] = "Env";
ParamType[ParamType["Default"] = 4] = "Default";
})(ParamType = exports.ParamType || (exports.ParamType = {}));
function isFunction(value) {
return value instanceof Function;
}
function getValue(value, ...args) {
return value instanceof Function ? value(...args) : value;
}
const CONFIG_FILE_NAME = Constants_1.default.COMMON_KEYS.conf;
class Command {
constructor(program) {
this.program = program;
this.aliases = undefined;
this.usage = undefined;
this.description = undefined;
this.configFileProvided = false;
if (!program) {
throw new Error('program is null');
}
}
getCmdLineFlags(alias, type) {
return ((alias.char ? `-${alias.char}, ` : '') +
`--${alias.name}` +
(type !== 'confirm' ? ' <value>' : ''));
}
getCmdLineDescription(option, spaces, alias) {
const msg = alias
? `same as --${option.name}`
: getValue(option.message) || '';
const env = alias ? alias.env : option.env;
return (msg + (env ? ` (env: ${env})` : ''))
.split('\n')
.reduce((acc, l) => (!acc ? l.trim() : `${acc}\n${spaces}${l.trim()}`), '');
}
getOptions(params) {
return getValue(this.options, params) || [];
}
findParamValue(params, name) {
return params && params[name];
}
paramValue(params, name) {
return params && params[name] && params[name].value;
}
paramFrom(params, name) {
return params && params[name] && params[name].from;
}
getDefaultConfigFileOption(preProcessParam) {
return {
name: CONFIG_FILE_NAME,
char: 'c',
env: 'CAPROVER_CONFIG_FILE',
message: 'path of the file where all parameters are defined in JSON or YAML format\n' +
"see others options to know config file parameters' names\n" +
'this is mainly for automation purposes, see docs',
preProcessParam
};
}
build() {
if (!this.command) {
throw new Error('Empty command name');
}
const cmd = this.program.command(this.command);
if (this.aliases && this.aliases.length) {
this.aliases.forEach(alias => alias && cmd.alias(alias));
}
if (this.description) {
cmd.description(this.description);
}
if (this.usage) {
cmd.usage(this.usage);
}
const options = this.getOptions().filter(opt => opt && opt.name && !opt.hide);
const spaces = ' '.repeat(options.reduce((max, opt) => Math.max(max, this.getCmdLineFlags(opt, opt.type).length, (opt.aliases || [])
.filter(alias => alias && alias.name && !alias.hide)
.reduce((amax, a) => Math.max(amax, this.getCmdLineFlags(a, opt.type).length), 0)), 0) + 4);
options.forEach(opt => {
cmd.option(this.getCmdLineFlags(opt, opt.type), this.getCmdLineDescription(opt, spaces), getValue(opt.default));
if (opt.aliases) {
opt.aliases
.filter(alias => alias && alias.name && !alias.hide)
.forEach(alias => cmd.option(this.getCmdLineFlags(alias, opt.type), this.getCmdLineDescription(opt, spaces, alias)));
}
});
cmd.action((...allParams) => __awaiter(this, void 0, void 0, function* () {
if (allParams.length > 1) {
StdOutUtil_1.default.printError(`Positional parameter not supported: ${allParams[0]}\n`, true);
}
const cmdLineOptions = yield this.preAction(allParams[0]);
const optionAliases = this.getOptions()
.filter(opt => opt && opt.name)
.reduce((acc, opt) => [
...acc,
Object.assign({}, opt, { aliasTo: opt.name }),
...(opt.aliases || [])
.filter(alias => alias && alias.name)
.map(alias => (Object.assign({}, alias, { aliasTo: opt.name })))
], []);
if (cmdLineOptions) {
this.action(yield this.getParams(cmdLineOptions, optionAliases));
}
}));
}
preAction(cmdLineoptions) {
return __awaiter(this, void 0, void 0, function* () {
if (this.description) {
StdOutUtil_1.default.printMessage(this.description + '\n');
}
return Promise.resolve(cmdLineoptions);
});
}
getParams(cmdLineOptions, optionAliases) {
return __awaiter(this, void 0, void 0, function* () {
const params = {};
// Read params from env variables
optionAliases
.filter(opta => opta.env && opta.env in process.env)
.forEach(opta => (params[opta.aliasTo] = {
value: process.env[opta.env],
from: ParamType.Env
}));
// Get config file name from env variables or command line options
let file = optionAliases
.filter(opta => cmdLineOptions &&
opta.aliasTo === CONFIG_FILE_NAME &&
opta.name in cmdLineOptions)
.reduce((prev, opta) => cmdLineOptions[opta.name], null);
if (params[CONFIG_FILE_NAME]) {
if (file === null) {
file = params[CONFIG_FILE_NAME].value;
}
delete params[CONFIG_FILE_NAME];
}
optionAliases = optionAliases.filter(opta => opta.aliasTo !== CONFIG_FILE_NAME);
if (file) {
// Read params from config file
const filePath = path_1.isAbsolute(file) ? file : path_1.join(process.cwd(), file);
if (!fs_extra_1.pathExistsSync(filePath)) {
StdOutUtil_1.default.printError(`File not found: ${filePath}\n`, true);
}
let config;
try {
const fileContent = fs_1.readFileSync(filePath, 'utf8').trim();
if (fileContent && fileContent.length) {
if (fileContent.startsWith('{') ||
fileContent.startsWith('[')) {
config = JSON.parse(fileContent);
}
else {
config = yaml.safeLoad(fileContent);
}
}
if (!config) {
throw new Error('Config file is empty!!');
}
}
catch (error) {
StdOutUtil_1.default.printError(`Error reading config file: ${error.message || error}\n`, true);
}
this.configFileProvided = true;
optionAliases
.filter(opta => opta.name in config)
.forEach(opta => (params[opta.aliasTo] = {
value: config[opta.name],
from: ParamType.Config
}));
}
if (cmdLineOptions) {
// Overwrite params from command line options
optionAliases
.filter(opta => opta.name in cmdLineOptions)
.forEach(opta => (params[opta.aliasTo] = {
value: cmdLineOptions[opta.name],
from: ParamType.CommandLine
}));
}
const options = this.getOptions(params).filter(opt => opt && opt.name);
let q = false;
for (const option of options) {
const name = option.name;
let param = params[name];
if (param) {
// Filter and validate already provided params
if (option.filter) {
param.value = yield option.filter(param.value);
}
if (option.validate) {
const err = yield option.validate(param.value);
if (err !== true) {
StdOutUtil_1.default.printError(`${q ? '\n' : ''}${err || 'Error!'}\n`, true);
}
}
}
else if (name !== CONFIG_FILE_NAME) {
// Questions for missing params
if (!isFunction(option.message)) {
option.message += ':';
}
const answer = yield inquirer.prompt([option]);
if (name in answer) {
q = true;
param = params[name] = {
value: answer[name],
from: ParamType.Question
};
}
}
if (option.preProcessParam) {
yield option.preProcessParam(param);
}
}
if (q) {
StdOutUtil_1.default.printMessage('');
}
return params;
});
}
}
exports.default = Command;
//# sourceMappingURL=Command.js.map