@zowe/imperative
Version:
framework for building configurable CLIs
211 lines • 9.21 kB
JavaScript
;
/*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NpmRegistryUtils = void 0;
exports.findNpmOnPath = findNpmOnPath;
exports.installPackages = installPackages;
exports.getPackageInfo = getPackageInfo;
const PMFConstants_1 = require("./PMFConstants");
const path = require("path");
const which = require("which");
const jsonfile_1 = require("jsonfile");
const npmPackageArg = require("npm-package-arg");
const utilities_1 = require("../../../../utilities");
const logger_1 = require("../../../../logger");
const error_1 = require("../../../../error");
const npmCmd = findNpmOnPath();
/**
* Common function that returns npm command as a string.
*
* @return {string} command with npm path
*/
function findNpmOnPath() {
return which.sync("npm");
}
/**
* Common function that installs a npm package using the local npm cli.
* @param {string} prefix Path where to install npm the npm package.
*
* @param {string} registry The npm registry to install from.
*
* @param {string} npmPackage The name of package to install.
*
* @return {string} command response
*
*/
function installPackages(npmPackage, npmArgs, verbose = false) {
var _a;
const pipe = ["pipe", "pipe", "pipe"];
const args = ["install", npmPackage, "-g", "--legacy-peer-deps"];
if (verbose) {
const logLevel = ((logger) => {
switch (logger.level) {
case "TRACE": return "silly";
case "DEBUG": return "verbose";
default: return "info";
}
})(logger_1.Logger.getAppLogger());
args.push(`--loglevel=${logLevel}`, "--foreground-scripts");
}
for (const [k, v] of Object.entries(npmArgs)) {
if (v != null) {
// If npm arg starts with @ like @zowe:registry, must use = as separator
args.push(...k.startsWith("@") ? [`--${k}=${v}`] : [`--${k}`, v]);
}
}
let execOutput = "";
const daemonStream = (_a = utilities_1.ImperativeConfig.instance.daemonContext) === null || _a === void 0 ? void 0 : _a.stream;
if (verbose && daemonStream == null) {
utilities_1.ExecUtils.spawnWithInheritedStdio(npmCmd, args, {
cwd: PMFConstants_1.PMFConstants.instance.PMF_ROOT,
});
}
else {
execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, args, {
cwd: PMFConstants_1.PMFConstants.instance.PMF_ROOT,
stdio: pipe
}).toString();
if (verbose && daemonStream != null) {
daemonStream.write(utilities_1.DaemonRequest.create({ stdout: execOutput }));
}
}
return execOutput;
}
/**
* Fetch name and version of NPM package that was installed
* @param pkgSpec The package name as specified on NPM install
*/
function getPackageInfo(pkgSpec) {
const pkgInfo = npmPackageArg(pkgSpec);
let packageName = pkgInfo.name;
if (!pkgInfo.registry) {
// Package name is unknown, so fetch it with 'npm pack' command
const maxOutputInx = 200;
let truncationMsg = "\n<Additional output not displayed>";
let execOutput = "No npm pack output was retrieved";
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const maxBuffer = 1024 * 1024 * 10; // 10MB
execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, ["pack", pkgSpec, "--dry-run", "--json"], { maxBuffer }).toString();
// In test pipelines, parallel tests use Git to retrieve source to compile and to
// run CodeQL analysis. Some conflict causes <YourSourceCodeRootDirectory>/.git/config.lock
// to be left around. As a result, when the pipeline spawns 'npm pack' to get the contents
// of package.json, an error message that looks like the following may be displayed before
// the correct contents of package.json.
//
// "error: could not lock config file .git/config: File exists"
// or
// "warning: unable to access '.git/config': Permission denied"
//
// JSON.parse() fails to parse the output because of that error message.
// A successful 'npm pack' command always displays its results in an array.
// The following code looks for the start of an array and removes any text
// that occurs before the array of valid JSON. This allows
// the JSON to be successfully parsed. Any removed text is logged.
let startOfJsonInx = execOutput.indexOf("\n[");
if (startOfJsonInx > 0) {
// we had some text before a JSON array
logger_1.Logger.getImperativeLogger().error("The following errors were displayed by 'npm pack' before its JSON output:\n" +
execOutput.substring(0, startOfJsonInx));
// discard the errors, and keep the JSON array
startOfJsonInx++;
execOutput = execOutput.substring(startOfJsonInx);
}
// parse the json output of the npm pack command
try {
packageName = JSON.parse(execOutput)[0].name;
}
catch (err) {
if (execOutput.length < maxOutputInx) {
truncationMsg = "";
}
throw new error_1.ImperativeError({
msg: `Unable to parse the JSON output of 'npm pack' for this package: '${pkgSpec}'`,
additionalDetails: "JSON.parse error = " + err.message +
"\nOutput of 'npm pack':\n" + execOutput.substring(0, maxOutputInx) + truncationMsg
});
}
}
return (0, jsonfile_1.readFileSync)(path.join(PMFConstants_1.PMFConstants.instance.PLUGIN_HOME_LOCATION, packageName, "package.json"));
}
class NpmRegistryUtils {
/**
* Get the registry to install to.
* @param userRegistry Registry override specified on the command line
* @return {string}
*/
static getRegistry(userRegistry) {
if (userRegistry != null)
return userRegistry;
const execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, ["config", "get", "registry"]);
return execOutput.toString().replace("\n", "");
}
/**
* NPM login to be able to install from secure registry
* @param {string} registry The npm registry to install from.
*/
static npmLogin(registry) {
utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, [
"login",
"--registry", registry,
"--always-auth",
"--auth-type=legacy"
], { stdio: "inherit" });
}
/**
* Get package location and npm registry args for installing it.
* @param packageInfo Plugin name or object from plugins.json
* @param userRegistry Registry override specified on the command line
* @returns Location info for npm package to be installed
*/
static buildRegistryInfo(packageInfo, userRegistry) {
const packageName = typeof packageInfo === "string" ? packageInfo : packageInfo.package;
const packageScope = packageName.startsWith("@") ? packageName.split("/")[0] : undefined;
if (userRegistry != null) {
// If --registry was passed on the command line, it takes precedence
return {
location: userRegistry,
npmArgs: this.buildRegistryNpmArgs(userRegistry, packageScope)
};
}
else if (typeof packageInfo === "string" || !packageInfo.location) {
// If installing a plug-in for the first time, get default registry
const defaultRegistry = this.getRegistry();
return {
location: npmPackageArg(packageName).registry ? defaultRegistry : packageName,
npmArgs: this.buildRegistryNpmArgs(defaultRegistry, packageScope)
};
}
else {
// If updating a plug-in, fetch registry info from plugins.json
const cachedRegistry = npmPackageArg(packageInfo.package).registry ? packageInfo.location : undefined;
return {
location: packageInfo.location,
npmArgs: this.buildRegistryNpmArgs(cachedRegistry !== null && cachedRegistry !== void 0 ? cachedRegistry : this.getRegistry(), packageScope)
};
}
}
static buildRegistryNpmArgs(registryUrl, scope) {
const npmArgs = { registry: registryUrl };
if (scope != null) {
npmArgs[`${scope}:registry`] = this.getScopeRegistry(scope);
}
return npmArgs;
}
static getScopeRegistry(scope) {
const execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, ["config", "get", `${scope}:registry`]);
if (execOutput.toString().trim() === "undefined")
return;
return execOutput.toString().replace("\n", "");
}
}
exports.NpmRegistryUtils = NpmRegistryUtils;
//# sourceMappingURL=NpmFunctions.js.map