forked from smysnk/gulp-rev-all
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.js
87 lines (63 loc) · 2.99 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
86
87
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, options) {
if (fileMap[filePath])
return fileMap[filePath];
var contents = fs.readFileSync(filePath).toString();
var hash = md5(contents).slice(0, options.hashLength);
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, options) {
var replaceMap = {};
var rootDir = options.rootDir || path.dirname(file.path);
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;
var fullpath = '';
while (result = filepathRegex.exec(contents)) {
// Skip if we've already resolved this reference
if (typeof replaceMap[result[1]] !== 'undefined') continue;
replaceMap[result[1]] = false;
// In the case where the referenced file is relative to the base path
if (rootDir) {
fullpath = path.join(rootDir, result[1]);
if (fs.existsSync(fullpath)) {
replaceMap[result[1]] = path.dirname(result[1]) + '/' + path.basename(revFile(fullpath, options));
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
fullpath = path.join(file.base, result[1]);
if (fs.existsSync(fullpath)) {
replaceMap[result[1]] = path.dirname(result[1]) + '/' + path.basename(revFile(fullpath, options));
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(key, replaceMap[key]);
}
file.contents = new Buffer(contents); // Update file contents with new reved references
};
return {
revFile: revFile,
revReferencesInFile: revReferencesInFile
};
}());