-
Notifications
You must be signed in to change notification settings - Fork 93
/
index.js
293 lines (261 loc) · 8.35 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
'use strict';
var through2 = require('through2');
var fancyLog = require('fancy-log');
var PluginError = require('plugin-error');
var colors = require('ansi-colors');
var streamToArray = require('stream-to-array');
var escapeStringRegexp = require('escape-string-regexp');
var groupArray = require('group-array');
var extname = require('../extname');
var transform = require('../transform');
var tags = require('../tags');
var getFilepath = require('../path');
var magenta = colors.magenta;
var cyan = colors.cyan;
var noop = function noop() {};
/**
* Constants
*/
var PLUGIN_NAME = 'gulp-inject';
var DEFAULT_NAME_FOR_TAGS = 'inject';
var LEADING_WHITESPACE_REGEXP = /^\s*/;
module.exports = exports = function (sources, opt) {
if (!sources) {
throw error('Missing sources stream!');
}
if (!opt) {
opt = {};
}
if (opt.sort) {
throw error('sort option is deprecated! Use `sort-stream` module instead!');
}
if (opt.templateString) {
throw error('`templateString` option is deprecated! Create a virtual `vinyl` file instead!');
}
if (opt.transform && typeof opt.transform !== 'function') {
throw error('transform option must be a function');
}
// Notify people of common mistakes...
if (typeof opt.read !== 'undefined') {
throw error('There is no `read` option. Did you mean to provide it for `gulp.src` perhaps?');
}
// Defaults:
opt.quiet = bool(opt, 'quiet', false);
opt.relative = bool(opt, 'relative', false);
opt.addRootSlash = bool(opt, 'addRootSlash', !opt.relative);
opt.transform = defaults(opt, 'transform', transform);
opt.tags = tags();
opt.name = defaults(opt, 'name', DEFAULT_NAME_FOR_TAGS);
transform.selfClosingTag = bool(opt, 'selfClosingTag', false);
// Is the first parameter a Vinyl File Stream:
if (typeof sources.on === 'function' && typeof sources.pipe === 'function') {
return handleVinylStream(sources, opt);
}
throw error('passing target file as a string is deprecated! Pass a vinyl file stream (i.e. use `gulp.src`)!');
};
function defaults(options, prop, defaultValue) {
return options[prop] || defaultValue;
}
function bool(options, prop, defaultVal) {
return typeof options[prop] === 'undefined' ? defaultVal : Boolean(options[prop]);
}
/**
* Handle injection when files to
* inject comes from a Vinyl File Stream
*
* @param {Stream} sources
* @param {Object} opt
* @returns {Stream}
*/
function handleVinylStream(sources, opt) {
var collected = streamToArray(sources);
return through2.obj(function (target, enc, cb) {
if (target.isStream()) {
return cb(error('Streams not supported for target templates!'));
}
collected.then(function (collection) { // eslint-disable-line promise/prefer-await-to-then
target.contents = getNewContent(target, collection, opt);
this.push(target);
cb();
}.bind(this))
.catch(function (error) {
cb(error);
});
});
}
/**
* Get new content for template
* with all injections made
*
* @param {Object} target
* @param {Array} collection
* @param {Object} opt
* @returns {Buffer}
*/
function getNewContent(target, collection, opt) {
var logger = opt.quiet ? noop : function (filesCount) {
if (filesCount) {
var pluralState = filesCount > 1 ? 's' : '';
log(cyan(filesCount) + ' file' + pluralState + ' into ' + magenta(target.relative) + '.');
} else {
log('Nothing to inject into ' + magenta(target.relative) + '.');
}
};
var content = String(target.contents);
var targetExt = extname(target.path);
var files = prepareFiles(collection, targetExt, opt, target);
var filesPerTags = groupArray(files, 'tagKey');
var startAndEndTags = Object.keys(filesPerTags);
var matches = [];
var injectedFilesCount = 0;
startAndEndTags.forEach(function (tagKey) {
var files = filesPerTags[tagKey];
var startTag = files[0].startTag;
var endTag = files[0].endTag;
var tagsToInject = getTagsToInject(files, target, opt);
content = inject(content, {
startTag: startTag,
endTag: endTag,
tagsToInject: tagsToInject,
removeTags: opt.removeTags,
empty: opt.empty,
willInject: function (filesToInject) {
injectedFilesCount += filesToInject.length;
},
onMatch: function (match) {
matches.push(match[0]);
}
});
});
logger(injectedFilesCount);
if (opt.empty) {
var ext = '{{ANY}}';
var startTag = getTagRegExp(opt.tags.start(targetExt, ext, opt.starttag), ext, opt);
var endTag = getTagRegExp(opt.tags.end(targetExt, ext, opt.endtag), ext, opt);
content = inject(content, {
startTag: startTag,
endTag: endTag,
tagsToInject: [],
removeTags: opt.removeTags,
empty: opt.empty,
shouldAbort: function (match) {
return matches.indexOf(match[0]) !== -1;
}
});
}
return Buffer.from(content);
}
/**
* Inject tags into content for given
* start and end tags
*
* @param {String} content
* @param {Object} opt
* @returns {String}
*/
function inject(content, opt) {
var startTag = opt.startTag;
var endTag = opt.endTag;
var startMatch;
var endMatch;
/**
* The content consists of:
*
* <everything before startMatch>
* <startMatch>
* <previousInnerContent>
* <endMatch>
* <everything after endMatch>
*/
while ((startMatch = startTag.exec(content)) !== null) {
if (typeof opt.onMatch === 'function') {
opt.onMatch(startMatch);
}
if (typeof opt.shouldAbort === 'function' && opt.shouldAbort(startMatch)) {
continue;
}
// Take care of content length change:
endTag.lastIndex = startTag.lastIndex;
endMatch = endTag.exec(content);
if (!endMatch) {
throw error('Missing end tag for start tag: ' + startMatch[0]);
}
var toInject = opt.tagsToInject.slice();
if (typeof opt.willInject === 'function') {
opt.willInject(toInject);
}
// <everything before startMatch>:
var newContents = content.slice(0, startMatch.index);
if (opt.removeTags) {
if (opt.empty) {
// Take care of content length change:
startTag.lastIndex -= startMatch[0].length;
}
} else {
// <startMatch> + <endMatch>
toInject.unshift(startMatch[0]);
toInject.push(endMatch[0]);
}
var previousInnerContent = content.substring(startTag.lastIndex, endMatch.index);
var indent = getLeadingWhitespace(previousInnerContent);
// <new inner content>:
newContents += toInject.join(indent);
// <everything after endMatch>:
newContents += content.slice(endTag.lastIndex);
// Replace old content with new:
content = newContents;
}
return content;
}
function getLeadingWhitespace(str) {
return str.match(LEADING_WHITESPACE_REGEXP)[0];
}
function prepareFiles(files, targetExt, opt, target) {
return files.map(function (file) {
var ext = extname(file.path);
var filePath = getFilepath(file, target, opt);
var startTag = getTagRegExp(opt.tags.start(targetExt, ext, opt.starttag), ext, opt, filePath);
var endTag = getTagRegExp(opt.tags.end(targetExt, ext, opt.endtag), ext, opt, filePath);
var tagKey = String(startTag) + String(endTag);
return {
file: file,
ext: ext,
startTag: startTag,
endTag: endTag,
tagKey: tagKey
};
});
}
function getTagRegExp(tag, sourceExt, opt, sourcePath) {
tag = makeWhiteSpaceOptional(escapeStringRegexp(tag));
tag = replaceVariables(tag, {
name: opt.name,
path: sourcePath,
ext: sourceExt === '{{ANY}}' ? '.+' : sourceExt
});
return new RegExp(tag, 'ig');
}
function replaceVariables(str, variables) {
return Object.keys(variables).reduce(function (str, variable) {
return str.replace(new RegExp(escapeStringRegexp(escapeStringRegexp('{{' + variable + '}}')), 'ig'), variables[variable] + '\\b');
}, str);
}
function makeWhiteSpaceOptional(str) {
return str.replace(/\s+/g, '\\s*');
}
function getTagsToInject(files, target, opt) {
return files.reduce(function transformFile(lines, file, i, files) {
var filepath = getFilepath(file.file, target, opt);
var transformedContents = opt.transform(filepath, file.file, i, files.length, target);
if (typeof transformedContents !== 'string') {
return lines;
}
return lines.concat(transformedContents);
}, []);
}
function log(message) {
fancyLog.info(magenta(PLUGIN_NAME), message);
}
function error(message) {
return new PluginError(PLUGIN_NAME, message);
}