zcatalyst-cli
Version:
Command Line Tool for CATALYST
231 lines (230 loc) • 11.7 kB
JavaScript
;
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ansi_colors_1 = require("ansi-colors");
const path_1 = require("path");
const languages_1 = require("./languages");
const archiver_1 = __importDefault(require("../../../archiver"));
const endpoints_1 = require("../../../endpoints");
const prompt_1 = __importDefault(require("../../../prompt"));
const runtime_store_1 = __importDefault(require("../../../runtime-store"));
const config_1 = require("../../../util_modules/config");
const constants_1 = require("../../../util_modules/constants");
const fs_1 = require("../../../util_modules/fs");
const js_1 = require("../../../util_modules/js");
const logger_1 = require("../../../util_modules/logger");
const project_1 = require("../../../util_modules/project");
const runtime_1 = __importDefault(require("../../../util_modules/constants/lib/runtime"));
const error_1 = __importDefault(require("../../../error"));
const python_1 = require("../../../fn-utils/lib/python");
const throbber_1 = __importDefault(require("../../../throbber"));
const ensure_java_userconfig_1 = require("../../../fn-utils/lib/ensure-java-userconfig");
const char_1 = require("../../../util_modules/char");
function selFnsPrompt(targs, fnDirPath) {
return __awaiter(this, void 0, void 0, function* () {
const choicesObj = targs.reduce((accumulator, fn) => {
const name = fn.name;
const type = fn.type === constants_1.REMOTE_REF.functions.type[constants_1.FN_TYPE.applogic]
? constants_1.REMOTE_REF.functions.type[constants_1.FN_TYPE.advanced]
: fn.type;
const choice = prompt_1.default.choice(name + ' (' + fn.stack + ')', {
value: {
id: fn.id + '',
stack: fn.stack,
name,
type: type,
source: (0, path_1.join)(fnDirPath, name)
},
short: name
});
accumulator[type] = js_1.JS.isArray(accumulator[type])
? accumulator[type].concat([choice])
: [choice];
return accumulator;
}, {});
const choicesArr = js_1.JS.transform(choicesObj, (result, value, key) => {
result.push(prompt_1.default.separator('----' + key + '----'));
result.push(...value);
return result;
}, []);
const functionsAns = yield prompt_1.default.ask(prompt_1.default.question('functions', 'Select all the functions that you want to pull from remote console : ', {
type: 'checkbox',
choices: choicesArr,
validate: (ansArr) => {
if (js_1.JS.isEmpty(ansArr)) {
return ('Must select at least one feature.\n' +
'(Press ' +
(0, ansi_colors_1.cyan)('<space>') +
' to select, ' +
(0, ansi_colors_1.cyan)('<a>') +
' to toggle all, ' +
(0, ansi_colors_1.cyan)('<i>') +
' to invert selection)');
}
return true;
}
}));
return functionsAns.functions;
});
}
exports.default = (_fns) => __awaiter(void 0, void 0, void 0, function* () {
const fnAPI = yield (0, endpoints_1.functionsAPI)();
const fnDirName = config_1.functionsConfig.source();
const fnDirPath = (0, project_1.resolveProjectPath)(fnDirName);
const fnArr = (yield fnAPI.getAllFunctions());
if (!Array.isArray(fnArr) || fnArr.length === 0) {
(0, logger_1.info)('No function found in remote console.');
return;
}
const fns = Array.isArray(_fns) && _fns.length > 0
? _fns.map((fn) => {
const idx = fnArr.findIndex((_fn) => _fn.name === fn);
if (idx === -1) {
throw new error_1.default('Cannot find the function in remote: ' + fn, {
exit: 2
});
}
const fnTarg = fnArr.splice(idx, 1)[0];
return {
id: fnTarg.id + '',
stack: fnTarg.stack,
name: fnTarg.name,
type: fnTarg.type,
source: (0, path_1.join)(fnDirPath, fnTarg.name)
};
})
: yield selFnsPrompt(fnArr, fnDirPath);
const dirOverwriteQns = [];
yield Promise.all(fns.map((fn) => __awaiter(void 0, void 0, void 0, function* () {
const folderExists = yield fs_1.ASYNC.dirExists(fn.source);
if (folderExists) {
dirOverwriteQns.push(prompt_1.default.question(fn.name, 'Directory ' + (0, ansi_colors_1.underline)(fn.source) + ' already exists. Overwrite ?', {
type: 'confirm',
defaultAns: false
}));
}
})));
const dirOverwriteAns = yield prompt_1.default.ask(...dirOverwriteQns);
let targets = fns.filter((fn) => {
if (dirOverwriteAns[fn.name] === undefined || dirOverwriteAns[fn.name]) {
return true;
}
(0, logger_1.message)('skipping pull of function: ' + fn.name);
return false;
});
if (js_1.JS.isEmpty(targets)) {
return;
}
const throbber = throbber_1.default.getInstance();
targets.forEach((fn) => __awaiter(void 0, void 0, void 0, function* () {
if (dirOverwriteAns[fn.name]) {
yield fs_1.ASYNC.deleteDir(fn.source);
}
throbber.add('function_pull_' + fn.name, {
text: `extracting function [${fn.name}]`
});
}));
runtime_store_1.default.set('context.functions.targets', targets);
let isFnPulled = false;
let isFnPulledFailed = false;
targets = yield Promise.all(targets.map((fn) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b, _c;
try {
yield fs_1.ASYNC.ensureDir(fn.source);
const buffer = (yield fnAPI.download(fn.id));
yield new archiver_1.default().load(buffer).extract((0, path_1.join)(fnDirPath, fn.name)).finalize();
if ((_a = fn.stack) === null || _a === void 0 ? void 0 : _a.startsWith(runtime_1.default.language.node.value)) {
yield (0, languages_1.node)(fn);
}
else if ((_b = fn.stack) === null || _b === void 0 ? void 0 : _b.startsWith(runtime_1.default.language.java.value)) {
yield (0, ensure_java_userconfig_1.ensureJava)(fn);
yield (0, languages_1.java)(fn);
}
else if ((_c = fn.stack) === null || _c === void 0 ? void 0 : _c.startsWith(runtime_1.default.language.python.value)) {
yield (0, languages_1.python)(fn);
const reqFile = (0, path_1.join)(fn.source, constants_1.FILENAME.functions.python_requirements);
const requirementsExists = yield fs_1.ASYNC.readFile(reqFile);
if (requirementsExists && fn.valid) {
try {
yield (0, python_1.removeRequirements)(reqFile, fn);
}
catch (e) {
const err = error_1.default.getErrorInstance(e);
(fn.valid = false), (fn.failure_reason = err.message);
}
}
}
const catalystJsonPth = (0, path_1.join)(fn.source, constants_1.FILENAME.catalyst_config);
const catalystJson = yield fs_1.ASYNC.readJSONFile(catalystJsonPth);
const fnDetails = (yield fnAPI.getFunction(fn.id));
const envVariables = js_1.JS.get(fnDetails, 'configuration.environment.variables', false);
if (catalystJson && envVariables) {
catalystJson.deployment.env_variables = envVariables;
yield fs_1.ASYNC.writeJSONFile(catalystJsonPth, catalystJson);
}
isFnPulled = true;
}
catch (err) {
const error = err;
let message = error.message;
if (error instanceof error_1.default) {
if (error.errorId && error.errorId === 'JAVACONFIG-3') {
message = `You are trying to pull a function of a higher stack version[${fn.stack}]. Please provide a valid java binary path for the config key ${fn.stack}.bin to pull function[${fn.name}].`;
}
}
throbber.remove('function_pull_' + fn.name);
(0, logger_1.warning)(`Skipping pull of function(${fn.name}). ${message}`);
fn.failure_reason = `there was an error while pulling function [${fn.name}]. ${message}`;
isFnPulledFailed = true;
}
throbber.remove('function_pull_' + fn.name);
return fn;
})));
targets = targets.filter((target) => {
var _a, _b, _c;
if (!target.valid &&
!((_a = target.failure_reason) === null || _a === void 0 ? void 0 : _a.startsWith('unable to locate python')) &&
!((_b = target.failure_reason) === null || _b === void 0 ? void 0 : _b.includes('You are trying to pull a function of a higher stack version'))) {
(0, logger_1.debug)('Invalid target : ' + target.name + ' reason : ' + target.failure_reason);
(0, logger_1.warning)(`skipping pull of function(${target.name}) since the package is invalid. \nContact catalyst support with debug log.`);
new error_1.default('invalid package: ' + target.name, { exit: 2 });
}
else if (!target.valid && ((_c = target.failure_reason) === null || _c === void 0 ? void 0 : _c.startsWith('unable to locate python'))) {
(0, logger_1.warning)(`skipping pull of function(${target.name}) since ${target.failure_reason}`);
}
if (target.compilationError) {
target.compilationError.forEach((error) => {
console.log(`${(0, ansi_colors_1.red)(char_1.CHAR.error)} Error while compiling function[${target.name}]`);
console.log(error);
});
}
if (target.compilationWarning) {
target.compilationWarning.forEach((warn) => {
console.warn(`${(0, ansi_colors_1.yellow)(char_1.CHAR.warning)} Warning while compiling function[${target.name}]`);
console.warn(warn);
});
}
return target.valid;
});
if (isFnPulled) {
runtime_store_1.default.set('payload.functions.targets', targets);
runtime_store_1.default.set('payload.functions.source', fnDirName);
if (isFnPulledFailed) {
runtime_store_1.default.set('payload.functions.status', 1);
}
else {
runtime_store_1.default.set('payload.functions.status', 2);
}
}
});