-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathpackage-manager.ts
More file actions
55 lines (49 loc) · 1.65 KB
/
Copy pathpackage-manager.ts
File metadata and controls
55 lines (49 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import type { PackageJsonShape } from './framework-detect.js';
const execAsync = promisify(exec);
export type PackageManager = 'pnpm' | 'yarn' | 'bun' | 'npm';
/**
* Detect the project's package manager from lockfile presence.
* Falls back to npm when no lockfile is found.
*/
export function detectPackageManager(cwd: string): PackageManager {
if (existsSync(join(cwd, 'pnpm-lock.yaml'))) return 'pnpm';
if (existsSync(join(cwd, 'yarn.lock'))) return 'yarn';
if (existsSync(join(cwd, 'bun.lockb')) || existsSync(join(cwd, 'bun.lock'))) {
return 'bun';
}
return 'npm';
}
/** Build the install command for a single package using the given manager. */
export function installCommand(pm: PackageManager, pkg: string): string {
switch (pm) {
case 'pnpm':
return `pnpm add ${pkg}`;
case 'yarn':
return `yarn add ${pkg}`;
case 'bun':
return `bun add ${pkg}`;
case 'npm':
default:
return `npm install ${pkg}`;
}
}
/**
* Returns true if the given package is already in dependencies or devDependencies.
*/
export function hasPackage(pkg: PackageJsonShape | null, name: string): boolean {
if (!pkg) return false;
return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
}
/** Run a package install command. Wraps errors with context. */
export async function runInstall(
pm: PackageManager,
pkgName: string,
cwd: string,
): Promise<void> {
const cmd = installCommand(pm, pkgName);
await execAsync(cmd, { cwd, maxBuffer: 16 * 1024 * 1024 });
}