Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Dec 4, 2023
1 parent 7e7ed2a commit 5c26e39
Showing 1 changed file with 42 additions and 31 deletions.
73 changes: 42 additions & 31 deletions scripts/check-deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,38 @@ import { execa } from "execa";
import chalk from "chalk";

const PACKAGE_JSON_FILE = new URL("../package.json", import.meta.url);
const shouldFix = process.argv.includes("--fix");
const DEPENDENCY_KINDS = [
"dependencies",
"devDependencies",
"peerDependencies",
"optionalDependencies",
"resolutions",
];

const isPinnedVersion = (version) =>
!(version.startsWith("^") || version.startsWith("~"));

function* getUnpinnedDependencies(packageJson) {
for (const kind of DEPENDENCY_KINDS) {
for (const [name, version] of Object.entries(packageJson[kind] ?? {})) {
if (!isPinnedVersion(version)) {
yield { kind, name, version };
}
}
}
}

async function checkDependencies(shouldFix) {
async function fixDependencies() {
const packageJson = JSON.parse(await fs.readFile(PACKAGE_JSON_FILE));

let changed = false;

for (const kind of [
"dependencies",
"devDependencies",
"peerDependencies",
"optionalDependencies",
"resolutions",
]) {
if (!packageJson[kind]) {
continue;
}

for (const [name, version] of Object.entries(packageJson[kind])) {
if (!(version.startsWith("^") || version.startsWith("~"))) {
continue;
}

if (shouldFix) {
packageJson[kind][name] = version.slice(1);
changed = true;
} else {
console.error(
chalk.red("error"),
`"${chalk.bold.red(name)}" in "${kind}" should be pinned.`,
);
process.exitCode = 1;
}
}
for (const { kind, name, version } of getUnpinnedDependencies(packageJson)) {
packageJson[kind][name] = version.slice(1);
changed = true;
}

if (shouldFix && changed) {
if (changed) {
await fs.writeFile(
PACKAGE_JSON_FILE,
JSON.stringify(packageJson, undefined, 2) + "\n",
Expand All @@ -49,4 +44,20 @@ async function checkDependencies(shouldFix) {
}
}

await checkDependencies(shouldFix);
async function checkDependencies() {
const packageJson = JSON.parse(await fs.readFile(PACKAGE_JSON_FILE));

for (const { kind, name } of getUnpinnedDependencies(packageJson)) {
console.error(
chalk.red("error"),
`"${chalk.bold.red(name)}" in "${kind}" should be pinned.`,
);
process.exitCode = 1;
}
}

if (process.argv.includes("--fix")) {
await fixDependencies();
}

await checkDependencies();

0 comments on commit 5c26e39

Please sign in to comment.