Skip to content

Instantly share code, notes, and snippets.

@sandfox
Last active April 11, 2018 18:42
Show Gist options
  • Save sandfox/148e977651d60f66498d19c4bbb4f5a6 to your computer and use it in GitHub Desktop.
Save sandfox/148e977651d60f66498d19c4bbb4f5a6 to your computer and use it in GitHub Desktop.
one off script to mixup lodash imports in a project
#! /usr/bin/env node
/**
* ./fix-lodash-imports path/to/file.js
*/
const fs = require('fs');
const loadFile = filepath => fs.readFileSync(filepath, 'utf8');
const writeFile = (filepath, data) => fs.writeFileSync(filepath, data, 'utf8');
const importRegex = /^import ([a-zA-Z]+) from 'lodash\/fp\/\1';$/;
const main = argv => {
const target = argv[2];
const file = loadFile(target);
const lines = file.split('\n');
const matches = lines.map((data, index) => [index, data]).filter(([, line]) => importRegex.test(line));
if (matches.length < 1) {
console.log(`0 matches found in ${target}`);
return;
}
// create list of sub modules
const subModules = matches.map(([, data]) => importRegex.exec(data)[1]);
// create new import statement
const newImport = `import { ${subModules.join(', ')} } from 'lodash/fp';`;
// naughttttyyy in place splicing
// replace first import with our shiny new one
const firstMatch = matches[0];
if (firstMatch) {
const pos = firstMatch[0];
lines.splice(pos, 1, newImport);
}
// delete any remaning matches
const remaning = matches.slice(1);
// reverse otherwise our match offsets go wrong with each removal
remaning.reverse().forEach(m => lines.splice(m[0], 1));
writeFile(target, lines.join('\n'));
console.log(`${subModules.length} imports splatted down (${remaning.length}--) in ${target}`);
};
main(process.argv);
git grep -l "[a-z] from 'lodash/fp/[a-zA-Z]" | while read line; do ./fix-lodash-imports "$line" ; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment