-
Notifications
You must be signed in to change notification settings - Fork 2
/
sync-package-versions.mjs
62 lines (49 loc) · 2.13 KB
/
sync-package-versions.mjs
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
56
57
58
59
60
61
62
import fs from 'node:fs';
const rootPackage = JSON.parse(fs.readFileSync('./package.json'));
const lernaConfig = JSON.parse(fs.readFileSync('./lerna.json'));
const monorepoVersion = lernaConfig.version;
const subPackages = rootPackage.workspaces
.map((packagePath) => {
const contents = fs.readFileSync(`./${packagePath}/package.json`);
return {
path: packagePath,
package: JSON.parse(contents),
contents: String(contents),
};
});
const { workspace = true, packages = [] } = rootPackage['sync-package-versions'] ?? {};
const updatedSubPackages = subPackages.map((subPackage) => {
let contents = subPackage.contents;
if (workspace) {
contents = subPackages.reduce((contents, sub) => {
return contents.replace(
new RegExp(`"version":\\s+"([^"]+)"`, 'g'),
(matchedString, matchedVersion) => matchedString.replace(matchedVersion, monorepoVersion),
);
}, contents);
contents = subPackages.reduce((contents, sub) => {
return contents.replace(
new RegExp(`"${sub.package.name}":\\s+"([^"]+)"`, 'g'),
(matchedString, matchedVersion) => matchedString.replace(matchedVersion, monorepoVersion),
);
}, contents);
}
contents = packages.reduce((contents, packageName) => {
const packageVersion = rootPackage.dependencies?.[packageName]
?? rootPackage.peerDependencies?.[packageName]
?? rootPackage.devDependencies?.[packageName];
if (!packageVersion) return contents;
return contents.replace(
new RegExp(`"${packageName}":\\s+"([^"]+)"`, 'g'),
(matchedString, matchedVersion) => matchedString.replace(matchedVersion, packageVersion),
);
}, contents);
if (contents === subPackage.contents) {
return undefined;
}
return { ...subPackage, contents }
}).filter(Boolean);
updatedSubPackages.forEach((subPackage) => {
console.log(`Writing ${subPackage.path}/package.json`);
fs.writeFileSync(`${subPackage.path}/package.json`, subPackage.contents);
})