Skip to content

Instantly share code, notes, and snippets.

@ox
Created December 21, 2018 18:00
Show Gist options
  • Save ox/5f57707f26ce3d86b9ff407a1b4e9e2f to your computer and use it in GitHub Desktop.
Save ox/5f57707f26ce3d86b9ff407a1b4e9e2f to your computer and use it in GitHub Desktop.
Inverted dep tree generator. Nodes higher up on the tree are dependencies of their child nodes.
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const {spawnSync} = require('child_process');
const deps = {};
const dependedBy = {};
function getDependencies(packageJsonFile) {
assert(packageJsonFile);
const pkg = JSON.parse(fs.readFileSync(packageJsonFile));
const {dependencies = {}} = pkg;
const ret = {};
Object.entries(dependencies).forEach(([name, location]) => {
if (location.includes('file:')) {
ret[name] = deps[name] || {};
dependedBy[name] = dependedBy[name] || {};
dependedBy[name][pkg.name] = dependedBy[pkg.name] || {};
}
});
deps[pkg.name] = ret;
}
function sh(command) {
const parts = command.split(' ').map((part) => part.trim()).filter((part) => !!part);
const prog = parts[0];
const args = parts.splice(1);
console.log(`$ ${prog} ${args.join(' ')}`);
const {error, status, stdout, stderr} = spawnSync(prog, args, {shell: true});
if (error) {
console.error(stderr.toString());
throw error;
}
if (status !== 0) {
console.error(stderr.toString());
throw new Error(`${prog} exited with code ${status}`);
}
const logout = stdout.toString().trim();
const errout = stderr.toString().trim();
return logout !== '' ? logout : errout;
}
const rootDir = sh('git rev-parse --show-toplevel');
const ignore = '! -path "*node_modules*" ! -path "*dist*" ! -path "*assets*"';
const packages = sh(`find ${rootDir} -name "package.json" ${ignore}`)
.split('\n').filter((x) => !!x);
packages.forEach(getDependencies);
console.log(JSON.stringify(dependedBy, null, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment