Skip to content

Instantly share code, notes, and snippets.

@rndD
Last active October 27, 2022 22:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rndD/044b6a00715710cdabf08d70452dbedb to your computer and use it in GitHub Desktop.
Save rndD/044b6a00715710cdabf08d70452dbedb to your computer and use it in GitHub Desktop.
Script replaces all deps versions in all `package.json`s from `yarn.lock` (yarn version 3). It works with yarn monorepo setup. Run: `yarn add @yarnpkg/parsers && npx ts-node yarn-lock-versions-to-package.ts`
import fs from 'fs';
import { parseSyml } from '@yarnpkg/parsers';
import path from 'path';
let file = fs.readFileSync('yarn.lock', 'utf8');
let json = parseSyml(file);
// function make map with all packages and their versions.
// Json format:
// 'zen-observable-ts@npm:^1.2.0': {
// version: '1.2.3',
// resolution: 'zen-observable-ts@npm:1.2.3',
// dependencies: { 'zen-observable': '0.8.15' },
// checksum: '0548b555c67671f1240fb416755d2c27abf095b74a9e25c1abf23b2e15de40e6b076c678a162021358fe62914864eb9f0a57cd65e203d66c4988a08b220e6172',
// languageName: 'node',
// linkType: 'hard'
// },
const packagesInYarn = new Map();
for (const key of Object.keys(json)) {
const packageNVersions = key.split(',');
packageNVersions.forEach((packageNVersion) => {
packageNVersion = packageNVersion.trim();
const [packageName, version] = packageNVersion.split('@npm:');
const resolvedVersion = json[key].version;
packagesInYarn.set(`${packageName}|${version}`, resolvedVersion);
});
}
function findDivergeVersionsInPackageJson(rootDir: string) {
// read all package json in root except node_modules
const files = fs.readdirSync(rootDir);
for (const file of files) {
const filePath = path.join(rootDir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory() && file !== 'node_modules') {
findDivergeVersionsInPackageJson(filePath);
} else if (stat.isFile() && file === 'package.json') {
const packageJson = fs.readFileSync(filePath, 'utf8');
const parsedPackageJson = parseSyml(packageJson);
const {
dependencies: deps,
} = parsedPackageJson;
let changed = false;
// iterate over dependencies and peerDependencies
if (deps) {
Object.keys(deps).forEach((dep) => {
if (packagesInYarn.has(`${dep}|${deps[dep]}`)) {
const resolvedVersion = packagesInYarn.get(`${dep}|${deps[dep]}`);
if (resolvedVersion !== deps[dep]) {
deps[dep] = resolvedVersion;
changed = true;
}
}
});
}
if (changed) {
fs.writeFileSync(
filePath,
JSON.stringify(parsedPackageJson, null, 2) + `\r`,
);
}
}
}
}
findDivergeVersionsInPackageJson(process.cwd());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment