UNPKG

@zowe/zos-files-for-zowe-sdk

Version:

Zowe SDK to interact with files and data sets on z/OS

269 lines 11.3 kB
"use strict"; /* * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright Contributors to the Zowe Project. * */ 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.ZosFilesUtils = void 0; const path = require("path"); const fs = require("fs"); const imperative_1 = require("@zowe/imperative"); const ZosFiles_constants_1 = require("../constants/ZosFiles.constants"); const ZosFiles_messages_1 = require("../constants/ZosFiles.messages"); const core_for_zowe_sdk_1 = require("@zowe/core-for-zowe-sdk"); /** * Common IO utilities */ class ZosFilesUtils { /** * Break up a dataset name of either: * USER.WORK.JCL(TEMPLATE) to user/work/jcl/template * Or: * USER.WORK.PS to user/work/ps * @param {string} dataSet - data set to break up into folders */ static getDirsFromDataSet(dataSet) { let localDirectory = dataSet.replace(new RegExp(`\\${this.DSN_SEP}`, "g"), path.posix.sep).toLowerCase(); if (localDirectory.indexOf("(") >= 0 && localDirectory.indexOf(")") >= 0) { localDirectory = localDirectory.replace(/\(/, path.posix.sep); localDirectory = localDirectory.slice(0, -1); } return localDirectory; } /** * Get fullpath name from input path. * @param {string} inputPath - input path * @return {string} full path version of the input path */ static getFullPath(inputPath) { let fullPath = path.normalize(inputPath); if (fullPath.indexOf(":\\") !== -1 || fullPath.indexOf("/") === 0) { fullPath = path.normalize(fullPath); } else { fullPath = path.resolve(process.cwd(), fullPath); } return fullPath; } /** * Return an array contain the list of all files in the input path. It does not trevor to * directory in the input path. * @param {string} inputPath input path to gather file list * @param {boolean} [inFullPathFormat=true] is the return file path in full path mode flag * @param {boolean} [isIgnoreHidden=true] is listing hidden files flag * @return {string[]} Array of all files finds in path */ static getFileListFromPath(inputPath, inFullPathFormat = true, isIgnoreHidden = true) { const returnFileList = []; const fullpath = this.getFullPath(inputPath); if (imperative_1.IO.isDir(fullpath)) { const fileList = fs.readdirSync(fullpath); fileList.forEach((file) => { const tempPath = path.resolve(fullpath, file); if (fs.lstatSync(tempPath).isFile()) { if (!(isIgnoreHidden && path.basename(file).startsWith("."))) { if (inFullPathFormat) { returnFileList.push(tempPath); } else { returnFileList.push(file); } } } }); } else if (fs.lstatSync(fullpath).isFile()) { if (inFullPathFormat) { returnFileList.push(fullpath); } else { returnFileList.push(inputPath); } } else { // todo add handler for symplink here } return returnFileList; } /** * Common method to build headers given input options object * @private * @static * @param {IOptions} options - various options * @returns {IHeaderContent[]} * @memberof ZosFilesUtils */ static generateHeadersBasedOnOptions(options) { const reqHeaders = []; if (options.binary) { reqHeaders.push(core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_BINARY); } else if (options.record) { reqHeaders.push(core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_RECORD); } else if (options.encoding) { const keys = Object.keys(core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_TEXT); const value = core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_TEXT[keys[0]] + core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_TEXT_ENCODING + options.encoding; const header = Object.create(core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_TEXT); header[keys[0]] = value; reqHeaders.push(header); } else { // do nothing } // TODO:gzip Always accept encoding after z/OSMF truncating gzipped binary data is fixed // See https://github.com/zowe/zowe-cli/issues/1170 if (!options.binary && !options.record) { reqHeaders.push(core_for_zowe_sdk_1.ZosmfHeaders.ACCEPT_ENCODING); } if (options.responseTimeout != null) { reqHeaders.push({ [core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_RESPONSE_TIMEOUT]: options.responseTimeout.toString() }); } return reqHeaders; } /** * Generate member name from input string base on IBM specification * @param {string} fileName input name used to generate member name with * @return {string} generated member name */ static generateMemberName(fileName) { let memberName = path.basename(fileName).toUpperCase(); // Remove extention memberName = memberName.replace(path.extname(memberName), ""); // First character must be either a letter or #, @, $. memberName = memberName.replace(/[^A-Z0-9@#$]/g, ""); // Member also does not allow to start with a number memberName = memberName.replace(/[\d]/gy, ""); // Trunkage lenght to max lenght allowed memberName = memberName.substring(0, this.MAX_MEMBER_LENGTH); return memberName; } /** * Check if the input data set name contain masking characters * @param {string} dataSetName input data set name to be checked * @return {boolean} status if data set name contain masking characters */ static isDataSetNameContainMasking(dataSetName) { let returnStatus = false; if (dataSetName.match(/[*%]/g)) { returnStatus = true; } return returnStatus; } /** * Normalize all Windows newline to Unix newline * @param {Buffer} buffer data to convert * @return {Buffer} converted data */ static normalizeNewline(buffer) { return Buffer.from(buffer.toString().replace(/\r\n/g, "\n")); } /** * Normanize and URL-encode a USS path to be passed to z/OSMF * @param ussPath path to sanitize */ static sanitizeUssPathForRestCall(ussPath) { let sanitizedPath = path.posix.normalize(ussPath); sanitizedPath = this.formatUnixFilepath(sanitizedPath); return encodeURIComponent(sanitizedPath); } /** * Format USS filepaths in the way that the APIs expect (no leading /) * @param {string} usspath - the path to format */ static formatUnixFilepath(usspath) { if (usspath.charAt(0) === "/") { // trim leading slash from unix files - API doesn't like it usspath = usspath.substring(1); } return usspath; } /** * @param {AbstractSession} session - z/OSMF connection info * @param {string} dataSetName -The name of the data set to recall|migrate|delete * @param {string} returnMessage - Message to return based upon command request * @param {any} hsmCommand - HsmCommand requested * @param {IRecallOptions | IMigrateOptions | IDeleteOptions} options * * - If true then the function waits for completion of the request. If false (default) the request is queued. */ static dfsmsHsmCommand(session_1, dataSetName_1, returnMessage_1, hsmCommand_1) { return __awaiter(this, arguments, void 0, function* (session, dataSetName, returnMessage, hsmCommand, options = {}) { imperative_1.ImperativeExpect.toNotBeNullOrUndefined(dataSetName, ZosFiles_messages_1.ZosFilesMessages.missingDatasetName.message); imperative_1.ImperativeExpect.toNotBeEqual(dataSetName, "", ZosFiles_messages_1.ZosFilesMessages.missingDatasetName.message); try { const endpoint = path.posix.join(ZosFiles_constants_1.ZosFilesConstants.RESOURCE, ZosFiles_constants_1.ZosFilesConstants.RES_DS_FILES, encodeURIComponent(dataSetName)); imperative_1.Logger.getAppLogger().debug(`Endpoint: ${endpoint}`); const payload = hsmCommand; if (options.wait != null) { payload.wait = options.wait; } if (options.purge != null) { payload.purge = options.purge; } const headers = [ imperative_1.Headers.APPLICATION_JSON, { "Content-Length": JSON.stringify(payload).length.toString() }, core_for_zowe_sdk_1.ZosmfHeaders.ACCEPT_ENCODING ]; if (options.responseTimeout != null) { headers.push({ [core_for_zowe_sdk_1.ZosmfHeaders.X_IBM_RESPONSE_TIMEOUT]: options.responseTimeout.toString() }); } yield core_for_zowe_sdk_1.ZosmfRestClient.putExpectString(session, endpoint, headers, payload); return { success: true, commandResponse: returnMessage }; } catch (error) { imperative_1.Logger.getAppLogger().error(error); throw error; } }); } /** * Converts the name of a data set to an IDataSet * @param {string} name - the name in the form USER.DATA.SET | USER.DATA.SET(mem1) */ static getDataSetFromName(name) { const parts = name.replace(')', '').split('('); if (parts.length > 1) { return { dsn: parts[0], member: parts[1] }; } else { return { dsn: name }; } } } exports.ZosFilesUtils = ZosFilesUtils; /** * Data set name qualifier separator * @type {string} */ ZosFilesUtils.DSN_SEP = "."; /** * Default file extension * @type {string} */ ZosFilesUtils.DEFAULT_FILE_EXTENSION = "txt"; ZosFilesUtils.MAX_MEMBER_LENGTH = 8; //# sourceMappingURL=ZosFilesUtils.js.map