forked from segabito/ZenzaWatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
122 lines (102 loc) · 2.68 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
112
113
114
115
116
117
118
119
120
var srcDir = './src';
var indexFile = 'index.js';
var outFile = 'ZenzaWatch.user.js';
function writeIfModified(file, newData, callback) {
var fs = require('fs');
try {
var oldData = fs.readFileSync(file, 'utf-8');
if (oldData === newData) {
callback('Not Modified', null);
return;
}
fs.writeFileSync(file, newData);
callback('OK', newData);
} catch(e) {
console.log('Exception: ', e);
fs.writeFileSync(file, newData);
callback('OK', newData);
}
}
function requireFile(srcDir, file) {
var fs = require('fs');
var lines = [];
var begin = false;
fs.readFileSync(srcDir + '/' + file, 'utf-8').split('\n').some(function(line) {
if (line.trim().indexOf('//===BEGIN===') === 0) {
begin = true;
return;
}
if (begin) {
if (line.trim().indexOf('//===END===') === 0) {
return true;
}
lines.push(line);
}
});
return lines.join('\n');
}
function deploy(srcFile) {
var path = require('path');
var fs = require('fs');
if (!fs.existsSync('setting.json')) {
console.log('setting.json not exist');
return;
}
var setting = JSON.parse(fs.readFileSync('setting.json', 'utf-8'));
setting.deployTo.some(function(dir) {
console.log('deploy To: ', dir);
if (!fs.existsSync(dir)) {
console.log('path not exist: ', dir);
return;
}
var destFile = dir.replace(/\/+$/, '') + '/' + path.basename(srcFile);
console.log('deploy file: ', destFile);
fs.createReadStream(srcFile).pipe(fs.createWriteStream(destFile));
});
}
function loadIndexFile(srcDir, indexFile, outFile) {
var fs = require('fs');
var lines = [];
var ver = null;
fs.readFileSync(srcDir + '/' + indexFile, 'utf-8').split('\n').some(function(line) {
if (line.match(/^(\s*)\/\/\s*@version(.*)$/)) {
if (!ver) {
ver = RegExp.$2.trim();
console.log('ver = ' + ver);
lines.push(line);
} else {
lines.push(RegExp.$1 + 'var VER = \'' + ver + '\';');
}
} else if (line.match(/^\s*\/\/@require (.+)$/)) {
console.log('require ' + RegExp.$1);
lines.push(requireFile(srcDir, RegExp.$1));
} else {
lines.push(line);
}
});
writeIfModified(outFile, lines.join('\n'), function(err, newData) {
console.log(err);
if (newData) {
deploy(outFile);
}
});
}
function build() {
loadIndexFile(srcDir, indexFile, outFile);
}
function watch(srcDir) {
var fs = require('fs');
fs.watch(srcDir, {recursive: true}, function(event, filename) {
console.log('\n\n\n', event, filename);
try {
build();
} catch(e) {
console.log(e);
}
});
}
function run() {
build();
watch(srcDir);
}
run();