-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexamples-generator.js
79 lines (63 loc) · 2.37 KB
/
examples-generator.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
const fs = require('fs');
const path = require('path');
const watch = require('node-watch');
const {spawn} = require('child_process');
const NAME = 'examples-generator';
const DIR = path.join('src','examples');
const OUTPUT = path.join('public','examples');
const mode = process.argv[2] === 'watch' ? 'watch' : 'build';
module.exports.generateExamples = function (production){
spawn('node examples-generator.js', [production ? 'build':'watch'],{
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
if(!module.parent){
if(mode === 'build'){
generateExamples();
process.exit(0);
}
if(mode === 'watch'){
generateExamples();
watch(DIR, { recursive: true }, function(_,name) {
generateExamples(name);
});
}
}
function generateExamples(){
if(!fs.existsSync(OUTPUT)) {fs.mkdirSync(OUTPUT)};
console.log(`[${NAME}] Building examples...`);
const index = [];
const list = fs.readdirSync(DIR);
for(let filename of list){
const exPath = path.join(DIR,filename);
if(fs.lstatSync(exPath).isDirectory()){
if(!fs.existsSync(path.join(exPath,'App.xht'))) {
console.log(`[${NAME}] Skipping example ${filename}: No App.xht file`);
continue;
}
let name = getExampleName(filename);
const result ={
name: name,
files: []
}
const files = fs.readdirSync(exPath);
for(let file of files){
if(!['.ma','.html','.js','.xht','.json'].includes(path.extname(file))) continue;
let body = fs.readFileSync(path.join(exPath,file),'utf-8');
body = body.replace(/^<!--(.+)-->\s*\r*\n/,'');
result.files.push({name:file, body});
}
fs.writeFileSync(path.join(OUTPUT,`${filename}.json`),JSON.stringify(result));
index.push({name,file:filename})
console.log(`[${NAME}] - ${name} -> ${filename}.json`);
}
}
fs.writeFileSync(path.join(OUTPUT,`index.json`),JSON.stringify(index));
}
function getExampleName(filename){
const appFile = path.join(DIR,filename,'App.xht');
const appCode = fs.readFileSync(appFile,'utf-8');
appCode.replace(/^<!--(.+)-->\s*\r*\n/, (_,name) => filename = name.trim());
return filename;
}