Skip to content

Instantly share code, notes, and snippets.

@gurunars
Created August 7, 2024 07:13
Show Gist options
  • Save gurunars/34e83672d65ddacc3d53a0e4566673d1 to your computer and use it in GitHub Desktop.
Save gurunars/34e83672d65ddacc3d53a0e4566673d1 to your computer and use it in GitHub Desktop.
Produces a yarn.lock that should be commented but does it ONLY for dev dependencies.
/** Inspired by https://classic.yarnpkg.com/blog/2016/11/24/lockfiles-for-all/
*
* Produces a yarn.lock that should be commented but does it ONLY for dev dependencies.
*/
import fs from 'node:fs'
import { execSync, exec } from 'node:child_process'
const getOutput = (cmd) => execSync(cmd).toString()
const getGitRoot = () => getOutput('git rev-parse --show-toplevel').replace('\n','')
const getWsInfo = () => JSON.parse(JSON.parse(getOutput('yarn --json workspaces info')).data)
const readJson = (path) => JSON.parse(fs.readFileSync(path).toString())
const writeJson = (path, json) => {
fs.writeFileSync(path, JSON.stringify(json, null, 2))
}
const main = async () => {
const root = getGitRoot()
const wsInfo = getWsInfo()
let devDeps = {}
const internalPackagesDeps = {}
const expandDevDeps = (more) => {
devDeps = {
...more,
...devDeps
}
}
const processPackageJson = (path) => {
if (!path) {
return
}
const pkgJson = readJson(path)
internalPackagesDeps[pkgJson.name] = pkgJson.dependencies
expandDevDeps(pkgJson.devDependencies)
}
processPackageJson(`${root}/package.json`)
for (const val of Object.values(wsInfo)) {
processPackageJson(`${root}/${val.location}/package.json`)
}
for (const name of Object.keys(devDeps)) {
expandDevDeps(internalPackagesDeps[name])
}
for (const name of Object.keys(internalPackagesDeps)) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete devDeps[name]
}
fs.rmSync(`${root}/.yarnrc`, { recursive: true, force: true })
fs.mkdirSync(`${root}/.dev-deps`, { recursive: true })
writeJson(`${root}/.dev-deps/package.json`, {
private: true,
name: 'dev-deps',
version: '0.0.1',
license: "Apache-2.0",
dependencies: devDeps
})
const child = exec('yarn --cwd=.dev-deps install')
// eslint-disable-next-line no-undef
child.stdout.on('data', console.log)
// eslint-disable-next-line no-undef
child.stderr.on('data', console.error)
await new Promise( (resolve) => {
child.on('close', resolve)
})
// This is necessary to avoid populating yarn.lock with non dev dependencies
fs.writeFileSync(`${root}/.yarnrc`, [
'--ignore-platform true',
'--frozen-lockfile true',
''
].join('\n'))
fs.copyFileSync(`${root}/.dev-deps/yarn.lock`, `${root}/yarn.lock`)
}
await main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment