UNPKG

@crestron/ch5-shell-utilities-cli

Version:
379 lines (378 loc) 21.9 kB
"use strict"; // Copyright (C) 2021 to the present, Crestron Electronics, Inc. // All rights reserved. // No part of this software may be reproduced in any form, machine // or natural, without the express written consent of Crestron Electronics. // Use of this source code is subject to the terms of the Crestron Software License Agreement // under which you licensed this source code. var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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 __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Ch5ExportAllCli = void 0; var Ch5BaseClassForCli_1 = require("../Ch5BaseClassForCli"); var path_1 = __importDefault(require("path")); var fs_1 = __importDefault(require("fs")); var fsExtra = require("fs-extra"); var zl = require("zip-lib"); var findRemoveSync = require('find-remove'); var Ch5ExportAllCli = /** @class */ (function (_super) { __extends(Ch5ExportAllCli, _super); /* - "requiredFolderPath": "./app/project/" - This indicates the folder path of the project files. - "outputFileName": "exported-all.zip" - This indicates the output zip file name. - "outputTempFolderName": "Exported-All-Code-Folder-Temp" - This indicates the temporary path created for copying output files. - "zipFolderName": "exported-all", - This is the name of the folder inside outputTempFolderName where the zip file will be created. - "zipFileDestinationPath": "./dist/", - This is the path where the zip file will be created. Ensure that it starts with './' and ends with '/'. - "ignoreFilesFolders": Indicates all the files / folders that must not be included in the zip file. */ /** * Constructor */ function Ch5ExportAllCli(showOutputMessages) { if (showOutputMessages === void 0) { showOutputMessages = true; } var _this = _super.call(this, "export-all") || this; _this.showOutputMessages = showOutputMessages; _this.outputResponse = { result: false }; _this.finalOutputZipFile = ""; return _this; } /** * Method for exporting all */ Ch5ExportAllCli.prototype.run = function () { return __awaiter(this, void 0, void 0, function () { var inputNames, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 10, , 11]); this.outputResponse = { result: false }; this.checkVersionToExecute(); this.finalOutputZipFile = path_1.default.join(this.getConfigNode("zipFileDestinationPath"), this.getConfigNode("outputFileName")); if (!(this.inputArguments["all"] === true)) return [3 /*break*/, 6]; if (!fs_1.default.existsSync(this.getConfigNode("requiredFolderPath"))) return [3 /*break*/, 4]; if (!(fs_1.default.readdirSync(this.getConfigNode("requiredFolderPath")).length > 0)) return [3 /*break*/, 2]; return [4 /*yield*/, this.copyAndZipFiles([], true)]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: this.outputResponse['result'] = false; this.outputResponse['errorMessage'] = this.getText("FAILURE_MESSAGE_NO_FILES_IN_DIR"); this.logFinalResponses(); _a.label = 3; case 3: return [3 /*break*/, 5]; case 4: this.outputResponse['result'] = false; this.outputResponse['errorMessage'] = this.getText("FAILURE_MESSAGE_NO_DIR"); this.logFinalResponses(); _a.label = 5; case 5: return [3 /*break*/, 9]; case 6: inputNames = this.inputArguments["list"]; this.logger.log("inputNames", inputNames); if (!(inputNames && inputNames.length > 0)) return [3 /*break*/, 8]; return [4 /*yield*/, this.copyAndZipFiles(inputNames, false)]; case 7: _a.sent(); return [3 /*break*/, 9]; case 8: this.outputResponse['result'] = false; this.outputResponse['errorMessage'] = this.getText("FAILURE_MESSAGE_INPUT_PARAMS_EMPTY_IN_REQUEST"); this.logFinalResponses(); _a.label = 9; case 9: return [3 /*break*/, 11]; case 10: e_1 = _a.sent(); if (e_1 && this.utils.isValidInput(e_1.message)) { this.outputResponse.errorMessage = e_1.message; } else { this.outputResponse.errorMessage = this.getText("ERRORS.SOMETHING_WENT_WRONG"); this.logger.log(e_1); } this.logFinalResponses(); return [3 /*break*/, 11]; case 11: return [2 /*return*/, this.outputResponse['result']]; } }); }); }; /** * Log Final Response Message */ Ch5ExportAllCli.prototype.logFinalResponses = function () { if (this.showOutputMessages === true) { if (this.utils.isValidInput(this.outputResponse['errorMessage'])) { this.logger.printError(this.outputResponse['errorMessage']); } else { if (this.outputResponse['result'] === true) { if (this.outputResponse['copyAll'] === true) { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_ALL", this.finalOutputZipFile)); } else { if (this.outputResponse['invalidInputs'].length > 0) { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_SPECIFIC_WITH_ERROR", this.finalOutputZipFile, this.utils.convertArrayToString(this.outputResponse['validInputs'], ", "), this.utils.convertArrayToString(this.outputResponse['invalidInputs'], ", "))); } else { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_SPECIFIC", this.finalOutputZipFile, this.utils.convertArrayToString(this.outputResponse['validInputs'], ", "))); } } } else { this.logger.printError(this.outputResponse['errorMessage']); } } } }; /** * Identify the exported components and create a sample project-config.json file internally to this export. * @param copyAll * @param validInputs * @returns */ Ch5ExportAllCli.prototype.processProjectConfigJSONFile = function (copyAll, validInputs) { var allPages = this.projectConfig.getAllPages() || []; var allWidgets = this.projectConfig.getAllWidgets() || []; var outputJSON = {}; if (copyAll === true) { outputJSON.pages = allPages; outputJSON.widgets = allWidgets; } else { var allPagesNew = []; var allWidgetsNew = []; var _loop_1 = function (i) { var pageObject = allPages.find(function (tempObj) { return path_1.default.resolve(path_1.default.join(tempObj.fullPath, tempObj.fileName)).trim().toLowerCase() === path_1.default.resolve(validInputs[i]).trim().toLowerCase(); }); if (pageObject) { allPagesNew.push(pageObject); } else { var widgetObject = allWidgets.find(function (tempObj) { return path_1.default.resolve(path_1.default.join(tempObj.fullPath, tempObj.fileName)).trim().toLowerCase() === path_1.default.resolve(validInputs[i]).trim().toLowerCase(); }); if (widgetObject) { allWidgetsNew.push(widgetObject); } else { //ERROR - MIGHT NOT HAPPEN } } }; for (var i = 0; i < validInputs.length; i++) { _loop_1(i); } outputJSON.pages = allPagesNew; outputJSON.widgets = allWidgetsNew; } this.logger.log("outputJSON", JSON.stringify(outputJSON)); return outputJSON; }; /** * Get folderPath from project-config.json file. * @param {string} htmlFileName */ Ch5ExportAllCli.prototype.getFolderPathFromProjectConfigJSON = function (htmlFileName) { var allPages = this.projectConfig.getAllPages() || []; var allWidgets = this.projectConfig.getAllWidgets() || []; var pageObject = allPages.find(function (tempObj) { return path_1.default.join(path_1.default.normalize(tempObj.fullPath), path_1.default.normalize(tempObj.fileName)).trim().toLowerCase() === path_1.default.normalize(htmlFileName).trim().toLowerCase(); }); if (pageObject) { return pageObject.fullPath; } else { var widgetObject = allWidgets.find(function (tempObj) { return path_1.default.join(path_1.default.normalize(tempObj.fullPath), path_1.default.normalize(tempObj.fileName)).trim().toLowerCase() === path_1.default.normalize(htmlFileName).trim().toLowerCase(); }); if (widgetObject) { return widgetObject.fullPath; } else { //This will not happen } } }; /** * Copy and Zip files * @param {*} inputNames * @param {*} copyAll */ Ch5ExportAllCli.prototype.copyAndZipFiles = function (inputNames, copyAll) { return __awaiter(this, void 0, void 0, function () { var invalidInputs, validInputs, temporaryFolderPath, i, checkFileOrFolder, removedFiles, e_2; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: invalidInputs = []; validInputs = []; this.outputResponse['copyAll'] = copyAll; this.logger.log(" Complete File Name: " + this.finalOutputZipFile); return [4 /*yield*/, this.utils.deleteFile(this.finalOutputZipFile)]; case 1: _a.sent(); temporaryFolderPath = path_1.default.join(this.getConfigNode("zipFileDestinationPath"), this.getConfigNode("outputTempFolderName")); _a.label = 2; case 2: _a.trys.push([2, 6, , 7]); this.utils.deleteFolder(temporaryFolderPath); //Create Temporary Folder for copy files before zipping fs_1.default.mkdirSync(temporaryFolderPath, { recursive: true, }); this.logger.log(" Temp Folder Path Created: " + temporaryFolderPath); if (copyAll === true) { fsExtra.copySync(this.getConfigNode("requiredFolderPath"), path_1.default.join(temporaryFolderPath, this.getConfigNode("zipFolderName"), path_1.default.normalize(this.getConfigNode("requiredFolderPath"))), { recursive: true }); } else { for (i = 0; i < inputNames.length; i++) { if (path_1.default.normalize(inputNames[i]).indexOf(path_1.default.normalize(this.getConfigNode("requiredFolderPath"))) >= 0) { if (fs_1.default.existsSync(inputNames[i])) { checkFileOrFolder = fs_1.default.statSync(inputNames[i]); if (checkFileOrFolder && checkFileOrFolder.isFile()) { if (validInputs.indexOf(inputNames[i]) === -1) { validInputs.push(inputNames[i]); if (inputNames[i].toLowerCase().indexOf("project/components/pages/") >= 0) { fsExtra.copySync(this.getFolderPathFromProjectConfigJSON(inputNames[i]), path_1.default.join(temporaryFolderPath, this.getConfigNode("zipFolderName"), this.getFolderPathFromProjectConfigJSON(path_1.default.normalize(inputNames[i]))), { recursive: true }); } else { fsExtra.copySync(inputNames[i], path_1.default.join(temporaryFolderPath, this.getConfigNode("zipFolderName"), path_1.default.normalize(inputNames[i])), { recursive: true }); } } } else { if (invalidInputs.indexOf(inputNames[i]) === -1) { invalidInputs.push(inputNames[i]); } } } else { if (invalidInputs.indexOf(inputNames[i]) === -1) { invalidInputs.push(inputNames[i]); } } } else { if (invalidInputs.indexOf(inputNames[i]) === -1) { invalidInputs.push(inputNames[i]); } } } } this.outputResponse['validInputs'] = validInputs; this.outputResponse['invalidInputs'] = invalidInputs; this.logger.info("Copy Done."); if (!(copyAll === true || validInputs.length > 0)) return [3 /*break*/, 4]; removedFiles = findRemoveSync(temporaryFolderPath, { extensions: this.getConfigNode("ignoreFilesFolders"), files: this.getConfigNode("ignoreFilesFolders") }); this.logger.log("RemovedFiles", removedFiles); if (copyAll === true) { fsExtra.writeJsonSync(path_1.default.join(temporaryFolderPath, this.getConfigNode("zipFolderName"), "app", "project-config.json"), this.processProjectConfigJSONFile(copyAll, [])); } else if (validInputs.length > 0) { fsExtra.writeJsonSync(path_1.default.join(temporaryFolderPath, this.getConfigNode("zipFolderName"), "app", "project-config.json"), this.processProjectConfigJSONFile(copyAll, validInputs)); } this.logger.info(" project-config.json file created."); return [4 /*yield*/, zl.archiveFolder(temporaryFolderPath, this.finalOutputZipFile).then(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { this.logger.info("Zip Done."); try { this.utils.deleteFolder(temporaryFolderPath); this.logger.info("Clean up Done."); this.outputResponse['result'] = true; this.outputResponse['errorMessage'] = ""; this.logFinalResponses(); } catch (e) { this.outputResponse['result'] = false; this.outputResponse['errorMessage'] = e; this.logFinalResponses(); } return [2 /*return*/]; }); }); }, function (err) { _this.outputResponse['result'] = false; _this.outputResponse['errorMessage'] = err; _this.logFinalResponses(); })]; case 3: _a.sent(); return [3 /*break*/, 5]; case 4: this.outputResponse['result'] = false; this.utils.deleteFolder(temporaryFolderPath); if (validInputs.length === 0) { this.outputResponse['errorMessage'] = this.getText("FAILURE_MESSAGE_NO_VALID_INPUTS"); } else { this.outputResponse['errorMessage'] = this.getText("FAILURE_MESSAGE_NO_VALID_FILES_IN_DIR"); } this.logFinalResponses(); _a.label = 5; case 5: return [3 /*break*/, 7]; case 6: e_2 = _a.sent(); this.outputResponse['result'] = false; this.utils.deleteFolder(temporaryFolderPath); this.outputResponse['errorMessage'] = e_2; this.logFinalResponses(); return [3 /*break*/, 7]; case 7: return [2 /*return*/]; } }); }); }; return Ch5ExportAllCli; }(Ch5BaseClassForCli_1.Ch5BaseClassForCli)); exports.Ch5ExportAllCli = Ch5ExportAllCli;