zcatalyst-cli
Version:
Command Line Tool for CATALYST
275 lines (274 loc) • 13.6 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 });
exports.executeHook = void 0;
const ansi_colors_1 = require("ansi-colors");
const path_1 = require("path");
const appsail_utils_1 = require("../../../appsail-utils");
const archiver_1 = __importDefault(require("../../../archiver"));
const endpoints_1 = require("../../../endpoints");
const error_1 = __importDefault(require("../../../error"));
const execute_script_1 = require("../../../execute-script");
const common_1 = require("../../../init/util/common");
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 logger_1 = require("../../../util_modules/logger");
const option_1 = require("../../../util_modules/option");
const project_1 = require("../../../util_modules/project");
const utils_1 = require("./utils");
const throbber_1 = __importDefault(require("../../../throbber"));
const minimatch_1 = __importDefault(require("minimatch"));
function executeHook(script, name, moduleSource) {
if ((0, option_1.getOptionValue)('ignoreScripts', false)) {
(0, logger_1.debug)(`skipping ${name} hook`);
return;
}
(0, execute_script_1.executeCommand)(script, { moduleSource, feature: name });
}
exports.executeHook = executeHook;
function getConfigJsonInputs() {
return __awaiter(this, void 0, void 0, function* () {
const runtimeDetailsPromise = (0, common_1.getRuntimeDetails)();
const stack = yield (0, utils_1.validateOptions)(utils_1.validateStack, 'stack', runtimeDetailsPromise);
const platform = yield (0, utils_1.validateOptions)(utils_1.validatePlatform, 'platform', stack);
const optValues = {
build_path: yield (0, utils_1.validateOptions)(utils_1.validateBuildPath, 'buildPath'),
stack,
platform,
command: (0, option_1.getOptionValue)('command', false)
};
const cwd = runtime_store_1.default.get('cwd');
yield prompt_1.default.register('file-path');
const appConfigAns = yield prompt_1.default.ask(prompt_1.default.question('buildPath', 'Please provide the build directory of your AppSail service', {
type: 'file-path',
when: () => optValues.build_path === false,
rootPath: cwd,
validate: ({ value }) => __awaiter(this, void 0, void 0, function* () {
const pathRes = yield (0, utils_1.validateBuildPath)(value);
if (!pathRes) {
return `Invalid path: ${value}`;
}
return true;
})
}), prompt_1.default.question('stack', 'Please select the stack for your AppSail service', {
type: 'list',
choices: yield (0, common_1.getRuntimeChoices)({ runtimeDetails: yield runtimeDetailsPromise }),
when: () => optValues.stack === false
}), prompt_1.default.question('platform', 'Please choose a platform for your AppSail: ', {
type: 'list',
choices: [
prompt_1.default.choice('JavaSE', {
value: 'javase',
short: 'JavaSE'
}),
prompt_1.default.choice('JavaWAR', {
value: 'war',
short: 'JavaWAR'
})
],
when: (answers) => {
var _a;
const _stack = ((_a = answers.stack) === null || _a === void 0 ? void 0 : _a.lang) ||
(typeof optValues.stack === 'boolean' ? '' : optValues.stack.lang) ||
'';
return (optValues.platform === false &&
_stack.startsWith(constants_1.RUNTIME.language.java.value));
}
}), prompt_1.default.question('command', 'Please specify the command to start the AppSail service', {
type: 'input',
when: (answers) => {
var _a;
const stack = ((_a = answers.stack) === null || _a === void 0 ? void 0 : _a.lang) ||
(typeof optValues.stack === 'boolean' ? '' : optValues.stack.lang) ||
'';
const _platform = answers.platform || optValues.platform || '';
return (optValues.command === false &&
!(stack.startsWith(constants_1.RUNTIME.language.java.value) &&
_platform === 'war'));
}
}));
const finalConfig = Object.entries(optValues).reduce((config, [key, val]) => {
config[key] = val === false ? appConfigAns[key] : val;
return config;
}, {});
if (typeof finalConfig.stack !== 'string') {
finalConfig.stack = finalConfig.stack.runtime;
}
if (!finalConfig.stack.startsWith(constants_1.RUNTIME.language.java.value) &&
finalConfig.platform) {
(0, logger_1.message)('Platform argument is not supported for stack: ' + finalConfig.stack);
delete finalConfig.platform;
}
if (finalConfig.platform === 'war' && finalConfig.command) {
(0, logger_1.message)('Command argument not need for platform type war');
delete finalConfig.command;
}
return finalConfig;
});
}
function getStandAloneTarget() {
return __awaiter(this, void 0, void 0, function* () {
const isProjectInfo = (0, project_1.getProjectId)(false) || (0, project_1.getProjectName)(false);
if (!isProjectInfo) {
throw new error_1.default('Project info is not present');
}
const cwd = runtime_store_1.default.get('cwd');
const catalystConfigPath = (0, path_1.join)(cwd, constants_1.FILENAME.app_config);
const nameOpt = yield (0, utils_1.validateOptions)(utils_1.validateName, 'name');
const appSailName = yield prompt_1.default.ask(prompt_1.default.question('name', 'Please provide a name for your AppSail service', {
type: 'input',
when: () => nameOpt === false,
validate: (name) => __awaiter(this, void 0, void 0, function* () {
return (yield (0, utils_1.validateName)(name)) !== false
? true
: `AppSail service name is Invalid, it should match ${constants_1.REGEX.functions.package.name}`;
})
}));
const configJson = (yield fs_1.ASYNC.readJSONFile(catalystConfigPath).catch((err) => (0, logger_1.debug)(err))) || (yield getConfigJsonInputs());
if (typeof configJson.stack === 'object') {
configJson.stack = configJson.stack.runtime;
}
return {
name: nameOpt === false ? appSailName.name : nameOpt,
source: cwd,
config: configJson,
validity: { valid: true }
};
});
}
exports.default = (standAlone = false) => __awaiter(void 0, void 0, void 0, function* () {
const targets = standAlone
? (yield config_1.appSailConfig.getAllTargetDetails(false)) || [yield getStandAloneTarget()]
: yield config_1.appSailConfig.getAllTargetDetails();
if (!targets || targets.length === 0) {
throw new error_1.default('No targets found');
}
const filtered = (0, appsail_utils_1.filterTargets)(targets);
let pythonPrompt = false;
const validTargets = (0, appsail_utils_1.validateAppSail)(filtered).filter((targ) => {
var _a;
if (targ.validity.valid) {
if (!pythonPrompt &&
((_a = targ.config) === null || _a === void 0 ? void 0 : _a.stack.startsWith(constants_1.RUNTIME.language.python.value))) {
pythonPrompt = true;
}
return targ;
}
(0, logger_1.labeled)('AppSail: ', 'Invalid AppSail service ' + (0, ansi_colors_1.bold)(targ.name || 'Unknown')).ERROR();
(0, logger_1.error)('Reason: ' + targ.validity.reason);
(0, logger_1.info)();
return false;
});
if (validTargets.length === 0) {
throw new error_1.default('No valid AppSail services found to deploy', {
skipHelp: true
});
}
const sailAPI = yield (0, endpoints_1.appSailAPI)();
const throbber = throbber_1.default.getInstance();
const deployRes = yield validTargets.reduce((result, _targ) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
const targ = _targ.config;
const prevRes = yield result;
const throbberName = `prepare_appsail_${_targ.name}`;
try {
if ((_a = targ.scripts) === null || _a === void 0 ? void 0 : _a.predeploy) {
executeHook(targ.scripts.predeploy, 'predeploy', _targ.source);
}
throbber.add(throbberName, {
text: `Preparing AppSail[${_targ.name}]`
});
const folderPath = targ.build_path;
const isBuildPath = yield fs_1.ASYNC.isPathExists(folderPath);
if (!isBuildPath) {
throw new error_1.default(`the build path doesn't exists: ${folderPath}`, {
exit: 1,
skipHelp: true
});
}
const ignoreFile = yield fs_1.ASYNC.readFile((0, path_1.join)(_targ.source, constants_1.FILENAME.catalyst_ignore));
const excludePatterns = [
'**/.DS_Store',
'**/.vscode/**/*',
`**/${constants_1.FILENAME.log}`,
`**/${constants_1.FILENAME.config}`,
`**/${constants_1.FILENAME.rc}`,
`**/${constants_1.FILENAME.app_config}`,
`**/${constants_1.FILENAME.catalyst_ignore}`,
...((ignoreFile === null || ignoreFile === void 0 ? void 0 : ignoreFile.split('\n')) || [])
];
const folderContents = yield fs_1.ASYNC.walk(folderPath, {
filter: {
exclude: (path) => __awaiter(void 0, void 0, void 0, function* () {
return !!excludePatterns.find((glob) => (0, minimatch_1.default)(path.replace(folderPath + path_1.sep, ''), glob, { dot: true }));
}),
excludeDir: true
}
});
const zip = new archiver_1.default();
folderContents.forEach((content) => {
zip.add(content.path === folderPath
? (0, path_1.basename)(content.path)
: content.path.replace(folderPath + path_1.sep, ''), content.stats.isSymbolicLink()
? fs_1.SYNC.readSymLink(content.path)
: fs_1.SYNC.getReadStream(content.path), { mode: content.stats.mode });
});
const finalized = yield zip.finalize();
const zipStream = yield finalized.fsStream();
throbber.remove(throbberName);
const { stack, command, memory, platform, env_variables, catalyst_auth, login_redirect } = targ;
const apiRes = yield sailAPI.deploy(zipStream.stream, {
stack,
name: _targ.name,
memory,
platform,
command,
catalystAuth: catalyst_auth,
loginRedirect: login_redirect,
envVariables: env_variables,
contentLength: zipStream.length
});
_targ.url = apiRes.url;
if ((_b = targ.scripts) === null || _b === void 0 ? void 0 : _b.postdeploy) {
executeHook(targ.scripts.postdeploy, 'postdeploy', _targ.source);
}
}
catch (err) {
throbber.remove(throbberName);
(0, logger_1.debug)(err);
_targ.validity = {
valid: false,
reason: error_1.default.getErrorInstance(err).message
};
}
prevRes.push(_targ);
return Promise.resolve(prevRes);
}), Promise.resolve([]));
const deployedValidTargets = deployRes.filter((targ) => {
if (!targ.validity.valid) {
(0, logger_1.warning)('Deploy of AppSail [' +
targ.name +
'] was unsuccessful since ' +
targ.validity.reason);
}
return targ.validity.valid;
});
runtime_store_1.default.set('payload.appsail.targets', deployedValidTargets);
if (deployedValidTargets.length > 0) {
runtime_store_1.default.set('payload.appsail.deploy', true);
}
});