-
Notifications
You must be signed in to change notification settings - Fork 1
/
hcliubuild.js
executable file
·585 lines (536 loc) · 15.7 KB
/
hcliubuild.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
var url = require('url');
var http = require('http');
var fs = require('fs');
var child_process = require('child_process');
var crypto = require('crypto');
var readline = require('readline');
var appVer = '1.0';
var jsCompiler = '';
var cssCompiler = '';
var tempFolder = '_tmp';
var logFile = 'build.log';
var confFile = 'build.conf';
var settingFile = 'setting.conf';
var conf = {};
var setting = {};
var ver = {};
var verFile = 'ver.conf';
var clearOldFile = true;
var useLock = false;
var lastver="";
var errCount = 0;
function diffItem(m,dt){
this.isMatch=m;
this.data=dt;
}
var log = function (str) {
console.log(str);
fs.appendFileSync(logFile, str + '\r\n');
};
var err = function (str) {
log('[error]: ' + str);
pause();
}
var pause = function () {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
setTimeout(function () {
rl.question('\n================================================================\nSOMTHING IS ERROR !!! check the logs and press any key to exit!\n================================================================\n', function () {
process.exit();
});
}, 1500);
};
var oldFileChecksum = function (file,chunkSize) {
var txt = fs.readFileSync(file, {
encoding: 'utf-8'
});
var checksumArray={};
var currentIndex=0;
var len=txt.length;
var chunkNo=0;
while(currentIndex<len) {
var chunk=txt.substr(currentIndex,chunkSize);
var chunkMd5=getMd5ByText(chunk);
checksumArray[chunkMd5]=chunkNo;
currentIndex=currentIndex+chunkSize;
chunkNo++;
}
return checksumArray;
};
var getMd5ByText = function (s) {
var md5sum = crypto.createHash('md5');
md5sum.update(s);
return md5sum.digest('hex');
};
var checkMatchIndex=function(chunkMd5,checksumArray){
var chunkNo=checksumArray[chunkMd5];
if(typeof(chunkNo)==undefined){
return -1;
}
else{
return chunkNo;
}
}
var doExactNewData=function( incDataArray,data){
var di = new diffItem(false,data);
incDataArray.push(di);
}
var doExactMatch=function( incDataArray,chunkNo) {
// 写块匹配
var di = new diffItem(true,chunkNo);
incDataArray.push(di);
}
var searchChunk=function(newFile,checksumArray,chunkSize){
var incDataArray=new Array();
//chunk
var buffer=null;
//用于缓存两个匹配块之间的新增数据
var outBuffer ="";
// 指向块后的第一个字符
var currentIndex = 0;
var strInput = fs.readFileSync(newFile, {
encoding: 'utf-8'
});
var tLen=strInput.length;
while(currentIndex<=tLen){
var endIndex=currentIndex+chunkSize;
if(endIndex>tLen){
endIndex=tLen;
}
buffer=strInput.substring(currentIndex,endIndex);
var chunkMd5=getMd5ByText(buffer);
var matchTrunkIndex=checkMatchIndex(chunkMd5,checksumArray);
//若果是最后一个
if(endIndex>tLen-1){
//先把新块压入队列
if(outBuffer.length>0&&!outBuffer==""){
doExactNewData(incDataArray,outBuffer);
outBuffer="";
}
if(buffer.length>0&&!buffer==""){
doExactNewData(incDataArray,buffer);
}
currentIndex=currentIndex+chunkSize;
}
//如果找到匹配块
else if(matchTrunkIndex>=0){
//先把新块压入队列
if(outBuffer.length>0&&!outBuffer==""){
doExactNewData(incDataArray,outBuffer);
outBuffer="";
}
doExactMatch(incDataArray, matchTrunkIndex);
currentIndex=currentIndex+chunkSize;
}
else{
outBuffer=outBuffer+strInput.substring(currentIndex,currentIndex+1);
currentIndex++;
}
}
return incDataArray;
};
var getFileInfo = function (path){
var pathArr = path.split('/');
var name = pathArr.pop();
var namearr = name.split('.');
var extName = namearr.pop();
var fileName = namearr.join('.');
var filePath = pathArr.join('/');
var verArr=fileName.split('-');
var ver=verArr.pop();
return {
filePath: filePath || '.',
fileName: fileName,
extName: extName,
ver:ver,
fullName: fileName + '.' + extName
};
};
var makeIncDataFile=function(oldFile,newFile,chunkSize){
var resultFile={};
var oInfo=getFileInfo(oldFile);
var nInfo=getFileInfo(newFile);
var incFile=oInfo.filePath+"/"+oInfo.fileName.replace(oInfo.ver,oInfo.ver+"_"+nInfo.ver)+"."+oInfo.extName;
resultFile.file=incFile.replace("./release/","");
resultFile.chunkSize=chunkSize;
// var oldChecksum=oldFileChecksum("F:/nginx-1.5.1/html/client-1000.js");
// var diffArray=searchChunk("F:/nginx-1.5.1/html/server.js",oldChecksum);
var oldChecksum=oldFileChecksum(oldFile,chunkSize);
var diffArray=searchChunk(newFile,oldChecksum,chunkSize);
var arrayData ="";
// var newData="";
var lastitem=null;
var matchCount=0;
var size=diffArray.length;
var strDataArray=new Array();
for(var i=0;i<size;i++){
var item=diffArray[i];
if (item.isMatch) {
//如果第一个匹配,
if(lastitem==null||!lastitem.isMatch){
arrayData="["+item.data+",";
matchCount=1;
}
else if(lastitem.isMatch&&lastitem.data+1==item.data){
matchCount++;
}
else if(lastitem.isMatch&&lastitem.data+1>item.data){
arrayData+=matchCount+"]";
strDataArray.push(JSON.parse(arrayData));
arrayData="["+item.data+","
matchCount=1;
}
if(i==(size-1)){
arrayData+=matchCount+"]";
strDataArray.push(JSON.parse(arrayData));
arrayData="";
}
} else {
if(matchCount>0){
arrayData+=matchCount+"]";
console.log(arrayData);
strDataArray.push(JSON.parse(arrayData));
arrayData="";
matchCount=0;
}
//"
var data=item.data;
//data=data.replace(/"/g, "&jsquot&&&;");
strDataArray.push(data);
//strData+="\"" +data +"\",";
}
lastitem=item;
}
// strData=strData.substr(0,strData.length-1);
// strData+="]";
// console.log("xxxsadfadfa"+strData);
resultFile.data=strDataArray;
return resultFile;
}
var log = function (str) {
console.log(str);
fs.appendFileSync(logFile, str + '\r\n');
};
var err = function (str) {
errCount ++;
log('[error]: ' + str);
pause();
}
var clearLog = function () {
fs.appendFileSync(logFile, '', {flag:'w'});
};
var pause = function () {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
setTimeout(function () {
rl.question('\n================================================================\nSOMTHING IS ERROR !!! check the logs and press any key to exit!\n================================================================\n', function () {
process.exit();
});
}, 1500);
};
var toJson = function (str) {
return new Function('return (' + str +')')();
};
var readConf = function (file) {
var txt = fs.readFileSync(file, {
encoding: 'utf8'
});
if (!txt) {
txt = '{}';
}
return toJson(txt);
};
//var getFileInfo = function (path){
// var pathArr = path.split('/');
// var name = pathArr.pop();
// var namearr = name.split('.');
// var extName = namearr.pop();
// var fileName = namearr.join('.');
// var filePath = pathArr.join('/');
// return {
// filePath: filePath || '.',
// fileName: fileName,
// extName: extName,
// fullName: fileName + '.' + extName
// };
//};
var getMd5 = function (path) {
var s = fs.readFileSync(path);
var md5sum = crypto.createHash('md5');
md5sum.update(s);
return md5sum.digest('hex');
};
var getVer = function () {
return ver.ver;
};
var fixZero = function (n, l) {
var i = 0;
var z = '';
l = Math.max(('' + n).length, l);
for (i=0; i<l; i++) {
z += '0';
}
z += n;
return z.slice(-1*l);
}
var updateVer = function () {
var v = ver.ver;
var per = fixZero(parseInt(ver.personalFlag || '0'), 2);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var today = now.getFullYear() + fixZero(month, 2) + fixZero(day, 2);
var vDate,vCount,newVer;
var s;
if (!v) {
v = today + per + '001';
}
vDate = v.slice(0, 8);
vCount = parseInt(v.slice(-3));
if (vDate != today) {
vCount = 0;
}
vCount = fixZero(++vCount, 3);
newVer = today + per + vCount;
ver.ver = newVer;
log('current Version: ' + newVer);
s = fs.readFileSync(verFile, {encoding: 'utf8'});
s = s.replace(/[\"\']?ver[\"\']?:\s*[\"\']?\d*[\"\']?/,'ver: \'' + newVer + '\'');
fs.writeFileSync(verFile, s);
}
var downloadFile = function (fileUrl, cb) {
var fileUrlObj = url.parse(fileUrl);
var opts = {
host: fileUrlObj.host,
port: fileUrlObj.port || 80,
path: fileUrlObj.pathname
};
var fileInfo = getFileInfo(fileUrlObj.pathname);
var req = http.get(fileUrl, function(res) {
res.on('data', function (chunk) {
var tmp = tempFolder + '/' + fileInfo.fileName + '_' + new Date().getTime() + '.' + fileInfo.extName;
fs.writeFileSync(tmp, chunk);
cb && cb(tmp);
});
});
req.on('error', function(e) {
err('problem with request: ' + e.message);
});
};
var copyFile = function (filePath, cb) {
var s = fs.readFileSync(filePath);
var fileInfo = getFileInfo(filePath);
var tmp = tempFolder + '/' + fileInfo.fileName + '_' + new Date().getTime() + '.' + fileInfo.extName;
fs.appendFileSync(tmp, s);
cb && cb(tmp);
};
var combineFiles = function (target, files, cb) {
var newFiles = [];
var len = files.length;
var targetInfo = getFileInfo(target);
var processNextFile = function (f) {
var file = files.shift();
if (f) {
newFiles.push(f);
}
if (!file) {
return;
}
if (/^http:\/\//.test(file)) {
log('download ' + file);
downloadFile(file, processNextFile);
}else {
log('copy ' + file);
copyFile(file, processNextFile);
}
};
var checkLen = function () {
var s = '';
var tmp = '';
var targetFileInfo;
var fileList;
var reg;
var realTarget
if (newFiles.length == len) {
newFiles.forEach(function (itm) {
s += fs.readFileSync(itm);
});
tmp = tempFolder + '/' + targetInfo.fileName + '_' + new Date().getTime() + '.' + targetInfo.extName;
fs.writeFileSync(tmp, s);
realTarget = target;
if (/{ver}/.test(target)) {
realTarget = target.replace('{ver}', getVer());
}
if (/{md5}/.test(target)) {
realTarget = target.replace('{md5}', getMd5(tmp));
}
if (clearOldFile) {
targetFileInfo = getFileInfo(realTarget);
fileList = fs.readdirSync(targetFileInfo.filePath);
fileList.forEach(function (itm) {
reg = new RegExp(target.replace('{ver}','\\d{13}').replace('{md5}', '[a-z\\d]{32}'));
if (reg.test(targetFileInfo.filePath + '/' + itm)){
log('delete file ' + targetFileInfo.filePath + '/' + itm);
fs.unlinkSync(targetFileInfo.filePath + '/' + itm);
}
});
}
cb && cb(tmp, realTarget);
}else {
setTimeout(checkLen, 100);
}
};
processNextFile();
checkLen();
};
var buildJs = function (target, files, cb) {
combineFiles(target, files, function (tmp, targetPath) {
var cmd = '';
cmd = 'java -jar ' + jsCompiler + ' --charset utf8 --language_in ECMASCRIPT5 --compilation_level SIMPLE_OPTIMIZATIONS --js ' + tmp + ' --js_output_file ' + targetPath;
log(cmd);
child_process.exec(cmd, function (error, stdout, stderr) {
if (error !== null) {
err('exec error ' + error);
}
cb && cb(getFileInfo(targetPath).fullName);
});
});
};
var buildCss = function (target, files, cb) {
combineFiles(target, files, function (tmp, targetPath) {
var cmd = '';
cmd = 'java -jar ' + cssCompiler + ' --type css --charset utf-8 -o ' + targetPath + ' ' + tmp;
log(cmd);
child_process.exec(cmd, function (error, stdout, stderr) {
if (error !== null) {
err('exec error: ' + error);
}
cb && cb(getFileInfo(targetPath).fullName);
});
});
};
//替换版本
var replaceFile = function (replacements, releasedFile) {
//var s = '',reg;
//([].concat(replacements)).forEach(function (itm) {
// s = fs.readFileSync(itm.file,{encoding: itm.encoding || 'utf8'});
//reg = new RegExp(itm.target || '', 'g');
//if (reg.test(s)){
//s = s.replace(lastver, ver.ver);
//fs.writeFileSync(itm.file,s,{encoding: itm.encoding || 'utf8'});
//}else{
// log('regexp not match in the file ' + itm.file + ' \'' + itm.target + '\'')
//}
//});
};
var buildIncFile=function(releasedFile,chunkSize){
//如有有老版本
var oldFile="./release/"+releasedFile.replace(ver.ver,lastver);
fs.exists(oldFile, function(exists) {
if (exists) {
var resultFile=makeIncDataFile(oldFile,"./release/"+releasedFile,chunkSize);
var incFileName="./release/"+releasedFile.replace(ver.ver,lastver+"_"+ver.ver);
console.log(resultFile);
fs.writeFileSync(incFileName, JSON.stringify(resultFile));
}
});
}
var build = function (target, files, replacements,chunkSize) {
log('build ' + target);
if (!target) {
err('target file is empty!');
return;
}
if ((!files) || (files.length == 0)) {
err('source file can not be empty! (' + target + ')');
return;
}
if (!replacements) {
replacements = [];
}
if (/\.js$/.test(target)) {
buildJs(target, files, function (releasedFile) {
replaceFile(replacements, releasedFile);
if(typeof(chunkSize)!="undefined"&&chunkSize>0){
//建增量文件
buildIncFile(releasedFile,chunkSize);
}
});
return;
}
if (/\.css$/.test(target)) {
buildCss(target, files, function (releasedFile) {
replaceFile(replacements, releasedFile);
if(typeof(chunkSize)!="undefined"&&chunkSize>0){
//建增量文件
buildIncFile(releasedFile,chunkSize);
}
});
return;
}
err('error: file type must be "js" or "css"!');
};
var fetchConf = function (conf) {
var k;
for(k in conf) {
if (conf.hasOwnProperty(k)) {
build(k, (conf[k] || {}).files, (conf[k] || {}).replace,(conf[k] || {}).chunkSize);
}
}
};
var init = function () {
var dirList;
settingFile = process.argv[1].replace(/[^\\]*$/, 'setting.conf');
verFile = process.argv[3] || 'ver.conf';
confFile = process.argv[2] || 'build.conf';
conf = readConf(confFile);
setting = readConf(settingFile);
ver = readConf(verFile);
//用一个变量保存上次的版本
lastver=ver.ver;
clearLog();
clearOldFile =false;
updateVer();
if (setting.temp) {
tempFolder = setting.temp;
}
tempFolder = process.argv[1].replace(/[^\\]*$/, tempFolder);
if (fs.existsSync(tempFolder)) {
dirList = fs.readdirSync(tempFolder);
dirList.forEach(function(item){
fs.unlinkSync(tempFolder + '/' + item)
});
}else {
fs.mkdirSync(tempFolder);
}
jsCompiler = process.argv[1].replace(/[^\\]*$/,setting.jsCompiler);
cssCompiler = process.argv[1].replace(/[^\\]*$/,setting.cssCompiler);
fetchConf(conf);
};
(function () {
process.on('exit', function () {
if (useLock) {
fs.unlinkSync(process.argv[1].replace(/[^\\]*$/,'lock'));
}
});
// 检查锁
if (fs.existsSync(process.argv[1].replace(/[^\\]*$/,'lock'))){
console.log('another build task is runing, try later ~\n');
pause();
}else {
fs.appendFileSync(process.argv[1].replace(/[^\\]*$/,'lock'),'');
useLock = true;
}
})();
//try {
init();
//}catch(e){
// err(e.message);
//}
//var resultFile=makeIncDataFile("F:/nginx-1.5.1/html/client-1000.js","F:/nginx-1.5.1/html/client-2000.js",20);
//log(resultFile);