UNPKG

obtain-package-manager

Version:

obtain which package manager you're using (yarn or npm)

76 lines (72 loc) 2.06 kB
import { existsSync } from 'fs'; import child_process from 'child_process'; import { resolve } from 'path'; const SEMVER_REGEX = /^\d+.\d+.\d+$/; function pathExists(p) { return existsSync(p); } async function exec_async(...commands) { const command_string = commands.join(" "); return new Promise((resolve2, reject) => { child_process.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(resolve(cwd, "yarn.lock")), pathExists(resolve(cwd, "package-lock.json")), pathExists(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"; }; export { clearCache, getPackManagerVersion, getPackageManager };