[scripts] Create internal-dependency-trace script package (#9783)

Adds a new package under `scripts/internal-dependency-trace` that can be used to generate a rendering of any internal file dependency graph.

Default configured to generate the directed dependency graph of `packages/cli/src/index.ts`
This commit is contained in:
Ethan Arrowood
2023-04-10 15:01:17 -06:00
committed by GitHub
parent 8634f9cd7e
commit 136077ab6f
10 changed files with 784 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
const path = require('path');
const fs = require('fs');
const { stripRootDirectory } = require('./root-directory');
const addExtension = filePath => {
if (filePath.endsWith('.json')) {
return filePath;
}
if (!filePath.endsWith('.ts')) {
try {
fs.statSync(filePath);
filePath += '/index.ts';
} catch (e) {
try {
fs.statSync(filePath + '.ts');
filePath += '.ts';
} catch (e2) {
fs.statSync(filePath + '.js');
filePath += '.js';
}
}
}
return filePath;
};
function trace(filePath) {
const files = {};
function _trace(_filePath) {
if (_filePath.endsWith('.json') || files[stripRootDirectory(_filePath)]) {
return;
}
const source = fs.readFileSync(_filePath, 'utf-8');
const matches = source.matchAll(/(require|from).+["'].*\n/g);
let localDepPaths = [...matches]
.map(a => a[0])
.map(b => /["'](\..*)["']/.exec(b))
.filter(c => c != null)
.map(d => addExtension(path.resolve(path.dirname(_filePath), d[1])));
// de-duplicate
localDepPaths = new Set(localDepPaths);
localDepPaths = [...localDepPaths];
files[stripRootDirectory(_filePath)] = {
dependsOn: localDepPaths.map(stripRootDirectory),
};
for (const localDepPath of localDepPaths) {
_trace(localDepPath);
}
}
_trace(filePath);
return files;
}
module.exports = { trace };