-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
111 lines (92 loc) · 2.81 KB
/
build.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const pegjs = require('pegjs');
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const dev = process.env.NODE_ENV !== 'production';
const pegjsOptions = {
output: 'source',
format: 'commonjs'
};
const replacements = [
{
text: [
'module.exports = {',
' SyntaxError: peg$SyntaxError,',
' parse: peg$parse',
'};'
].join('\n'),
replacement: [
'module.exports = {',
' SyntaxError: peg$SyntaxError,',
' parse: peg$parse,',
' version,',
' Node',
'};'
].join('\n')
}
];
const grammarFiles = [
{
input: './src/tex.pegjs',
output: './lib/index.js',
dependencies: {
Node: './Node.js',
version: './version.js',
prepareInput: './prepareInput.js',
merge: "./merge.js",
}
}
];
grammarFiles.forEach(file => {
pegjsOptions.dependencies = file.dependencies;
const inputPath = path.resolve(__dirname, file.input);
const inputDir = path.dirname(inputPath);
const outputPath = path.resolve(__dirname, file.output);
const outputDir = path.dirname(outputPath);
if (outputDir !== inputDir) {
prepareOutputDir(outputDir);
}
console.log('compiling>>>>>>>>>>>>>');
console.log(inputPath);
console.log();
function getParserCode () {
const grammar = fs.readFileSync(inputPath).toString('utf8');
let code = pegjs.generate(grammar, pegjsOptions);
/// some targeted replacments
for (const r of replacements) {
code = code.replace(r.text, r.replacement);
}
/// here we want to replace comment with contents file
/** # require('./preParse.js'); */
code = code.replace(/\/\*\*#\s*require\s*\(\s*(?:"|')(.*?)(?:"|')\s*\)\s*;?\s*\*\//gm, (m, g) => {
return fs.readFileSync(path.resolve(inputDir, g)).toString('utf8');
});
return code;
}
fs.writeFileSync(outputPath, getParserCode());
if (outputDir !== inputDir) {
// copy depedencies to the output directory
for (const d of Object.values(file.dependencies)) {
const p1 = path.resolve(inputDir, d);
const p2 = path.resolve(outputDir, d);
const dist = path.dirname(p2);
if (!fs.existsSync(dist)) {
fs.mkdirSync(dist, { recursive: true });
}
const readable = fs.createReadStream(p1, { encoding: 'utf-8' });
const writable = fs.createWriteStream(p2);
readable.pipe(writable);
}
}
console.log('js code:::::::::');
console.log(outputPath);
console.log();
});
function prepareOutputDir (outputDir) {
if (fs.existsSync(outputDir)) {
/// delete all the output dir content
rimraf.sync(path.resolve(outputDir, '*'));
} else {
fs.mkdirSync(outputDir, { recursive: true });
}
}