@broadcom/endevor-bridge-for-git-for-zowe-cli
Version:
Endevor Bridge for Git plug-in for Zowe CLI
248 lines • 11.5 kB
JavaScript
;
/*
* Copyright (c) 2019 Broadcom. All Rights Reserved. The term
* "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
*
* This software and all information contained therein is
* confidential and proprietary and shall not be duplicated,
* used, disclosed, or disseminated in any way except as
* authorized by the applicable license agreement, without the
* express written permission of Broadcom. All authorized
* reproductions must be marked with this language.
*
* EXCEPT AS SET FORTH IN THE APPLICABLE LICENSE AGREEMENT, TO
* THE EXTENT PERMITTED BY APPLICABLE LAW, BROADCOM PROVIDES THIS
* SOFTWARE WITHOUT WARRANTY OF ANY KIND, INCLUDING WITHOUT
* LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL BROADCOM
* BE LIABLE TO THE END USER OR ANY THIRD PARTY FOR ANY LOSS OR
* DAMAGE, DIRECT OR INDIRECT, FROM THE USE OF THIS SOFTWARE,
* INCLUDING WITHOUT LIMITATION, LOST PROFITS, BUSINESS
* INTERRUPTION, GOODWILL, OR LOST DATA, EVEN IF BROADCOM IS
* EXPRESSLY ADVISED OF SUCH LOSS OR DAMAGE.
*/
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuildUtils = void 0;
const imperative_1 = require("@zowe/imperative");
const object_1 = require("../../utils/object");
const api_1 = require("@broadcom/endevor-for-zowe-cli/lib/api");
const EndevorService_1 = require("../service/EndevorService");
const EBGConstants_1 = require("../constants/EBGConstants");
const MappingMetadata_1 = require("./MappingMetadata");
const fs = require("fs");
const path = require("path");
/**
*
* @export
* @class BuildUtils
*/
class BuildUtils {
static readJSONFileAsObject(filePath, filename) {
try {
imperative_1.Logger.getAppLogger().trace(`BuildUtils - Read: ${filePath}`);
const file = fs.readFileSync(filePath, "utf8"); // read with default encoding
imperative_1.Logger.getAppLogger().trace(`BuildUtils - Get ${filename} file content: \n${file}`);
return JSON.parse(file);
}
catch (err) {
throw new imperative_1.ImperativeError({
msg: `${filePath} does not contain a valid ${filename} file. Error ${err}`,
});
}
}
/**
* Reads the work areas file (last version takes precedence)
* @param gitLocation
*/
static getWorkAreasFromFile(gitLocation) {
let workAreas;
let workAreasPath = EBGConstants_1.EBGConstants.getWorkAreasFilePathV2(gitLocation);
let filename = EBGConstants_1.EBGConstants.WORK_AREAS_FILENAME_V2;
if (!fs.existsSync(workAreasPath)) {
if (fs.existsSync(EBGConstants_1.EBGConstants.getWorkAreasFilePath(gitLocation))) {
workAreasPath = EBGConstants_1.EBGConstants.getWorkAreasFilePath(gitLocation);
filename = EBGConstants_1.EBGConstants.WORK_AREAS_FILENAME;
}
else {
throw new imperative_1.ImperativeError({
msg: `${gitLocation} does not contain a valid ${EBGConstants_1.EBGConstants.WORK_AREAS_FILENAME} or
a valid ${EBGConstants_1.EBGConstants.WORK_AREAS_FILENAME_V2} file.`,
});
}
}
workAreas = this.readJSONFileAsObject(workAreasPath, filename);
if ((0, object_1.isNil)(workAreas.workAreas) || workAreas.workAreas.length === 0) {
throw new imperative_1.ImperativeError({
msg: `No work area specified in a ${filename} file`,
});
}
return workAreas.workAreas;
}
static getWorkAreaByIDFromWorkAreas(workAreas, workAreaId) {
if ((0, object_1.isNil)(workAreas) || workAreas.length === 0) {
throw new imperative_1.ImperativeError({
msg: `No work area definition found`,
});
}
const foundWorkArea = workAreas.find(workArea => workAreaId === workArea.id);
if ((0, object_1.isNil)(foundWorkArea)) {
throw new imperative_1.ImperativeError({
msg: `No work area found with id '${workAreaId}'`,
});
}
else {
return foundWorkArea;
}
}
static getWorkAreaByIDFromFile(gitLocation, workAreaID) {
const workAreas = BuildUtils.getWorkAreasFromFile(gitLocation);
return BuildUtils.getWorkAreaByIDFromWorkAreas(workAreas, workAreaID);
}
/**
* Get the IElementBasicData information of the lock element. Throw error if any field is missing
*
* @static
* @param {IWorkArea} workArea
* @param {string} instance
* @returns {IElementBasicData}
* @memberof BuildUtils
*/
static getLockElementSpec(workArea, instance) {
const elementSpec = {
environment: workArea.lockElement.environment,
stageNumber: "1",
system: workArea.lockElement.system,
subsystem: workArea.lockElement.subsystem,
type: workArea.lockElement.type,
element: workArea.lockElement.name,
instance
};
const errorStack = [];
Object.keys(elementSpec).forEach((key) => {
if ((0, object_1.isNil)(elementSpec[key])) {
errorStack.push(key);
}
});
if (errorStack.length > 0) {
imperative_1.Logger.getAppLogger().trace(`BuildUtils - getLockElementSpec: ${JSON.stringify(elementSpec)} \n` +
`missing the following fields: ${errorStack.join(", ")} `);
throw new imperative_1.ImperativeError({
msg: `Work area with id ${workArea.id} does not contain all the required information`
});
}
return elementSpec;
}
/**
* Read the metadata file from git working directory gitLocation (last version takes precedence)
*
* @static
* @param {string} gitLocation
* @returns {IMappingMetadata}
* @memberof BuildUtils
*/
static readMappingMetadata(gitLocation) {
const VERSION_4 = 4;
const mappingMetadataPath = EBGConstants_1.EBGConstants.getMappingMetadataFilePath(gitLocation);
let metadata;
let mappingMetadata;
metadata = this.readJSONFileAsObject(mappingMetadataPath, EBGConstants_1.EBGConstants.MAPPING_METADATA_FILENAME);
this.validateMappingMetadata(metadata);
if (metadata.version === VERSION_4) {
return metadata;
}
mappingMetadata = MappingMetadata_1.MappingMetadata.convert(metadata);
return mappingMetadata;
}
/**
* Download listing for element "elm", if elm's return code >= listingRC.
* Downloaded output will be put into listingDir.
* When there's any error happened during print, error report will be written into endvReportsDir.
* An error will be thrown with message of the error report location. (when there's no error report, err msg will be rest api err msg),
* and causeErrors as the return code
*
* @static
* @param {Session} endevorSession
* @param {string} instance
* @param {IElementActionReport} elm
* @param {string} listingDir
* @param {number} listingRC
* @param {string} endvReportsDir
* @returns {Promise<string>}
* @memberof BuildUtils
*/
static downloadListings(endevorSession, instance, elm, listingDir, listingRC, endvReportsDir) {
return __awaiter(this, void 0, void 0, function* () {
const stages = yield EndevorService_1.EndevorService.getStages(endevorSession, instance, elm.environment);
const stage = stages.find(s => s.stgId === elm.stage && (0, object_1.isNotNil)(s.stgNum));
if ((0, object_1.isNil)(stage)) {
throw new imperative_1.ImperativeError({
msg: `Stage ${elm.stage} not found`
});
}
if (Number(elm.endevorRC) < listingRC) {
return `Skip downloading. NDRVRC < listing-rc ${listingRC}`;
}
const now = new Date();
const fileDateTime = api_1.EndevorUtils.formatDate(now, false) + "-" + api_1.EndevorUtils.formatTime(now, true, "");
const outputFileName = path.join(listingDir, elm.system + "-" + elm.subsystem + "-" + elm.elementName + "-" + elm.type + "-" + fileDateTime + ".txt");
// print listing
const printEleDef = {
element: elm.elementName,
environment: elm.environment,
stageNumber: String(stage.stgNum),
system: elm.system,
subsystem: elm.subsystem,
type: elm.type,
instance: "",
};
const printResult = yield EndevorService_1.EndevorService.printListingWithoutThrowingErr(endevorSession, instance, printEleDef);
// process unexpected response
if (Number(printResult.body.returnCode) > 0) {
if ((0, object_1.isNotNil)(printResult.body.messages)) {
const msgs = printResult.body.messages.toString().split(",");
if (msgs.length > 0) {
const lasterr = msgs[msgs.length - 1];
const matchGroup = lasterr.match(/^(\d{2}:\d{2}:\d{2})(.*)$/); // match and remove timestamp
if ((0, object_1.isNil)(matchGroup)) {
return `No listing. ${lasterr.trim()}`;
}
else {
// tslint:disable-next-line: no-magic-numbers
return `No listing. ${matchGroup[2].trim()}`;
}
}
}
return "No listing";
}
else {
api_1.EndevorUtils.generalWriteFile(outputFileName, (0, object_1.isNil)(printResult.body.data) ? "" : printResult.body.data[0]);
return outputFileName;
}
});
}
static validateMappingMetadata(mappingMetadata) {
if ((0, object_1.isNil)(mappingMetadata.version) ||
(0, object_1.isNil)(mappingMetadata.url) ||
(0, object_1.isNil)(mappingMetadata.git) ||
(0, object_1.isNil)(mappingMetadata.endevor) ||
(0, object_1.isNil)(mappingMetadata.git.cloneUrl) ||
(0, object_1.isNil)(mappingMetadata.git.branch) ||
(0, object_1.isNil)(mappingMetadata.git.context) ||
(0, object_1.isNil)(mappingMetadata.git.repository)) {
throw new imperative_1.ImperativeError({
msg: `mapping.json file is not valid`
});
}
}
}
exports.BuildUtils = BuildUtils;
//# sourceMappingURL=BuildUtils.js.map