UNPKG

@crestron/ch5-shell-utilities-cli

Version:
689 lines (688 loc) 40.4 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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Ch5ImportComponentsCli = void 0; var Ch5BaseClassForCli_1 = require("../Ch5BaseClassForCli"); var fs = require("fs"); var fsExtra = require("fs-extra"); var path = require('path'); var zl = require("zip-lib"); var Enquirer = require('enquirer'); var enquirer = new Enquirer(); var Ch5ImportComponentsCli = /** @class */ (function (_super) { __extends(Ch5ImportComponentsCli, _super); function Ch5ImportComponentsCli(showOutputMessages) { if (showOutputMessages === void 0) { showOutputMessages = true; } var _this = _super.call(this, "import-components") || this; _this.showOutputMessages = showOutputMessages; /* - "requiredFolderPath": "./app/project/components/" - This indicates the folder path of the project asset files. - "outputFileName": "imported-components.zip" - This indicates the output zip file name. - "outputTempFolderName": "Imported-Components-Code-Folder-Temp" - This indicates the temporary path created for copying output files. - "zipFolderName": "imported-components", - 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 '/'. - "exportedFolderName": Indicates the name of the folder that was used for exporting the zip file during export:components process. */ _this.outputResponse = {}; _this.folderPaths = {}; return _this; } /** * Initialize all variables and set module level constants */ Ch5ImportComponentsCli.prototype.initialize = function () { this.outputResponse = { result: false, errorMessage: "", warningMessage: "", data: { overwriteFiles: false, invalidInputFiles: [], inputFileExistsInSourceFolder: [], sourceFilesInTargetFolder: [], newSourceFiles: [], listOfFilesWithOverrideFalse: [], filesToBeAvoidedFromCopying: ['./app/project-config.json'] } }; this.folderPaths = { inputZipFileToImport: this.inputArguments["zipFile"], temporaryLocationForCopiedZipFile: path.join(this.getConfigNode("zipFileDestinationPath"), this.getConfigNode("outputFileName")), temporaryLocationForExtractedFilesFolder: path.join(this.getConfigNode("zipFileDestinationPath"), this.getConfigNode("outputTempFolderName")), temporaryLocationForAllFilesCopyFrom: path.join(this.getConfigNode("zipFileDestinationPath"), this.getConfigNode("outputTempFolderName"), this.getConfigNode("exportedFolderName")), temporaryLocationForProjectConfig: path.join(this.getConfigNode("zipFileDestinationPath"), this.getConfigNode("outputTempFolderName"), this.getConfigNode("exportedFolderName"), path.normalize("app/project-config.json")) }; }; Object.defineProperty(Ch5ImportComponentsCli.prototype, "getZl", { /** * Utils function so that we can mock zl library in our test cases */ get: function () { return zl; }, enumerable: false, configurable: true }); /** * Method for importing components */ Ch5ImportComponentsCli.prototype.run = function () { return __awaiter(this, void 0, void 0, function () { var e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, 5, 6]); this.checkVersionToExecute(); // Initialize this.initialize(); // Verify input params return [4 /*yield*/, this.verifyInputParams()]; case 1: // Verify input params _a.sent(); // Ask details to developer based on input parameter validation return [4 /*yield*/, this.checkPromptQuestions()]; case 2: // Ask details to developer based on input parameter validation _a.sent(); // Update project-config first (so that if this fails, we don't worry about file deletion). Next Delete Files return [4 /*yield*/, this.processRequest()]; case 3: // Update project-config first (so that if this fails, we don't worry about file deletion). Next Delete Files _a.sent(); return [3 /*break*/, 6]; case 4: 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); } return [3 /*break*/, 6]; case 5: // Clean up this.cleanUp(); return [7 /*endfinally*/]; case 6: // Show output response this.logOutput(); return [2 /*return*/, this.outputResponse.result]; // The return is required to validate in automation test case } }); }); }; /** * Verify input parameters */ Ch5ImportComponentsCli.prototype.verifyInputParams = function () { return __awaiter(this, void 0, void 0, function () { var unzip, inputListOfFiles, checkedFilesForLoop, i, fileNewPath, checkFileOrFolder, i, fileNewPath, checkFileOrFolder, i, isExists, j; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.utils.isValidInput(this.inputArguments["zipFile"]) && this.isZipFileValid(this.inputArguments["zipFile"])) { if (this.inputArguments["all"] === false) { if (this.inputArguments["list"].length === 0) { throw new Error(this.getText("FAILURE_MESSAGE_INPUT_PARAMS_EMPTY_IN_REQUEST")); } } } else { throw new Error(this.getText("FAILURE_MESSAGE_INPUT_PARAM_ZIP_FILE_MISSING")); } // Copy zip file from developer input to a temporary location in dist folder. fsExtra.copySync(this.folderPaths.inputZipFileToImport, this.folderPaths.temporaryLocationForCopiedZipFile); unzip = new this.getZl.Unzip({ // Called before an item is extracted. onEntry: function (event) { if (/^__MACOSX\//.test(event.entryName)) { // entry name starts with __MACOSX/ event.preventDefault(); } } }); this.utils.deleteFolder(this.folderPaths.temporaryLocationForExtractedFilesFolder); // Extract the developer input zip file into a temporary location in dist folder. return [4 /*yield*/, unzip.extract(this.folderPaths.temporaryLocationForCopiedZipFile, this.folderPaths.temporaryLocationForExtractedFilesFolder).then(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { this.logger.log("Folder unzipped"); return [2 /*return*/]; }); }); }, function (err) { throw new Error(err); })]; case 1: // Extract the developer input zip file into a temporary location in dist folder. _a.sent(); /* If inputArguments("all") is false Run through all the input files, and check if they exist in the zipped folder to identify Valid, Invalid files If overwrite = true or ForceFlag overwrite: true will ensure that files already existing are overwritten If invalid files is zero Message listing valid files Else Message showing valid and invalid files Else overwrite: false will ensure that files already existing are not overwritten If invalid files is zero Message listing valid files Else Message showing valid and invalid files Else In this case, I am not worried if files are valid or not in the zip file. The zip file is extracted as an output of export, and so the expectation is that the files are valid. If overwrite = true or ForceFlag Generic Message Else Identify the copied files */ // Check if proper folder exists after unzip. // This can happen if user is trying to import assets using exported-components.zip file if (!fs.existsSync(path.normalize(this.folderPaths.temporaryLocationForAllFilesCopyFrom))) { throw new Error(this.getText("FAILURE_MESSAGE_INVALID_ZIP_FILE_EXTRACT")); } inputListOfFiles = []; if (this.inputArguments["all"] === false) { inputListOfFiles = this.inputArguments['list']; } else { inputListOfFiles = this.replaceDistFolderPathNameInInput(this.getAllFiles(path.normalize(this.folderPaths.temporaryLocationForAllFilesCopyFrom))); } this.logger.log("inputListOfFiles", inputListOfFiles); checkedFilesForLoop = []; for (i = 0; i < inputListOfFiles.length; i++) { if (this.checkIfNewFileInput(checkedFilesForLoop, inputListOfFiles[i])) { fileNewPath = path.join(path.normalize(this.folderPaths.temporaryLocationForAllFilesCopyFrom), path.normalize(inputListOfFiles[i])); if (fs.existsSync(fileNewPath)) { checkFileOrFolder = fs.statSync(fileNewPath); if (checkFileOrFolder && checkFileOrFolder.isFile()) { if (!this.isFileToBeAvoided(inputListOfFiles[i])) { this.outputResponse.data.inputFileExistsInSourceFolder.push(inputListOfFiles[i]); } } else { this.outputResponse.data.invalidInputFiles.push(inputListOfFiles[i]); } } else { this.outputResponse.data.invalidInputFiles.push(inputListOfFiles[i]); } } checkedFilesForLoop.push(inputListOfFiles[i]); } // Identify source files in target folder for (i = 0; i < this.outputResponse.data.inputFileExistsInSourceFolder.length; i++) { fileNewPath = path.normalize(this.outputResponse.data.inputFileExistsInSourceFolder[i]); if (fs.existsSync(fileNewPath)) { checkFileOrFolder = fs.statSync(fileNewPath); if (checkFileOrFolder && checkFileOrFolder.isFile()) { if (!this.isFileToBeAvoided(this.outputResponse.data.inputFileExistsInSourceFolder[i])) { this.outputResponse.data.sourceFilesInTargetFolder.push(this.outputResponse.data.inputFileExistsInSourceFolder[i]); } } else { // Not a file, and so we cannot identify this as a valid source file } } else { if (!this.isFileToBeAvoided(this.outputResponse.data.inputFileExistsInSourceFolder[i])) { this.outputResponse.data.newSourceFiles.push(this.outputResponse.data.inputFileExistsInSourceFolder[i]); } } } /* this.outputResponse.data.sourceFilesInTargetFolder [ './app/project/components/pages/page1/page1.html', './app/project/components/pages/page2/page2.html' ] this.outputResponse.data.newSourceFiles [ './app/project/components/widgets/pagedisplay/pagedisplay.htm', './app/project/components/pages/page7/page7.html', './app/project/components/widgets/widget1/widget1.html' ] this.outputResponse.data.invalidInputFiles [ './app/project/components/widgets/pagedisplay/pagedisplay.htm', './app/project/components/pages/page2/' ] this.outputResponse.data.inputFileExistsInSourceFolder [ './app/project/components/pages/page1/page1.html', './app/project/components/pages/page2/page2.html', './app/project/components/pages/page7/page7.html', './app/project/components/widgets/widget1/widget1.html' ] */ for (i = 0; i < this.outputResponse.data.inputFileExistsInSourceFolder.length; i++) { isExists = false; for (j = 0; j < this.outputResponse.data.sourceFilesInTargetFolder.length; j++) { if (this.outputResponse.data.inputFileExistsInSourceFolder[i] === this.outputResponse.data.sourceFilesInTargetFolder[j]) { isExists = true; break; } } if (isExists === false) { this.outputResponse.data.listOfFilesWithOverrideFalse.push(this.outputResponse.data.inputFileExistsInSourceFolder[i]); } } this.logger.log("this.outputResponse.data.sourceFilesInTargetFolder", this.outputResponse.data.sourceFilesInTargetFolder); this.logger.log("this.outputResponse.data.newSourceFiles", this.outputResponse.data.newSourceFiles); this.logger.log("this.outputResponse.data.invalidInputFiles", this.outputResponse.data.invalidInputFiles); this.logger.log("this.outputResponse.data.inputFileExistsInSourceFolder", this.outputResponse.data.inputFileExistsInSourceFolder); this.logger.log("this.outputResponse.data.listOfFilesWithOverrideFalse", this.outputResponse.data.listOfFilesWithOverrideFalse); if (this.outputResponse.data.inputFileExistsInSourceFolder.length === 0) { throw new Error(this.getText("FAILURE_MESSAGE_INPUT_PARAMS_INVALID_IN_REQUEST", this.folderPaths.inputZipFileToImport, this.utils.convertArrayToString(this.inputArguments["list"], "\n"))); } return [2 /*return*/]; } }); }); }; /** * * @param {*} fileName */ Ch5ImportComponentsCli.prototype.isFileToBeAvoided = function (fileName) { for (var i = 0; i < this.outputResponse.data.filesToBeAvoidedFromCopying.length; i++) { if (path.normalize(this.outputResponse.data.filesToBeAvoidedFromCopying[i]).trim().toLowerCase() === path.normalize(fileName).trim().toLowerCase()) { return true; } } return false; }; /** * * @param {*} input */ Ch5ImportComponentsCli.prototype.replaceDistFolderPathNameInInput = function (input) { if (input && input.length > 0) { var output = []; for (var i = 0; i < input.length; i++) { output.push(input[i].replace(this.folderPaths.temporaryLocationForAllFilesCopyFrom, ".")); } return output; } else { return []; } }; /** * * @param {*} sourcePath */ Ch5ImportComponentsCli.prototype.getAllFiles = function (sourcePath) { var _this = this; return fs.readdirSync(sourcePath).reduce(function (files, file) { var name = path.join(sourcePath, file); var isDirectory = fs.statSync(name).isDirectory(); return isDirectory ? __spreadArray(__spreadArray([], files, true), _this.getAllFiles(name), true) : __spreadArray(__spreadArray([], files, true), [name], false); }, []); }; /** * Check if there are questions to be prompted to the developer */ Ch5ImportComponentsCli.prototype.checkPromptQuestions = function () { return __awaiter(this, void 0, void 0, function () { var messageText, newSourceText, existingFilesText, invalidFilesText, i, i, i, questionsArray, response; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(this.inputArguments["force"] === true)) return [3 /*break*/, 1]; this.outputResponse.data.overwriteFiles = true; return [3 /*break*/, 3]; case 1: messageText = ""; newSourceText = ""; existingFilesText = ""; invalidFilesText = ""; if (this.outputResponse.data.newSourceFiles && this.outputResponse.data.newSourceFiles.length > 0) { for (i = 0; i < this.outputResponse.data.newSourceFiles.length; i++) { newSourceText += this.outputResponse.data.newSourceFiles[i] + "\n"; } newSourceText = this.getText("VALIDATIONS.NEW_FILES_TO_BE_IMPORTED") + "\n" + newSourceText + "\n"; } else { newSourceText = this.getText("VALIDATIONS.NO_NEW_FILES_AVAILABLE_TO_BE_IMPORTED") + "\n\n"; } if (this.outputResponse.data.invalidInputFiles && this.outputResponse.data.invalidInputFiles.length > 0) { for (i = 0; i < this.outputResponse.data.invalidInputFiles.length; i++) { invalidFilesText += this.outputResponse.data.invalidInputFiles[i] + "\n"; } invalidFilesText = this.getText("VALIDATIONS.INVALID_FILES_IN_IMPORT_LIST") + "\n" + invalidFilesText + "\n"; } if (this.outputResponse.data.sourceFilesInTargetFolder && this.outputResponse.data.sourceFilesInTargetFolder.length > 0) { for (i = 0; i < this.outputResponse.data.sourceFilesInTargetFolder.length; i++) { existingFilesText += this.outputResponse.data.sourceFilesInTargetFolder[i] + "\n"; } existingFilesText = this.getText("VALIDATIONS.EXISTING_FILES_IN_IMPORT_FOLDER") + "\n" + existingFilesText + "\n"; } existingFilesText += this.getText("VALIDATIONS.OVERWRITE_FILES"); messageText = newSourceText + invalidFilesText + existingFilesText; questionsArray = [ { type: 'select', name: 'overwriteFile', message: messageText, choices: [ { message: this.getText("VALIDATIONS.OVERWRITE_FILES_YES"), hint: this.getText("VALIDATIONS.OVERWRITE_FILES_HINT_YES"), value: 'Y' }, { message: this.getText("VALIDATIONS.OVERWRITE_FILES_NO"), hint: this.getText("VALIDATIONS.OVERWRITE_FILES_HINT_NO"), value: 'N' } ], initial: 0 } ]; return [4 /*yield*/, enquirer.prompt(questionsArray).then(function (response) { _this.logger.log(response); return response.overwriteFile; }).catch(function (err) { throw new Error(_this.getText("ERRORS.PROGRAM_STOPPED_OR_UNKNOWN_ERROR")); })]; case 2: response = _a.sent(); this.outputResponse.data.overwriteFiles = this.utils.convertStringToBoolean(response); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; /** * Implement this component's main purpose * Unzip the export-components.zip file, copy files as per user input in command-terminal from source (extracted export-components.zip file) to destination (./ project folder). */ Ch5ImportComponentsCli.prototype.processRequest = function () { return __awaiter(this, void 0, void 0, function () { var pagesSelected, widgetsSelected, i, fromPath, toPath; return __generator(this, function (_a) { switch (_a.label) { case 0: this.logger.log("this.outputResponse.data.overwriteFiles", this.outputResponse.data.overwriteFiles); pagesSelected = []; widgetsSelected = []; if (this.inputArguments["all"] === true) { fsExtra.copySync(this.folderPaths.temporaryLocationForAllFilesCopyFrom, "./", { overwrite: this.outputResponse.data.overwriteFiles, filter: function (file) { if (path.basename(file).toLowerCase() === "project-config.json") { return false; } else { return true; } } }); } else { for (i = 0; i < this.outputResponse.data.inputFileExistsInSourceFolder.length; i++) { this.logger.log("this.folderPaths.temporaryLocationForAllFilesCopyFrom", this.folderPaths.temporaryLocationForAllFilesCopyFrom); this.logger.log("this.outputResponse.data.inputFileExistsInSourceFolder[i]", this.outputResponse.data.inputFileExistsInSourceFolder[i]); fromPath = path.normalize(path.dirname(path.join(this.folderPaths.temporaryLocationForAllFilesCopyFrom, path.normalize(this.outputResponse.data.inputFileExistsInSourceFolder[i])))); toPath = path.normalize(path.dirname(path.normalize(this.outputResponse.data.inputFileExistsInSourceFolder[i]))); fsExtra.copySync(fromPath, toPath, { recursive: true, overwrite: this.outputResponse.data.overwriteFiles, filter: function (file) { if (path.basename(file).toLowerCase() === "project-config.json") { return false; } else { return true; } } }); if (fromPath.indexOf(path.normalize("components/pages")) >= 0) { pagesSelected.push(path.basename(path.normalize(this.outputResponse.data.inputFileExistsInSourceFolder[i]))); } else { widgetsSelected.push(path.basename(path.normalize(this.outputResponse.data.inputFileExistsInSourceFolder[i]))); } } } return [4 /*yield*/, this.processExportedProjectConfigJSON(pagesSelected, widgetsSelected)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Log Final Response Message */ Ch5ImportComponentsCli.prototype.logOutput = function () { if (this.showOutputMessages === true) { this.logger.log("this.outputResponse", JSON.stringify(this.outputResponse)); if (this.utils.isValidInput(this.outputResponse.errorMessage)) { this.logger.printError(this.outputResponse.errorMessage); } else { if (this.outputResponse.result === true) { /* If inputArguments("all") is false If overwrite = true If invalid files is zero Message listing valid files Else Message showing valid and invalid files Else If invalid files is zero Message listing valid files Else Message showing valid and invalid files Else If overwrite = true Generic Message Else Identify the copied files */ if (this.inputArguments["all"] === true) { if (this.outputResponse.data.overwriteFiles === true) { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_ALL")); } else { if (this.outputResponse.data.listOfFilesWithOverrideFalse.length === 0) { this.logger.printError(this.getText("FAILURE_MESSAGE_NO_VALID_OVERWRITE_FILES")); } else { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_SPECIFIC", this.utils.convertArrayToString(this.outputResponse.data.listOfFilesWithOverrideFalse, "\n"))); } } } else { if (this.outputResponse.data.overwriteFiles === true) { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_SPECIFIC", this.utils.convertArrayToString(this.outputResponse.data.inputFileExistsInSourceFolder, "\n"))); } else { if (this.outputResponse.data.listOfFilesWithOverrideFalse.length === 0) { this.logger.printError(this.getText("FAILURE_MESSAGE_NO_VALID_OVERWRITE_FILES")); } else { if (this.outputResponse.data.invalidInputFiles.length > 0) { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_SPECIFIC_WITH_ERROR", this.utils.convertArrayToString(this.outputResponse.data.listOfFilesWithOverrideFalse, "\n"), this.utils.convertArrayToString(this.outputResponse.data.sourceFilesInTargetFolder, "\n"), this.utils.convertArrayToString(this.outputResponse.data.invalidInputFiles, "\n"))); } else { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_SPECIFIC", this.utils.convertArrayToString(this.outputResponse.data.listOfFilesWithOverrideFalse, "\n"))); } } } } } else { this.logger.printError(this.outputResponse.errorMessage); } } } }; /** * Clean up method */ Ch5ImportComponentsCli.prototype.cleanUp = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: // Delete the copied zip file from temp folder return [4 /*yield*/, this.utils.deleteFile(this.folderPaths.temporaryLocationForCopiedZipFile)]; case 1: // Delete the copied zip file from temp folder _a.sent(); return [4 /*yield*/, this.utils.deleteFolder(this.folderPaths.temporaryLocationForExtractedFilesFolder)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** * * @param {*} arrayOfFiles * @param {*} newFile */ Ch5ImportComponentsCli.prototype.checkIfNewFileInput = function (arrayOfFiles, newFile) { var outputObj = arrayOfFiles.find(function (tempObj) { return path.normalize(tempObj).trim().toLowerCase() === path.normalize(newFile).trim().toLowerCase(); }); if (outputObj) { return false; } return true; }; /** * Check if the file is a zip file and exists, and follows proper folder structure * Suggestion - Export and import should have version number * Note that we are not checking for export-components.zip file as filename because the * user can rename his file if required. * @param {*} fileName */ Ch5ImportComponentsCli.prototype.isZipFileValid = function (fileName) { if (fs.existsSync(fileName)) { var checkFileOrFolder = fs.statSync(fileName); if (checkFileOrFolder && checkFileOrFolder.isFile()) { if (path.extname(fileName).trim().toLowerCase() === ".zip") { return true; } else { return false; } } else { return false; } } else { return false; } }; /** * For 'page' type components without conflicting name * - The target project content view should be appended with the imported pages in the same order they were in the source project. * - If the navigation buttons were defined in source project, the target project navigation buttons should be appended with buttons for imported page in same order they were in the source project. * For 'page' type components with conflicting name * - the location in the content view of the imported page should remain the same as before the import * - if navigation buttons were defined in both the source and target project, the order should remain the same * - if navigation button was defined in source project, but not the target project, an imported navigation button should be appended to end of navigation buttons * - if navigation button was not defined in source project, but was defined in target project, the target project button should be removed. */ Ch5ImportComponentsCli.prototype.processExportedProjectConfigJSON = function (selectedPages, selectedWidgets) { return __awaiter(this, void 0, void 0, function () { var jsonToBeImported, jsonToBeImported, pageArray, _loop_1, i, pageArray, _loop_2, i; return __generator(this, function (_a) { if (this.inputArguments["all"] === true) { jsonToBeImported = fsExtra.readJSONSync(path.resolve(this.folderPaths.temporaryLocationForProjectConfig)); this.logger.log("jsonToBeImported", jsonToBeImported); this.projectConfig.addPagesToJSON(jsonToBeImported.pages); this.projectConfig.addWidgetsToJSON(jsonToBeImported.widgets); } else { jsonToBeImported = fsExtra.readJSONSync(path.resolve(this.folderPaths.temporaryLocationForProjectConfig)); this.logger.log("jsonToBeImported", jsonToBeImported); if (selectedPages.length > 0) { pageArray = []; _loop_1 = function (i) { pageArray.push(jsonToBeImported.pages.find(function (tempObj) { return tempObj.fileName.trim().toLowerCase() === selectedPages[i].trim().toLowerCase(); })); }; for (i = 0; i < selectedPages.length; i++) { _loop_1(i); } if (pageArray.length > 0) { this.projectConfig.addPagesToJSON(pageArray); } } if (selectedWidgets.length > 0) { pageArray = []; _loop_2 = function (i) { pageArray.push(jsonToBeImported.widgets.find(function (tempObj) { return tempObj.fileName.trim().toLowerCase() === selectedWidgets[i].trim().toLowerCase(); })); }; for (i = 0; i < selectedWidgets.length; i++) { _loop_2(i); } if (pageArray.length > 0) { this.projectConfig.addWidgetsToJSON(pageArray); } } } this.logger.log("project-config read done"); this.outputResponse.result = true; return [2 /*return*/]; }); }); }; return Ch5ImportComponentsCli; }(Ch5BaseClassForCli_1.Ch5BaseClassForCli)); exports.Ch5ImportComponentsCli = Ch5ImportComponentsCli;