obtain-package-manager
Version:
obtain which package manager you're using (yarn or npm)
86 lines (78 loc) • 2.42 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
const fs = require('fs');
const child_process = require('child_process');
const path = require('path');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
const child_process__default = /*#__PURE__*/_interopDefaultLegacy(child_process);
const SEMVER_REGEX = /^\d+.\d+.\d+$/;
function pathExists(p) {
return fs.existsSync(p);
}
async function exec_async(...commands) {
const command_string = commands.join(" ");
return new Promise((resolve2, reject) => {
child_process__default.exec(command_string, (error, stdout, stderr) => {
if (error)
return reject(error);
if (stderr)
return reject(stderr.trim());
resolve2(stdout.trim());
});
});
}
function hasGlobalInstallation(pm, cache) {
const key = `has_global_${pm}`;
if (cache.has(key))
return Promise.resolve(cache.get(key));
return exec_async(pm, "--version").then((stdout) => {
return SEMVER_REGEX.test(stdout);
}).then((value) => {
cache.set(key, value);
return value;
});
}
function getTypeofLockFile(cwd = ".", cache) {
const key = `lockfile_${cwd}`;
if (cache.has(key))
return Promise.resolve(cache.get(key));
return Promise.all([
pathExists(path.resolve(cwd, "yarn.lock")),
pathExists(path.resolve(cwd, "package-lock.json")),
pathExists(path.resolve(cwd, "pnpm-lock.yaml"))
]).then(([isYarn, isNpm, isPnpm]) => {
let value = null;
if (isYarn)
value = "yarn";
else if (isPnpm)
value = "pnpm";
else if (isNpm)
value = "npm";
cache.set(key, value);
return value;
});
}
async function getPackManagerVersion(pm = "npm") {
return exec_async(pm || "npm", "--version").then((stdout) => stdout);
}
function clearCache(cache) {
return cache.clear();
}
const cache = /* @__PURE__ */ new Map();
const getPackageManager = async ({ cwd } = {}) => {
const type = await getTypeofLockFile(cwd, cache);
if (type)
return type;
const [hasYarn, hasPnpm] = await Promise.all([
hasGlobalInstallation("yarn", cache),
hasGlobalInstallation("pnpm", cache)
]);
if (hasYarn)
return "yarn";
if (hasPnpm)
return "pnpm";
return "npm";
};
exports.clearCache = clearCache;
exports.getPackManagerVersion = getPackManagerVersion;
exports.getPackageManager = getPackageManager;