LemonJS/main.js

95 lines
2.7 KiB
JavaScript

/**
* Created by Aleksey Chichenkov <a.chichenkov@initi.ru> on 1/28/19.
*/
var js_beautify = require("./libs/js-beautifier");
var args = require("./libs/args-parser")(process.argv);
var fs = require("fs");
var exec = require('child_process').exec;
var config;
if(args["c"] !== undefined) {
config = require("./" + args["c"]);
} else {
config = require("./config.js");
}
var program_path = config.lemon_bin;
var lemon_flags = config.flags;
var input_path = config.input_path;
var output_path = config.output_path;
var file_name = config.file_name;
var fn_y = file_name + ".y";
var fn_js = file_name + ".js";
var fn_out = file_name + ".out";
var temp_fn_y = "temp_" + "file_name" + ".y";
var temp_fn_js = "temp_" + "file_name" + ".js";
var temp_fn_out = "temp_" + "file_name" + ".out";
var update_parser_y = function () {
var source_parser_y = fs.readFileSync(input_path + fn_y, "utf8");
source_parser_y = source_parser_y.replace(/&&.*?REPLACER\{(.*?)\}&&/gm, function (match, file_path, offset, string) {
return fs.readFileSync("./" + input_path + file_path, "utf8");
});
fs.writeFileSync(input_path + temp_fn_y, source_parser_y);
};
var post_process_parser = function () {
var out_js = fs.readFileSync(input_path + temp_fn_js, "utf8");
if (args["t"] !== undefined) {
switch (args["t"]) {
case "web":
if(!fs.existsSync(config.require_template)){
throw "Not exist file: " + config.require_template;
}
var template = fs.readFileSync(config.require_template, "utf8");
out_js = template.replace(/<%%PARSER%%>/gm, out_js);
break;
case "node":
out_js += "\n\n module.exports = LemonJS;";
break;
}
}
out_js = js_beautify(out_js, {
indent_size: 4,
indent_char: ' ',
preserve_newlines: true,
space_after_anon_function: true,
keep_array_indentation: false,
braces_on_own_line: false
});
if(!fs.existsSync(output_path)){
fs.mkdirSync(output_path);
}
fs.writeFileSync(output_path + fn_js, out_js);
var temp_parser_out = fs.readFileSync(input_path + temp_fn_out, "utf8");
fs.writeFileSync(output_path + fn_out, temp_parser_out);
};
var start = function () {
update_parser_y();
exec(program_path + " " + input_path + temp_fn_y + " " + lemon_flags, function(err, stdout, stderr) {
err && console.log("ERROR: ", err);
err && process.exit(1);
post_process_parser();
fs.unlinkSync(input_path + temp_fn_y);
fs.unlinkSync(input_path + temp_fn_js);
fs.unlinkSync(input_path + temp_fn_out);
});
};
start();