buffer-apg-js
Version:
JavaScript APG, an ABNF Parser Generator
48 lines (41 loc) • 1.6 kB
JavaScript
// Reads a JSON file of color and class names.
// Outputs a LESS file defining variable color and class names.
module.exports = function (inFile, outFile) {
"use strict";
function capFirst(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getFileExtension(filename) {
return filename.slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2);
}
let fs = require("fs");
try {
/* validate arguments */
if (!inFile) {
throw new Error("missing input JSON file (name.json)");
}
if (getFileExtension(inFile) !== "json") {
throw new Error("input JSON file (" + inFile + ") must have .json extension");
}
if (!outFile) {
throw new Error("missing output LESS file (name.less)");
}
if (getFileExtension(outFile) !== "less") {
throw new Error("output LESS file (" + outFile + ") must have .less extension");
}
let json = fs.readFileSync(inFile, "utf8");
let obj = JSON.parse(json);
/* generate the LESS file */
let less = "/* This file automatically generated by jsonToless() and LESS. */\n";
for (let key in obj.colors) {
less += "@color" + capFirst(key) + ": " + obj.colors[key] + ";\n";
}
for (let key in obj.classes) {
less += "@class" + capFirst(key) + ": " + obj.classes[key] + ";\n";
}
fs.writeFileSync(outFile, less);
} catch (e) {
console.log("jsonToLESS.js: EXCEPTION: \n");
console.log(e.message);
}
};