Add detect package manager util function

This commit is contained in:
Han Yeong-woo 2023-09-02 04:27:58 +09:00
parent fcf2d83f3d
commit cbe5f5b523
No known key found for this signature in database
GPG key ID: A46E340CB4E4D6AD
6 changed files with 46 additions and 2 deletions

View file

@ -1,6 +1,11 @@
import { expect, test, describe } from "vitest";
import { checkWorkingDirectory, getNpxCmd, semverCompare } from "./utils";
import path from "node:path"; import path from "node:path";
import { describe, expect, test } from "vitest";
import {
checkWorkingDirectory,
detectPackageManager,
getNpxCmd,
semverCompare,
} from "./utils";
test("getNpxCmd ", async () => { test("getNpxCmd ", async () => {
process.env.RUNNER_OS = "Windows"; process.env.RUNNER_OS = "Windows";
@ -43,3 +48,25 @@ describe("checkWorkingDirectory", () => {
); );
}); });
}); });
describe("detectPackageManager", () => {
test("should return name of package manager for current workspace", () => {
expect(detectPackageManager()).toBe("npm");
});
test("should return npm if package-lock.json exists", () => {
expect(detectPackageManager("test/fixtures/npm")).toBe("npm");
});
test("should return yarn if yarn.lock exists", () => {
expect(detectPackageManager("test/fixtures/yarn")).toBe("yarn");
});
test("should return pnpm if pnpm-lock.yaml exists", () => {
expect(detectPackageManager("test/fixtures/pnpm")).toBe("pnpm");
});
test("should return null if no package manager is detected", () => {
expect(detectPackageManager("test/fixtures/empty")).toBe(null);
});
});

View file

@ -33,3 +33,20 @@ export function checkWorkingDirectory(workingDirectory = ".") {
throw new Error(`Directory ${workingDirectory} does not exist.`); throw new Error(`Directory ${workingDirectory} does not exist.`);
} }
} }
export type PackageManager = "npm" | "yarn" | "pnpm";
export function detectPackageManager(
workingDirectory = ".",
): PackageManager | null {
if (existsSync(path.join(workingDirectory, "package-lock.json"))) {
return "npm";
}
if (existsSync(path.join(workingDirectory, "yarn.lock"))) {
return "yarn";
}
if (existsSync(path.join(workingDirectory, "pnpm-lock.yaml"))) {
return "pnpm";
}
return null;
}

0
test/fixtures/empty/.gitkeep vendored Normal file
View file

0
test/fixtures/npm/package-lock.json generated vendored Normal file
View file

0
test/fixtures/pnpm/pnpm-lock.yaml vendored Normal file
View file

0
test/fixtures/yarn/yarn.lock vendored Normal file
View file