Skip to content

Instantly share code, notes, and snippets.

@bsdelf
Last active June 7, 2023 12:55
Show Gist options
  • Save bsdelf/d24465c089c6eaba7ddac0951ac5faf7 to your computer and use it in GitHub Desktop.
Save bsdelf/d24465c089c6eaba7ddac0951ac5faf7 to your computer and use it in GitHub Desktop.
yarn list direct dependencies with locked version
const path = require('path');
const exec = require('child_process').exec;
function run(command) {
return new Promise((resolve, reject) => {
exec(command, function (error, stdout, stderr) {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}
async function main() {
// get dependencies
const { dependencies } = require(path.join(process.cwd(), './package.json'));
// get locked versions
const output = await run(`yarn list --depth=0`);
const lockedPackages = new Map(
output
.split('\n')
.filter(
(line) =>
!line.startsWith('yarn list') &&
!line.includes('Done in') &&
line.length > 2
)
.map((line) => {
const pkgver = line.slice(3);
const split = pkgver.lastIndexOf('@');
const name = pkgver.slice(0, split);
const ver = pkgver.slice(split + 1);
return [name, ver];
})
);
for (const name of Object.keys(dependencies)) {
const ver = lockedPackages.get(name);
if (!ver) {
console.log(
'OOPS, locked version not found for:',
name,
dependencies[name]
);
process.exit(1);
}
console.log(`${name}: ${ver}`);
}
}
(async () => {
try {
await main();
} catch (err) {
console.log(err);
}
})();
@bsdelf
Copy link
Author

bsdelf commented Aug 14, 2020

Requirements:

  • package.json
  • yarn.lock
  • yarn

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment