Skip to content

Commit 294c0f6

Browse files
committed
chore: add --fix option to lint-versions.js
1 parent 3350afa commit 294c0f6

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

scripts/lint-versions.js

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env node
2-
const { readdirSync, existsSync, readFileSync } = require('fs');
2+
const { readdirSync, existsSync, readFileSync, writeFileSync } = require('fs');
33

44
const getDirectories = source =>
55
readdirSync(source, { withFileTypes: true })
@@ -32,11 +32,11 @@ function readPackageJsonNameVersion(filePath) {
3232
}
3333

3434
function compareVersions(versionsA, versionsB) {
35-
let output = '';
35+
let output = {};
3636
const newVersions = { ...versionsA };
3737
Object.keys(versionsB).forEach(dep => {
3838
if (versionsA[dep] && versionsB[dep] && versionsA[dep] !== versionsB[dep]) {
39-
output += ` - "${dep}" should be "${versionsA[dep]}" but is "${versionsB[dep]}"\n`;
39+
output[dep] = [versionsA[dep], versionsB[dep]];
4040
}
4141
if (!newVersions[dep]) {
4242
newVersions[dep] = versionsB[dep];
@@ -58,20 +58,44 @@ for (const subPackage of getDirectories('./packages')) {
5858
currentVersions = { ...currentVersions, ...readPackageJsonNameVersion(filePath) };
5959
}
6060

61+
const fixes = new Map();
62+
6163
// lint all versions in packages
6264
for (const subPackage of getDirectories('./packages')) {
6365
const filePath = `./packages/${subPackage}/package.json`;
6466
const subPackageVersions = readPackageJsonDeps(filePath);
6567
const { output, newVersions } = compareVersions(currentVersions, subPackageVersions);
6668
currentVersions = { ...newVersions };
67-
if (output) {
69+
const entries = Object.entries(output);
70+
if (entries.length) {
71+
fixes.set(filePath, output);
6872
console.log(`Version mismatches found in "${filePath}":`);
69-
console.log(output);
73+
console.log(
74+
entries.reduce(
75+
(acc, [dep, [should, is]]) => `${acc} - "${dep}" should be "${should}" but is "${is}"\n`,
76+
'',
77+
),
78+
);
7079
console.log();
7180
endReturn = 1;
7281
}
7382
}
7483

84+
function fixJSON(filePath, changes) {
85+
const json = JSON.parse(readFileSync(filePath, 'utf8'));
86+
for (const [dep, [should]] of Object.entries(changes)) {
87+
json.dependencies[dep] = should;
88+
}
89+
writeFileSync(filePath, JSON.stringify(json, null, 2));
90+
}
91+
92+
if (fixes.size && process.argv.includes('--fix')) {
93+
for (const [filePath, changes] of fixes) {
94+
fixJSON(filePath, changes);
95+
}
96+
console.log('package.json files updated, run `yarn`');
97+
}
98+
7599
if (endReturn === 0) {
76100
console.log('All versions are aligned 💪');
77101
}

0 commit comments

Comments
 (0)