forked from vfasky/fbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.js
91 lines (74 loc) · 2.52 KB
/
hash.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
/**
*
* @date 2015-03-30 00:12:45
* @author vfasky <[email protected]>
*/
"use strict";
var through2 = require('through2');
var FS = require("q-io/fs");
var path = require('path');
var crypto = require('crypto');
var del = require('del');
var md5 = function(text) {
return crypto.createHash('md5').update(String(text)).digest('hex');
};
var getHash = function(text) {
return md5(text).substring(0, 6);
};
var fileMapPath = path.join(__dirname, 'filemap.json');
var buildHash = function() {
return through2.obj(function(file, enc, callback) {
//var newPath = file.path.replace('all.js', 'all.min.js');
var paths = file.path.split(path.sep);
var packName = paths.pop().split('.all.')[0];
if (paths.pop() === 'tpl') {
packName = 'tpl/' + packName.replace('.js', '');
}
//file.path = newPath;
var hash = getHash(file.contents);
var delPath;
FS.exists(fileMapPath).then(function(stat) {
if (stat) {
return FS.read(fileMapPath);
}
return '{}';
})
.then(function(json) {
var data = JSON.parse(json);
var paths = file.path.split(path.sep);
var soureName = paths.pop();
var name = soureName.replace('.js', '.' + hash + '.js');
var match = soureName.replace('.js', '.*.js');
paths.push(name);
file.path = paths.join(path.sep);
paths[paths.length - 1] = match;
delPath = paths.join(path.sep);
var devPath = false;
if(name.indexOf('.min.') !== -1){
paths[paths.length - 1] = soureName.replace('.min.js', '.js');
devPath = paths.join(path.sep);
}
data[packName] = {
hash: hash,
path: file.path,
devPath: devPath
};
return FS.write(fileMapPath, JSON.stringify(data, null, 4));
})
.then(function() {
del([delPath, '!'+file.path], {force: true}, function(){
callback(null, file);
});
})
.fail(function(err) {
callback(err);
});
});
};
buildHash.setPath = function(filePath) {
fileMapPath = path.join(filePath, 'filemap.json');
};
buildHash.getPath = function(){
return fileMapPath;
};
module.exports = buildHash;