@stackbit/utils
Version:
Stackbit utilities
85 lines (77 loc) • 2.66 kB
text/typescript
import _ from 'lodash';
import path from 'path';
import fse from 'fs-extra';
import yaml from 'js-yaml';
async function detectPackageManager(dir: string) {
let packageManager = null;
if (await fse.pathExists(path.join(dir, 'pnpm-lock.yaml'))) {
packageManager = 'pnpm';
} else if (await fse.pathExists(path.join(dir, 'yarn.lock'))) {
packageManager = 'yarn';
} else if (await fse.pathExists(path.join(dir, 'Gemfile'))) {
packageManager = 'bundle';
} else if (await fse.pathExists(path.join(dir, 'package.json'))) {
packageManager = 'npm';
}
return packageManager;
}
async function checkIsYarnV2or3(dir: string) {
try {
const yarnRcFile = path.join(dir, '.yarnrc.yml');
const yarnRcExists = await fse.pathExists(yarnRcFile);
if (yarnRcExists) {
const fileContents = await fse.readFile(yarnRcFile, 'utf8');
const data = yaml.load(fileContents);
return _.get(data, 'yarnPath') === '.yarn/releases/yarn-berry.cjs' || _.get(data, 'yarnPath').startsWith('.yarn/releases/yarn-3.');
}
} catch (err) {
throw new Error('error checking for yarn2');
}
return false;
}
export interface PackageManagerDetails {
name: string;
cmd: string;
args: string[];
env: NodeJS.ProcessEnv;
useNvm: boolean;
}
export async function getPackageManager(dir: string): Promise<PackageManagerDetails | null> {
const packageManager = await detectPackageManager(dir);
if (!packageManager) {
return null;
}
let cmd = packageManager;
let args: string[] = [];
let useNvm = false;
const env: NodeJS.ProcessEnv = {};
if (packageManager === 'bundle') {
cmd = 'bundle';
args = ['install'];
} else if (packageManager === 'pnpm') {
cmd = 'pnpm';
args = ['install', '--prefer-offline', '--color=always'];
useNvm = true;
} else if (packageManager === 'npm') {
cmd = 'npm';
args = ['install', '--no-audit', '--prefer-offline', '--no-save', '--color=always'];
useNvm = true;
} else if (packageManager === 'yarn') {
const isYarnV2orHigher = await checkIsYarnV2or3(dir);
cmd = 'yarn';
args = ['install'];
useNvm = true;
if (isYarnV2orHigher) {
env.YARN_NODE_LINKER = 'node-modules';
} else {
args.push('--non-interactive', `--cache-folder ${path.join(path.dirname(dir), '.cache-' + path.basename(dir))}`, '--color=always');
}
}
return {
name: packageManager,
cmd,
args,
useNvm,
env
};
}