Skip to content

Instantly share code, notes, and snippets.

@Moudoux
Last active April 23, 2018 20:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Moudoux/33e26c6854f4791dd1555699d5472f08 to your computer and use it in GitHub Desktop.
Save Moudoux/33e26c6854f4791dd1555699d5472f08 to your computer and use it in GitHub Desktop.
/**
Searches for all strings that contains a color code, eg "§cTest" and replaces §c with
ChatColor.RED so the string looks like ChatColor.RED + "Test".
*/
const fs = require('fs');
const glob = require('glob');
const regex = /"[^"\\]*(?:\\.[^"\\]*)*"/gim;
const imp = 'import me.deftware.client.framework.utils.ChatColor;';
function processFile(file) {
console.log(`Processing file ${file}`);
fs.readFile(file, 'utf8', (err, data) => {
let transformedFile = data.toString(), matchArr = transformedFile.match(regex);
if (!matchArr) { return; }
matchArr.forEach((match) => {
let array = match.split(""), transformed = "", flag = false;
for (let charIndex in array) {
charIndex = parseInt(charIndex), char = array[charIndex];
if (char === "§" && array[charIndex + 1] !== " ") {
let colorCode = array[charIndex + 1], colorJavaCode = convertCodeToEnum(colorCode);
if (transformed === "\"") { transformed = ""; } else if (array[charIndex - 2] !== "§") {
transformed += "\" + ";
}
transformed += colorJavaCode + " + " + (array[charIndex + 2] === "§" ? "" : "\"");
flag = true;
} else {
if (flag) { flag = false; continue; } transformed += char;
}
}
transformedFile = transformedFile.replace(match, transformed);
});
if (!transformedFile.includes(imp) && transformedFile.includes("ChatColor.")) {
const package = transformedFile.match(/package ([A-z].*.[A-z]);/i)[0];
transformedFile = transformedFile.replace(package, package + "\n\n" + imp);
console.log(`Transformed ${file}`);
}
fs.writeFile(file, transformedFile, 'utf8', (err) => {
if (err) return console.log(err);
});
});
}
function convertCodeToEnum(code) {
switch (code) {
case "a":
return "ChatColor.GREEN";
case "c":
return "ChatColor.RED";
case "f":
return "ChatColor.WHITE";
case "n":
return "ChatColor.UNDERLINE";
case "8":
return "ChatColor.DARK_GRAY";
case "4":
return "ChatColor.DARK_RED";
case "e":
return "ChatColor.YELLOW";
case "6":
return "ChatColor.GOLD";
case "d":
return "ChatColor.LIGHT_PURPLE";
case "b":
return "ChatColor.AQUA";
case "7":
return "ChatColor.GRAY";
case "l":
return "ChatColor.BOLD";
case "r":
return "ChatColor.RESET";
default:
throw new Error(`Unknown color code: ${code}`);
}
}
glob('src/main' + '/**/*', (err, res) => res.forEach(file => processFile(file)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment