-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
102 lines (80 loc) · 3.15 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
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
'use strict';
var through = require('through2'),
async = require('async'),
fs = require('fs'),
crypto = require('crypto'),
extname = require('path').extname,
gutil = require('gulp-util');
var PLUGIN_NAME = 'gulp-css-image-hash';
function cssImageHash(webPath, includeFileExtensions) {
var stream = through.obj(function(file, enc, cb) {
var that = this;
var regex = /url\(([^\)]+)\)/g,
matches = null;
var asString = '';
if (file.isBuffer()) {
asString = String(file.contents);
matches = asString.match(regex);
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
return cb();
}
if (matches != null && matches.length) {
var pairs = [];
matches = matches.forEach(function(curValue) {
// remove url()
var path = curValue.slice(4).slice(0, -1);
// Remove surrounding quotes
if (path[0] == '"' || path[0] == "'") {
path = path.slice(1).slice(0, -1);
}
pairs.push([curValue, path]);
});
async.eachSeries(pairs, function(tuple, callback) {
var path = tuple[1];
if (Array.isArray(includeFileExtensions)) {
var extension = extname(tuple[1]).slice(1);
if(includeFileExtensions.indexOf(extension) < 0) {
return callback();
}
}
if (path.substr(0, 4) == 'data') {
return callback();
}
if (typeof(webPath) == 'function') {
path = webPath(path);
} else if (typeof(webPath) != 'undefined') {
path = webPath + path;
}
if (!path) {
return callback();
}
var md5 = crypto.createHash('md5'),
file = fs.ReadStream(path),
hash = '';
file.on('data', function(d) {
md5.update(d);
});
file.on('end', function() {
hash = md5.digest('hex');
asString = asString.replace(tuple[0], 'url(' + tuple[1] + '?h=' + hash + ')');
callback();
});
file.on('error', function(error) {
gutil.log('gulp-css-image-hash: Skipping ' + path);
callback();
});
}, function (err) {
file.contents = new Buffer(asString);
that.push(file);
cb();
});
} else {
this.push(file);
cb();
}
});
return stream;
};
module.exports = cssImageHash;