forked from bleech/gulp-rev-all
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.js
85 lines (63 loc) · 3.02 KB
/
tools.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 fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var gutil = require('gulp-util');
module.exports = ( function () {
var filepathRegex = /.*?(?:\'|\")([a-z0-9_\-\/\.]+?\.[a-z]{2,4})(?:(?:\?|\#)[^'"]*?|)(?:\'|\").*?/ig;
var fileMap = {};
// Taken from gulp-rev: https://github.com/sindresorhus/gulp-rev
var md5 = function (str) {
return crypto.createHash('md5').update(str, 'utf8').digest('hex');
};
// Taken from gulp-rev: https://github.com/sindresorhus/gulp-rev
var revFile = function (filePath) {
if (fileMap[filePath])
return fileMap[filePath];
var contents = fs.readFileSync(filePath).toString();
var hash = md5(contents).slice(0, 8);
var ext = path.extname(filePath);
var filename = path.basename(filePath, ext) + '-' + hash + ext;
var filePathReved = path.join(path.dirname(filePath), filename);
fileMap[filePath] = filePathReved;
return fileMap[filePath];
};
var revReferencesInFile = function (file, rootDir, ignoreExtensions) {
var replaceMap = {};
gutil.log('gulp-rev-all:', 'Finding references in [', file.path, ']');
// Create a map of file references and their proper revisioned name
var contents = String(file.contents);
var result;
while (result = filepathRegex.exec(contents)) {
// Skip if we've already resolved this reference
if (replaceMap[result[1]] != undefined) continue;
replaceMap[result[1]] = false;
// Skip if extension is ignored
if (ignoreExtensions.indexOf(path.extname(result[1])) !== -1) continue;
// In the case where the referenced file is relative to the base path
if (rootDir) {
var fullpath = path.join(rootDir, result[1]);
if (fs.existsSync(fullpath)) {
replaceMap[result[1]] = path.dirname(result[1]) + '/' + path.basename(revFile(fullpath));
gutil.log('gulp-rev-all:', 'Found root reference [', result[1], '] -> [', replaceMap[result[1]], ']');
continue;
}
}
// In the case where the file referenced is relative to the file being processed
var fullpath = path.join(path.dirname(file.path), result[1]);
if (fs.existsSync(fullpath)) {
replaceMap[result[1]] = path.dirname(result[1]) + '/' + path.basename(revFile(fullpath));
gutil.log('gulp-rev-all:', 'Found relative reference [', result[1], '] -> [', replaceMap[result[1]], ']');
continue;
}
}
for (var key in replaceMap) {
if (!replaceMap[key]) continue;
contents = contents.replace(new RegExp(key, 'g'), replaceMap[key]);
}
file.contents = new Buffer(contents); // Update file contents with new reved references
};
return {
revFile: revFile,
revReferencesInFile: revReferencesInFile
}
}());