forked from shonny-ua/gulp-rev-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
205 lines (187 loc) · 7.05 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
'use strict';
var _ = require('underscore');
var PluginError = require('plugin-error');
var Vinyl = require('vinyl');
var through = require('through2');
var path = require('path');
var PLUGIN_NAME = 'gulp-rev-collector';
var defaults = {
revSuffix: '-[0-9a-f]{8,10}-?',
extMap: {
'.scss': '.css',
'.less': '.css',
'.jsx': '.js'
}
};
function _getManifestData(file, opts) {
var data;
var ext = path.extname(file.path);
if (ext === '.json') {
var json = {};
try {
var content = file.contents.toString('utf8');
if (content) {
json = JSON.parse(content);
}
} catch (x) {
this.emit('error', new PluginError(PLUGIN_NAME, x));
return;
}
if (_.isObject(json)) {
var isRev = 1;
Object.keys(json).forEach(function (key) {
if (!_.isString(json[key])) {
isRev = 0;
return;
}
var cleanReplacement = path.basename(json[key]).replace(new RegExp( opts.revSuffix ), '' );
if (!~[
path.basename(key),
_mapExtnames(path.basename(key), opts)
].indexOf(cleanReplacement)
) {
isRev = 0;
}
});
if (isRev) {
data = json;
}
}
}
return data;
}
// Issue #30 extnames normalisation
function _mapExtnames(filename, opts) {
Object.keys(opts.extMap).forEach(function (ext) {
var extPattern = new RegExp( escPathPattern(ext) + '$' );
if (extPattern.test(filename)) {
filename = filename.replace(extPattern, opts.extMap[ext]);
}
});
return filename;
}
function escPathPattern(pattern) {
return pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\^\$\|\/\\]/g, "\\$&");
}
function closeDirBySep(dirname) {
return dirname + (!dirname || new RegExp( escPathPattern('/') + '$' ).test(dirname) ? '' : '/');
}
function revCollector(opts) {
opts = _.defaults((opts || {}), defaults);
var manifest = {};
var mutables = [];
return through.obj(function (file, enc, cb) {
if (!file.isNull()) {
var mData = _getManifestData.call(this, file, opts);
if (mData) {
_.extend( manifest, mData );
} else {
mutables.push(file);
}
}
cb();
}, function (cb) {
var changes = [];
var dirReplacements = [];
if ( _.isObject(opts.dirReplacements) ) {
Object.keys(opts.dirReplacements).forEach(function (srcDirname) {
dirReplacements.push({
dirRX: escPathPattern( closeDirBySep(srcDirname) ),
dirRpl: opts.dirReplacements[srcDirname]
});
});
}
if (opts.collectedManifest) {
this.push(
new Vinyl({
path: opts.collectedManifest,
contents: new Buffer(JSON.stringify(manifest, null, "\t"))
})
);
}
// Issue #50 extnames extended
Object.keys(manifest).forEach(function (key) {
var expMapedPattern = _mapExtnames(key, opts);
if (key != expMapedPattern && !~Object.keys(manifest).indexOf(expMapedPattern)) {
manifest[expMapedPattern] = _mapExtnames(manifest[key], opts);
}
});
for (var key in manifest) {
var patterns = [ escPathPattern(key) ];
if (opts.replaceReved) {
var patternExt = path.extname(key);
if (patternExt in opts.extMap) {
patternExt = '(' + escPathPattern(patternExt) + '|' + escPathPattern(opts.extMap[patternExt]) + ')';
} else {
patternExt = escPathPattern(patternExt);
}
patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) )
+ path.basename(key, path.extname(key))
.split('.')
.map(function(part){
return escPathPattern(part) + '(' + opts.revSuffix + ')?';
})
.join('\\.')
+ patternExt
);
}
if ( dirReplacements.length ) {
dirReplacements.forEach(function (dirRule) {
patterns.forEach(function (pattern) {
changes.push({
regexp: new RegExp( dirRule.dirRX + pattern, 'g' ),
patternLength: (dirRule.dirRX + pattern).length,
replacement: _.isFunction(dirRule.dirRpl)
? dirRule.dirRpl(manifest[key])
: closeDirBySep(dirRule.dirRpl) + manifest[key]
});
});
});
} else {
patterns.forEach(function (pattern) {
// without dirReplacements we must leave asset filenames with prefixes in its original state
var prefixDelim = '([\/\\\\\'"';
// if dir part in pattern exists, all exsotoic symbols should be correct processed using dirReplacements
if (/[\\\\\/]/.test(pattern)) {
prefixDelim += '\(=';
} else {
if (!/[\(\)]/.test(pattern)) {
prefixDelim += '\(';
}
if (!~pattern.indexOf('=')) {
prefixDelim += '=';
}
}
prefixDelim += '])';
changes.push({
regexp: new RegExp( prefixDelim + pattern, 'g' ),
patternLength: pattern.length,
replacement: '$1' + manifest[key]
});
});
}
}
// Replace longer patterns first
// e.g. match `script.js.map` before `script.js`
// if opts.replaceShorterPatternsFirst, then Replace shorter patterns first
if (!opts.replaceShorterPatternsFirst) {
changes.sort(
function(a, b) {
return b.patternLength - a.patternLength;
}
);
}
mutables.forEach(function (file){
if (!file.isNull()) {
var src = file.contents.toString('utf8');
changes.forEach(function (r) {
src = src.replace(r.regexp, r.replacement);
});
file.contents = new Buffer(src);
}
this.push(file);
}, this);
cb();
});
}
module.exports = revCollector;