UNPKG

@zowe/imperative

Version:
147 lines 6.88 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 }); const fs = require("fs"); const path = require("path"); const url_1 = require("url"); const JSONC = require("comment-json"); const error_1 = require("../../../../../error"); const utilities_1 = require("../../../../../utilities"); const rest_1 = require("../../../../../rest"); /** * Import config */ class ImportHandler { /** * Process the command and input. * * @param {IHandlerParameters} params Parameters supplied by yargs * * @throws {ImperativeError} */ process(params) { return __awaiter(this, void 0, void 0, function* () { var _a; this.params = params; // Load the config and set the active layer according to user options const config = utilities_1.ImperativeConfig.instance.config; const configDir = params.arguments.globalConfig ? null : process.cwd(); config.api.layers.activate(params.arguments.userConfig, params.arguments.globalConfig, configDir); const layer = config.api.layers.get(); if (layer.exists && !params.arguments.overwrite) { params.response.console.log(`Skipping import because ${layer.path} already exists.\n` + `Rerun the command with the --overwrite flag to import anyway.`); return; } const configFilePath = path.resolve(params.arguments.location); const isConfigLocal = fs.existsSync(configFilePath) || path.isAbsolute(params.arguments.location); // Typecasting because of this issue: https://github.com/kaelzhang/node-comment-json/issues/42 const configJson = isConfigLocal ? JSONC.parse(fs.readFileSync(configFilePath, "utf-8")) : yield this.fetchConfig(new url_1.URL(params.arguments.location)); config.api.layers.set(configJson); let schemaImported = false; if ((_a = configJson.$schema) === null || _a === void 0 ? void 0 : _a.startsWith("./")) { // Only import schema if relative path const schemaUri = new url_1.URL(configJson.$schema, isConfigLocal ? (0, url_1.pathToFileURL)(configFilePath) : params.arguments.location); const schemaFilePath = path.resolve(path.dirname(layer.path), configJson.$schema); try { yield this.downloadSchema(schemaUri, schemaFilePath); schemaImported = true; } catch (error) { params.response.console.error(utilities_1.TextUtils.chalk.yellow("Warning:") + ` Failed to download schema\n${error.message}\n`); } } // Write the active created/updated config layer config.api.layers.write(); params.response.console.log(`Imported config${schemaImported ? " and schema" : ""} to ${layer.path}`); }); } /** * Build a session from a URL and command line arguments. * @param url Web URL of the config JSON file * @returns Populated session object */ buildSession(url) { let session = rest_1.Session.createFromUrl(url, false); if (this.params.arguments.user != null && this.params.arguments.password != null) { const { protocol, hostname, port } = session.ISession; session = new rest_1.Session({ protocol, hostname, port, type: rest_1.SessConstants.AUTH_TYPE_BASIC, user: this.params.arguments.user, password: this.params.arguments.password }); } rest_1.AuthOrder.addCredsToSession(session.ISession, this.params.arguments); session.ISession.rejectUnauthorized = this.params.arguments.rejectUnauthorized; return session; } /** * Download the config from a URL * @param url Web URL of the config JSON file * @returns Parsed config object */ fetchConfig(url) { return __awaiter(this, void 0, void 0, function* () { const response = yield rest_1.RestClient.getExpectString(this.buildSession(url), url.pathname); try { // Typecasting because of this issue: https://github.com/kaelzhang/node-comment-json/issues/42 return JSONC.parse(response); } catch (error) { throw new error_1.ImperativeError({ msg: "Failed to parse config JSON: URL must point to a valid JSON file\n" + error.message, causeErrors: error }); } }); } /** * Download the config schema from a URL to disk * @param url Web URL of the schema JSON file * @param filePath Local path to download to */ downloadSchema(url, filePath) { return __awaiter(this, void 0, void 0, function* () { if (url.protocol === "file:") { fs.copyFileSync((0, url_1.fileURLToPath)(url), filePath); } else { const response = yield rest_1.RestClient.getExpectString(this.buildSession(url), url.pathname); try { // Typecasting because of this issue: https://github.com/kaelzhang/node-comment-json/issues/42 JSONC.parse(response); } catch (error) { throw new error_1.ImperativeError({ msg: "Failed to parse schema JSON: URL must point to a valid JSON file\n" + error.message, causeErrors: error }); } fs.writeFileSync(filePath, response); } }); } } exports.default = ImportHandler; //# sourceMappingURL=import.handler.js.map