Skip to content

Instantly share code, notes, and snippets.

@leggsimon
Last active March 27, 2017 00:26
Show Gist options
  • Save leggsimon/79013a27aa6a4280f7b6f710b75b82e9 to your computer and use it in GitHub Desktop.
Save leggsimon/79013a27aa6a4280f7b6f710b75b82e9 to your computer and use it in GitHub Desktop.
A shell script that finds files in a specified directory and returns the instances it is used within another directory. Used to find files that weren't ever required in another file in a repository
#!/usr/bin/env node
const shell = require('child_process');
const path = require('path')
if (process.argv.length <= 3) {
console.log(`Usage: ${__filename} path/to/directory/with/needles path/to/haystack`);
process.exit(-1);
}
const filesToCheck = process.argv[2];
const haystack = process.argv[3];
const toShortname = filePath => path.parse(filePath).name;
shell.exec(`find ${filesToCheck} -type f`, (error, stdout) => {
const needles = stdout.split('\n')
.filter(n => n)
const notUsed = [];
Promise.all(
needles.map(file => {
const command = `grep -Rn --exclude-dir={node_modules,.git,public,views} "${toShortname(file)}'" ${haystack}`;
return new Promise((resolve) => {
shell.exec(command, (error, stdout) => {
const results = stdout.split('\n')
.filter(line => line.includes('import') || line.includes('require'))
.filter(n => n)
.map(line => line
.split(':')
.splice(0, 2)
.join(':')
)
console.log('\x1b[36m', file, '\x1b[0m');
if (!results.length) {
notUsed.push(file)
console.log('\x1b[31m', 'Not Found', '\x1b[0m')
} else {
results.forEach(match => console.log(match))
}
console.log('\n');
resolve(stdout)
});
})
})
)
.then(() => {
if (notUsed.length) {
console.log('\x1b[31m', 'These files were not used anywhere', '\x1b[0m')
notUsed.forEach(file => console.log(file))
} else {
console.log('\x1b[32m', 'All good!', '\x1b[0m')
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment