-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
60 lines (49 loc) · 1.41 KB
/
index.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
var path = require('path')
, log = require('fancy-log')
, PluginError = require('plugin-error')
, through = require('through2')
, crypto = require('crypto');
module.exports = function(options) {
var separator, size, printOnly;
if (typeof options === 'object') {
printOnly = options.printOnly || false;
separator = options.separator || '_';
size = options.size | 0;
} else {
size = options | 0;
separator = '_';
printOnly = false;
}
return through.obj(function(file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError('gulp-debug', 'Streaming not supported'));
return cb();
}
var md5Hash = calcMd5(file, size),
filename = path.basename(file.path),
dir;
if (printOnly) {
log(filename + ' ' + md5Hash);
return cb(null, file)
}
if (file.path[0] == '.') {
dir = path.join(file.base, file.path);
} else {
dir = file.path;
}
dir = path.dirname(dir);
filename = filename.split('.').map(function(item, i, arr) {
return i == arr.length - 2 ? item + separator + md5Hash : item;
}).join('.');
file.path = path.join(dir, filename);
this.push(file);
cb();
}, function(cb) {
cb();
});
};
function calcMd5(file, slice) {
var md5 = crypto.createHash('md5');
md5.update(file.contents, 'utf8');
return slice > 0 ? md5.digest('hex').slice(0, slice) : md5.digest('hex');
}