Skip to content

Commit

Permalink
feat(shared): add detectPackageManager
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope committed May 3, 2022
1 parent bc41194 commit 777a2bb
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/shared/rollup.config.js
Expand Up @@ -5,8 +5,10 @@ export default [
resolve: true,
external: [
"@vuepress/plugin-git",
"@vuepress/utils",
"@vuepress/shared",
"chalk",
"execa",
"http",
"ora",
"vite",
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/node/utils/index.ts
@@ -1,3 +1,4 @@
export * from "./assign";
export * from "./date";
export * from "./encode";
export * from "./packageManager";
78 changes: 78 additions & 0 deletions packages/shared/src/node/utils/packageManager.ts
@@ -0,0 +1,78 @@
import { existsSync } from "fs";
import { resolve } from "path";
import { sync } from "execa";

export type PackageManager = "npm" | "yarn" | "pnpm";

const globalCache = new Map<string, boolean>();
const localCache = new Map<string, PackageManager>();

const isInstalled = (packageManager: PackageManager): boolean => {
try {
return (
sync(`${packageManager} --version`, { stdio: "ignore" }).exitCode === 0
);
} catch (e) {
return false;
}
};

/**
* Check if a global package manager is available
*/
const hasGlobalInstallation = (packageManager: PackageManager): boolean => {
const key = `global:${packageManager}`;

const status = globalCache.get(key);

if (status !== undefined) return status;

if (isInstalled(packageManager)) {
globalCache.set(key, true);

return true;
}

return false;
};

const getTypeofLockFile = (cwd: string): PackageManager | null => {
const key = `local:${cwd}`;

const status = localCache.get(key);

if (status !== undefined) return status;

if (existsSync(resolve(cwd, "pnpm-lock.yaml"))) {
localCache.set(key, "pnpm");

return "pnpm";
}

if (existsSync(resolve(cwd, "yarn.lock"))) {
localCache.set(key, "yarn");

return "yarn";
}

if (existsSync(resolve(cwd, "package-lock.json"))) {
localCache.set(key, "npm");

return "npm";
}

return null;
};

export const detectPackageManager = (cwd = process.cwd()): PackageManager => {
const type = getTypeofLockFile(cwd);

return (
type ||
(hasGlobalInstallation("pnpm")
? "pnpm"
: hasGlobalInstallation("yarn")
? "yarn"
: "npm")
);
};

0 comments on commit 777a2bb

Please sign in to comment.