Skip to content

Instantly share code, notes, and snippets.

@heyimalex
Created January 31, 2017 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save heyimalex/20310b0c8abebb353ab6c6bebad9bfc6 to your computer and use it in GitHub Desktop.
Save heyimalex/20310b0c8abebb353ab6c6bebad9bfc6 to your computer and use it in GitHub Desktop.
Hacky script to find un-imported files
const fs = require('fs');
const path = require('path');
const entry = 'src\\index.js';
const importRegex = /^import.+?from ['"]([^'"]+)['"];?\s*$/gm;
function resolve(name) {
try {
const withext = `${name}.js`
const stats = fs.accessSync(withext);
return withext;
} catch(e) {
return `${name}\\index.js`;
}
}
function getImports(f) {
const dirname = path.dirname(f);
const contents = fs.readFileSync(f, {encoding: 'utf8'});
let withoutComments = contents.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1');
return getMatches(withoutComments, importRegex, 1)
.filter(match => match.startsWith('.'))
.map(match => path.normalize(`${dirname}\\${match}`))
.map(match => resolve(match));
}
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
const imported = new Set();
function walkImports(f) {
if (imported.has(f)) return;
imported.add(f);
const imports = getImports(f);
imports.forEach(i => walkImports(i));
}
function walkSync(dir, filelist = []) {
fs.readdirSync(dir).forEach(file => {
fs.statSync(path.join(dir, file)).isDirectory()
? walkSync(path.join(dir, file), filelist)
: filelist.push(path.join(dir, file));
});
return filelist;
}
walkImports(entry);
const all = new Set(walkSync('src'));
console.log(`Unrequired files (${all.size - imported.size}/${all.size})`);
all.forEach(p => {
if (!imported.has(p)) {
console.log(p);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment