Skip to content

Instantly share code, notes, and snippets.

@nfaltermeier
Last active June 20, 2018 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfaltermeier/d363b90c0c07e69a11934bc90f8f20aa to your computer and use it in GitHub Desktop.
Save nfaltermeier/d363b90c0c07e69a11934bc90f8f20aa to your computer and use it in GitHub Desktop.
/* Recursively fixes react/jsx-curly-brace-presence ex. changes <div id={'container'}> to <div id="container"> */
const fs = require('fs');
const path = require('path');
// List all files in a directory in Node.js recursively in a synchronous fashion
const walkSync = (dir, fileExt, filelist = []) => {
fs.readdirSync(dir).forEach((file) => {
/* eslint-disable no-param-reassign */
if (fs.statSync(path.join(dir, file)).isDirectory() && file !== 'node_modules') {
filelist = walkSync(path.join(dir, file), fileExt, filelist);
} else if (path.extname(file) === fileExt) {
filelist = filelist.concat(path.join(dir, file));
}
/* eslint-enable no-param-reassign */
});
return filelist;
};
const searchDirectory = process.argv[2];
if (!fs.statSync(searchDirectory).isDirectory()) {
console.error(`'${searchDirectory}' is not a directory!`);
process.exit(1);
}
if (!searchDirectory[searchDirectory.length - 1] === path.sep) {
console.error('Directory to search must end in \'/\'');
process.exit(1);
}
const extToFind = process.argv[3] || '.jsx';
if (!process.argv[3]) {
console.warn('No extension specified, defaulting to \'.jsx\'');
}
const files = walkSync(searchDirectory, extToFind);
const regex = /={'(.*?)'}/;
const findAndReplaceFromRegex = (match, data) => {
let changed = false;
const newData = data.replace(`={'${match[1]}'}`, `="${match[1]}"`);
changed = true;
return { newData, changed };
};
function processFile(srcPath) {
fs.readFile(srcPath, 'utf8', (err, data) => {
if (err) throw err;
let writeableData = data;
let changed = false;
let match = writeableData.match(regex);
let result;
while (match) {
result = findAndReplaceFromRegex(match, writeableData);
changed = result.changed || changed;
writeableData = result.newData;
match = writeableData.match(regex);
}
if (changed) {
fs.writeFile(srcPath, writeableData, (error) => {
if (error) throw error;
});
}
});
}
files.forEach((file) => {
processFile(file);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment