Skip to content

Instantly share code, notes, and snippets.

@cmfsotelo
Last active May 25, 2020 14:53
Show Gist options
  • Save cmfsotelo/d09c8e35a2bde004d4ed6549d1b69b5e to your computer and use it in GitHub Desktop.
Save cmfsotelo/d09c8e35a2bde004d4ed6549d1b69b5e 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. Intended to aid androidX migration using the scripts from
'use strict';
/**
* AndroidX class mapping: https://developer.android.com/topic/libraries/support-library/downloads/androidx-class-mapping.csv
* AndroidX artifact mapping: https://developer.android.com/topic/libraries/support-library/downloads/androidx-artifact-mapping.csv
**/
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