-
Notifications
You must be signed in to change notification settings - Fork 68
/
index.js
334 lines (275 loc) · 12.6 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
var fs = require('fs'),
path = require('path'),
es = require('event-stream'),
glob = require('glob'),
PluginError = require('plugin-error'),
colors = require('ansi-colors'),
applySourceMap = require('vinyl-sourcemaps-apply'),
stripBom = require('strip-bom');
module.exports = function (params) {
params = params || {};
var SourceMapGenerator = require('source-map').SourceMapGenerator;
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var extensions = null, // The extension to be searched after
globalIncludedFiles = [], // To track what files have been included over all files
includePaths = false, // The paths to be searched
hardFail = false, // Throw error when no match
separateInputs = false; // Process each input file separately when using `require` directive
// Check for includepaths in the params
if (params.includePaths) {
if (typeof params.includePaths == "string") {
// Arrayify the string
includePaths = [params.includePaths];
} else if (Array.isArray(params.includePaths)) {
// Set this array to the includepaths
includePaths = params.includePaths;
}
}
if (params.separateInputs) {
separateInputs = true;
}
// Toggle error reporting
if (params.hardFail != undefined) {
hardFail = params.hardFail;
}
if (params.extensions) {
extensions = typeof params.extensions === 'string' ? [params.extensions] : params.extensions;
}
function include(file, callback) {
var includedFiles = separateInputs ? [] : globalIncludedFiles;
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
throw new PluginError('gulp-include', 'stream not supported');
}
if (file.isBuffer()) {
var result = processInclude(String(file.contents), file.path, file.sourceMap, includedFiles);
file.contents = new Buffer(result.content);
if (file.sourceMap && result.map) {
if (Object.prototype.toString.call(result.map) === '[object String]') {
result.map = JSON.parse(result.map);
}
// relative-ize the paths in the map
result.map.file = path.relative(file.base, result.map.file);
result.map.sources.forEach(function (source, q) {
result.map.sources[q] = path.relative(file.base, result.map.sources[q]);
});
applySourceMap(file, result.map);
}
}
callback(null, file);
}
function processInclude(content, filePath, sourceMap, includedFiles) {
var matches = content.match(/^(\s+)?(\/\/|\/\*|\#|\<\!\-\-)(\s+)?=(\s+)?(include|require)(.+$)/mg);
var relativeBasePath = path.dirname(filePath);
if (!matches) return {
content: content,
map: null
};
// Apply sourcemaps
var map = null,
mapSelf, lastMappedLine, currentPos, insertedLines;
if (sourceMap) {
map = new SourceMapGenerator({
file: unixStylePath(filePath)
});
lastMappedLine = 1;
currentPos = 0;
insertedLines = 0;
mapSelf = function (currentLine) { // maps current file between matches and after all matches
var currentOrigLine = currentLine - insertedLines;
for (var q = (currentLine - lastMappedLine); q > 0; q--) {
map.addMapping({
generated: {
line: currentLine - q,
column: 0
},
original: {
line: currentOrigLine - q,
column: 0
},
source: filePath
});
}
lastMappedLine = currentLine;
};
}
for (var i = 0; i < matches.length; i++) {
var leadingWhitespaceMatch = matches[i].match(/^\s*/);
var leadingWhitespace = null;
if (leadingWhitespaceMatch) {
leadingWhitespace = leadingWhitespaceMatch[0].replace("\n", "");
}
// Remove beginnings, endings and trim.
var includeCommand = matches[i]
.replace(/\s+/g, " ")
.replace(/(\/\/|\/\*|\#|<!--)(\s+)?=(\s+)?/g, "")
.replace(/(\*\/|-->)$/g, "")
.replace(/['"]/g, "")
.trim();
var split = includeCommand.split(" ");
var currentLine;
if (sourceMap) {
// get position of current match and get current line number
currentPos = content.indexOf(matches[i], currentPos);
currentLine = currentPos === -1 ? 0 : content.substr(0, currentPos).match(/^/mg).length;
// sometimes the line matches the leading \n and sometimes it doesn't. wierd.
// in case it does, increment the current line counter
if (leadingWhitespaceMatch[0][0] == '\n') currentLine++;
mapSelf(currentLine);
}
// SEARCHING STARTS HERE
// Split the directive and the path
var includeType = split[0];
// Use glob for file searching
var fileMatches = [];
var includePath = "";
if (includePaths != false && !isExplicitRelativePath(split[1])) {
// If includepaths are set, search in those folders
for (var y = 0; y < includePaths.length; y++) {
includePath = includePaths[y] + "/" + split[1];
var globResults = glob.sync(includePath, {
mark: true
});
fileMatches = fileMatches.concat(globResults);
}
} else {
// Otherwise search relatively
includePath = relativeBasePath + "/" + removeRelativePathPrefix(split[1]);
var globResults = glob.sync(includePath, {
mark: true
});
fileMatches = globResults;
}
if (fileMatches.length < 1) fileNotFoundError(includePath);
var replaceContent = '';
for (var y = 0; y < fileMatches.length; y++) {
var globbedFilePath = fileMatches[y];
// If directive is of type "require" and file already included, skip to next.
if (includeType == "require" && includedFiles.indexOf(globbedFilePath) > -1) continue;
// If not in extensions, skip this file
if (!inExtensions(globbedFilePath)) continue;
// Get file contents and apply recursive include on result
// Unicode byte order marks are stripped from the start of included files
var fileContents = stripBom(fs.readFileSync(globbedFilePath));
var result = processInclude(fileContents.toString(), globbedFilePath, sourceMap, includedFiles);
var resultContent = result.content;
if (sourceMap) {
var lines = resultContent.match(/^/mg).length; //count lines in result
if (result.map) { // result had a map, merge mappings
if (Object.prototype.toString.call(result.map) === '[object String]') {
result.map = JSON.parse(result.map);
}
if (result.map.mappings && result.map.mappings.length > 0) {
var resultMap = new SourceMapConsumer(result.map);
resultMap.eachMapping(function (mapping) {
if (!mapping.source) return;
map.addMapping({
generated: {
line: mapping.generatedLine + currentLine - 1,
column: mapping.generatedColumn + (leadingWhitespace ? leadingWhitespace.length : 0)
},
original: {
line: mapping.originalLine,
column: mapping.originalColumn
},
source: mapping.source,
name: mapping.name
});
});
if (result.map.sourcesContent) {
result.map.sourcesContent.forEach(function (sourceContent, i) {
map.setSourceContent(result.map.sources[i], sourceContent);
});
}
}
} else { // result was a simple file, map whole file to new location
for (var q = 0; q < lines; q++) {
map.addMapping({
generated: {
line: currentLine + q,
column: leadingWhitespace ? leadingWhitespace.length : 0
},
original: {
line: q + 1,
column: 0
},
source: globbedFilePath
});
}
if (sourceMap.sourcesContent) {
map.setSourceContent(globbedFilePath, resultContent);
}
}
// increment/set map line counters
insertedLines += lines;
currentLine += lines;
lastMappedLine = currentLine;
}
if (includedFiles.indexOf(globbedFilePath) == -1) includedFiles.push(globbedFilePath);
// If the last file did not have a line break, and it is not the last file in the matched glob,
// add a line break to the end
if (!resultContent.trim().match(/\n$/) && y != fileMatches.length - 1) {
resultContent += "\n";
}
if (leadingWhitespace) resultContent = addLeadingWhitespace(leadingWhitespace, resultContent);
replaceContent += resultContent;
}
// REPLACE
if (replaceContent.length) {
// sometimes the line matches the leading \n and sometimes it doesn't. wierd.
// in case it does, preserve that leading \n
if (leadingWhitespaceMatch[0][0] === '\n') {
replaceContent = '\n' + replaceContent;
}
content = content.replace(matches[i], function () {
return replaceContent
});
insertedLines--; // adjust because the original line with comment was removed
}
}
if (sourceMap) {
currentLine = content.match(/^/mg).length + 1;
mapSelf(currentLine);
}
return {
content: content,
map: map ? map.toString() : null
};
}
function unixStylePath(filePath) {
return filePath.replace(/\\/g, '/');
}
function addLeadingWhitespace(whitespace, string) {
return string.split("\n").map(function (line) {
return whitespace + line;
}).join("\n");
}
function isExplicitRelativePath(filePath) {
return filePath.indexOf('./') === 0;
}
function removeRelativePathPrefix(filePath) {
return filePath.replace(/^\.\//, '');
}
function fileNotFoundError(includePath) {
if (hardFail) {
throw new PluginError('gulp-include', 'No files found matching ' + includePath);
} else {
console.warn(
colors.yellow('WARN: ') +
colors.cyan('gulp-include') +
' - no files found matching ' + includePath
);
}
}
function inExtensions(filePath) {
if (!extensions) return true;
for (var i = 0; i < extensions.length; i++) {
var re = extensions[i] + "$";
if (filePath.match(re)) return true;
}
return false;
}
return es.map(include)
};