forked from thomastuts/gulp-rev-mtime
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
85 lines (73 loc) · 2.46 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
var path = require('path');
var fs = require('fs');
var EOL = require('os').EOL;
var through = require('through2');
var gutil = require('gulp-util');
module.exports = function(options) {
options = options || {};
var startReg = /<!--\s*rev\-hash\s*-->/gim;
var endReg = /<!--\s*end\s*-->/gim;
var jsAndCssReg = /<\s*script\s+.*?src\s*=\s*"([^"]+.js).*".*?><\s*\/\s*script\s*>|<\s*link\s+.*?href\s*=\s*"([^"]+.css).*".*?>/gi;
var regSpecialsReg = /([.?*+^$[\]\\(){}|-])/g;
var basePath, mainPath, mainName, alternatePath;
function getBlockType(content) {
return jsReg.test(content) ? 'js' : 'css';
}
function getTags(content) {
var tags = [];
content
.replace(/<!--(?:(?:.|\r|\n)*?)-->/gim, '')
.replace(jsAndCssReg, function (a, b, c) {
tags.push({
html: a,
path: b || c,
pathReg: new RegExp(escapeRegSpecials(b || c) + '.*?"', 'g')
});
});
return tags;
}
function escapeRegSpecials(str) {
return (str + '').replace(regSpecialsReg, "\\$1");
}
return through.obj(function(file, enc, callback) {
if (file.isNull()) {
this.push(file); // Do nothing if no contents
callback();
}
else if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-usemin', 'Streams are not supported!'));
callback();
}
else {
basePath = file.base;
mainPath = path.dirname(file.path);
mainName = path.basename(file.path);
var html = [];
var sections = String(file.contents).split(endReg);
for (var i = 0, l = sections.length; i < l; ++i) {
if (sections[i].match(startReg)) {
var tag;
var section = sections[i].split(startReg);
var tags = getTags(section[1]);
html.push(section[0]);
html.push('<!-- rev-hash -->\r\n')
for (var j = 0; j < tags.length; j++) {
tag = tags[j];
var hash = require('crypto')
.createHash('md5')
.update(
fs.readFileSync(
path.join((options.assetsDir?options.assetsDir:''), tag.path), {encoding: 'utf8'}))
.digest("hex");
html.push(tag.html.replace(tag.pathReg, tag.path + '?v=' + hash + '"') + '\r\n');
}
html.push('<!-- end -->');
}
else { html.push(sections[i]); }
}
file.contents = new Buffer(html.join(''));
this.push(file);
return callback();
}
});
};