forked from Frizi/gulp-pipemin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
413 lines (357 loc) · 11.4 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
var path = require('path');
var fs = require('fs');
var EOL = require('os').EOL;
var through = require('through2');
var gutil = require('gulp-util');
var glob = require('glob');
var minimatch = require('minimatch');
var when = require('when');
var es = require('event-stream');
var Readable = require('stream').Readable;
var gulpConcat = require('gulp-concat');
var _ = require('lodash');
module.exports = function (options) {
options = options || {};
var startReg = /<!--\s*build:(\w+)(?:\(([^\)]+?)\))?\s+(\/?([^\s]+?))?\s*-->/gim;
var endReg = /<!--\s*endbuild\s*-->/gim;
var jsReg = /<\s*script\s+.*?src\s*=\s*("|')((?:[^\1]|\\\1)+?)\1.*?><\s*\/\s*script\s*>/gi;
var cssReg = /<\s*link\s+.*?href\s*=\s*("|')((?:[^\1]|\\\1)+?)\1.*?>/gi;
var startCondReg = /<!--\[[^\]]+\]>/gim;
var endCondReg = /<!\[endif\]-->/gim;
var basePath, mainPath, mainName, alternatePath;
function getPath (name) {
var filePath = path.join(path.relative(basePath, mainPath), name);
var isStatic = name.split('.').pop() === 'js' || name.split('.').pop() === 'css';
if (options.outputRelativePath && isStatic) {
filePath = options.outputRelativePath + name;
}
return filePath;
}
function createFile (name, content) {
return new gutil.File({
path: getPath(name),
contents: new Buffer(content)
})
}
function getBlockType (content) {
return !cssReg.test(content) ? 'js' : 'css';
}
function readStream (streamCtor, callback) {
var files = [];
var deferred = when.defer();
var stream = streamCtor();
stream.on('data', function (file) {
if (file.isStream()) {
this.emit('error', gutil.PluginError('gulp-usemin', 'Streams in assets are not supported!'));
}
file.base = path.resolve(file.base);
file.path = path.resolve(file.path);
files.push(file);
});
stream.on('end', function () {
if (options.debugStreamFiles) {
console.log('asssets:\n', files.map(function (f) {
return f.base + ' :: ' + f.path;
}).join('\n '));
}
deferred.resolve(files);
});
return deferred.promise;
}
function produceMatcher (fileArray) {
var allFiles = fileArray.map(function (file) {
return file.path;
});
var filesByPath = fileArray.reduce(function (obj, file) {
obj[file.path] = file;
return obj;
}, {});
var notMatched = allFiles.slice(); // clone
return {
matching: function (patterns) {
function doMatch (pattern) {
return minimatch.match(allFiles, pattern);
}
var incs = patterns.inc.map(doMatch);
var excs = patterns.exc.map(doMatch);
var matched = _.difference(_.union.apply(null, incs), _.union.apply(null, excs));
// filter array
notMatched = notMatched.filter(function (i) {
return matched.indexOf(i) < 0;
});
return matched.map(function (path) {
return filesByPath[path];
});
},
notMatched: function () {
return notMatched.map(function (path) {
return filesByPath[path];
});
}
}
}
function getFiles (content, reg, alternatePath, matcherPromise) {
var paths = [];
var promises = [];
var files = [];
var i, l;
var arrayDetect = /^\[.*\]$/;
var arrayParse = /'((?:[^']|\\')*[^'\\])'(?:\s*,\s*)?/g;
content
.replace(startCondReg, '')
.replace(endCondReg, '')
.replace(/<!--(?:(?:.|\r|\n)*?)-->/gim, '')
.replace(reg, function (a, quote, pathPattern) {
var patterns;
var arrayDetected = pathPattern.match(arrayDetect);
if (arrayDetected) {
patterns = [];
pathPattern.replace(arrayParse, function (a, pattern) {
patterns.push(pattern);
});
}
else {
patterns = [pathPattern];
}
var inc = [],
exc = [];
_.each(patterns, function (pattern) {
var isExc = false;
if (pattern[0] === '!') {
isExc = true;
pattern = pattern.slice(1);
}
var filePath = path.resolve(path.join(alternatePath || options.path || mainPath, pattern));
if (options.assetsDir) {
filePath = path.resolve(path.join(options.assetsDir, path.relative(basePath, filePath)));
}
(isExc ? exc : inc).push(filePath);
});
paths.push({inc: inc, exc: exc, src: pathPattern});
});
if (!matcherPromise) {
function globSync (pattern) {
return glob.sync(pattern);
}
// read files from filesystem
for (i = 0, l = paths.length; i < l; ++i) {
var incs = paths[i].inc.map(globSync);
var excs = paths[i].exc.map(globSync);
var filepaths = _.difference(_.union.apply(null, incs), _.union.apply(null, excs));
if (filepaths[0] === undefined) {
throw new gutil.PluginError('gulp-usemin', 'Path ' + paths[i].src + ' not found!');
}
promises.push.apply(promises, filepaths.map(function (filepath) {
var fileDeferred = when.defer();
fs.readFile(filepath, function (err, data) {
if (err) {
throw err;
}
fileDeferred.resolve(new gutil.File({
path: filepath,
contents: data
}));
});
return fileDeferred.promise;
}));
}
return when.all(promises);
}
else {
// read files from stream
for (i = 0, l = paths.length; i < l; ++i) {
var matching = matcherPromise.matching(paths[i]);
if (matching[0] === undefined) {
throw new gutil.PluginError('gulp-usemin', 'Pattern ' + paths[i].src + ' not in stream!');
}
files.push.apply(files, matching);
}
return when.resolve(files);
}
}
function concatThrough (name) {
return gulpConcat(name);
}
function wrapLazypipe (lazypipe) {
return function (stream, concat) {
if (!_.isUndefined(concat)) {
return stream
.pipe(concat)
.pipe(lazypipe());
}
else {
return stream
.pipe(lazypipe());
}
};
}
function processTask (pipeline, name, files) {
if (pipeline === null) {
return null;
}
var tip = new Readable({objectMode: true});
tip._read = function () {
if (files.length > 0) {
var file = files.shift();
this.push(file);
}
else {
this.push(null);
}
};
var concatTask = name ? concatThrough(name) : undefined;
if (typeof pipeline === 'function') {
// lazypipe support
if (typeof pipeline.pipe === 'function') {
return wrapLazypipe(pipeline)(tip, concatTask);
}
return pipeline(tip, concatTask);
}
else if (name) {
return tip.pipe(concatTask);
}
else {
return tip;
}
}
function process (name, files, pipelineId) {
var pipeline = options[pipelineId];
if (typeof pipeline === 'undefined') {
pipeline = [];
}
return processTask(pipeline, name, files);
}
function processHtml (content, matcherProducer) {
var html = [];
var sections = content.split(endReg);
var promise = when.resolve();
var streams = [];
for (var i = 0, l = sections.length; i < l; ++i) {
if (sections[i].match(startReg)) {
var section = sections[i].split(startReg);
alternatePath = section[2];
(function (section) {
promise = promise
.then(function () {
html.push(section[0]);
});
}(section));
var startCondLine = section[5].match(startCondReg);
var endCondLine = section[5].match(endCondReg);
if (startCondLine && endCondLine) {
(function (startCondLine) {
promise = promise.then(function () {
html.push(startCondLine[0]);
});
}(startCondLine))
}
if (section[1] !== 'remove') {
(function (section, alternatePath) {
var type = getBlockType(section[5]);
promise = promise
.then(matcherProducer)
.then(function (matcher) {
return getFiles(section[5], type === 'js' ? jsReg : cssReg, alternatePath, matcher)
})
.then(function (files) {
var name = section[4];
streams.push(process(name, files, section[1]));
var filePaths = name ? [section[3]] : files.map(function (f) {
return '/' + path.relative(f.base, f.path).split(path.sep).join('/');
});
filePaths
.map(function (path) {
return [path, getPath(path)]
})
.forEach(function (filePath) {
var relPath = filePath[0].replace(path.basename(filePath[0]), path.basename(filePath[1]));
if (type === 'js') {
html.push('<script src="' + relPath + '"></script>');
} else {
html.push('<link rel="stylesheet" href="' + relPath + '"/>');
}
});
});
}(section, alternatePath));
}
if (startCondLine && endCondLine) {
(function (endCondLine) {
promise = promise.then(function () {
html.push(endCondLine[0]);
});
}(endCondLine));
}
}
else {
(function (section) {
promise = promise.then(function () {
html.push(section);
});
}(sections[i]))
}
}
return promise.then(function () {
streams.push(process(mainName, [createFile(mainName, html.join(''))], 'html'));
return es.merge.apply(es, streams.filter(function (stream) {
return stream !== null;
}));
});
}
var matcherPromise, matcherProducer;
if (options.assetsStream) {
matcherPromise = readStream(options.assetsStream)
.then(function (filesList) {
return produceMatcher(filesList);
});
matcherProducer = function () {
return matcherPromise;
}
}
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 push = this.push.bind(this);
processHtml(String(file.contents), matcherProducer)
.then(function (stream) {
stream.on('data', function (file) {
push(file);
});
stream.on('end', function () {
callback();
})
});
}
}, function (callback) {
// push not processed files down the stream
if (options.other && matcherPromise) {
var push = this.push.bind(this);
matcherPromise.then(function (filesMatcher) {
var rest = filesMatcher.notMatched();
var stream = processTask(options.other, options.othersName, rest);
if (stream === null) {
callback();
return;
}
stream.on('data', function (file) {
push(file);
});
stream.on('end', function () {
callback();
})
});
}
else {
callback();
}
});
};