Created
September 4, 2019 17:42
-
-
Save Meandmybadself/8694cf9cb8ccac0b70c68da2365b905d to your computer and use it in GitHub Desktop.
Globally replace mass-lodash imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { exec } = require("child_process"); | |
const fs = require("fs"); | |
const script = exec( | |
"grep -lir --exclude-dir={android,ios,node_modules,coverage} \"import _ from 'lodash'\" . | grep -v .map" | |
); | |
let filesToUpdate; | |
const fixNextFile = () => { | |
if (filesToUpdate.length) { | |
const filename = filesToUpdate.shift(); | |
let fileContents = fs.readFileSync(filename, { | |
encoding: "utf8" | |
}); | |
let lodashRegex = /(_\.)([a-zA-Z]+)/g; | |
let lodashFns = []; | |
match = lodashRegex.exec(fileContents); | |
while (match != null) { | |
const wholeRef = match[0]; | |
fileContents = fileContents.replace(wholeRef, wholeRef.substr(2)); | |
lodashFns.push(match[2]); | |
match = lodashRegex.exec(fileContents); | |
} | |
lodashFns = lodashFns.filter( | |
(item, pos) => lodashFns.indexOf(item) === pos | |
); | |
if (lodashFns.length) { | |
fileContents = fileContents.replace( | |
"import _ from 'lodash'", | |
`import { ${lodashFns.join(",")} } from 'lodash'` | |
); | |
console.log(`Analysis of ${filename}`); | |
console.log(`Lodash functions detected: ${lodashFns.join(",")}`); | |
console.log("-----"); | |
fs.writeFileSync(filename, fileContents, { encoding: "utf-8" }); | |
} else { | |
console.log('Could not find lodash usage.') | |
} | |
fixNextFile(); | |
} | |
}; | |
script.stdout.on("data", function(data) { | |
filesToUpdate = data | |
.split("\n") | |
.filter(val => !!val) | |
.filter(val => !val.includes("lodash-fix")); | |
fixNextFile(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment