Skip to content

Instantly share code, notes, and snippets.

@cmfsotelo
Created May 24, 2020 23:32
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 cmfsotelo/5dff731050569b78083a0aae7dceab19 to your computer and use it in GitHub Desktop.
Save cmfsotelo/5dff731050569b78083a0aae7dceab19 to your computer and use it in GitHub Desktop.
This simple script receives a pattern and a csv file with key,value lines and replaces all keys in all files with the respective values.
'use strict';
var fs = require('fs'),
lineReader = require('n-readlines'),
glob = require('glob');
/**
* Expects a csv with 2 columns in the format key,value on each line.
* @param csvFile
* @returns Returns an object with properties keys and values value
*/
function parseKeyPairCsv(csvFile) {
const map = {};
let line;
const liner = new lineReader(csvFile);
while (line = liner.next()) {
const splitted = line.toString().split(",")
map[splitted[0]] = splitted[1];
}
return map;
}
function updateFiles(file, mapping, confirmDeletion) {
let originalFile = fs.readFileSync(file, 'utf-8');
let finalFile = originalFile;
for (let key in mapping) {
finalFile = finalFile.replace(key, mapping[key]);
}
if (originalFile != finalFile) {
if (confirmDeletion === "-f") {
fs.writeFileSync(file, finalFile, 'utf-8');
console.log(`Rewriting ${file}`);
} else {
console.log(`Would rewrite ${file}`);
}
return 1;
} else {
return 0;
}
}
function updateFile(pattern, mappingFile, confirmDeletion) {
const mapping = parseKeyPairCsv(mappingFile)
glob(pattern, {}, (err, files) => {
let count = 0
files.forEach(function (file) {
count += updateFiles(file, mapping, confirmDeletion)
})
console.log(`Affected files: ${count}`)
});
}
let myArgs = process.argv.slice(2);
if (myArgs.length > 1) {
updateFile(myArgs[0], myArgs[1], myArgs[2])
} else {
console.error("Sample usage: node replaceOnFiles.js androidApp/**/*.java mappingFile.csv")
console.error("Command needs a file filter in which to replace the mappings from the csv file on the second argument")
process.exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment