-
Notifications
You must be signed in to change notification settings - Fork 38
/
injector.js
340 lines (285 loc) · 10.5 KB
/
injector.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
/*
* grunt-injector
* https://github.com/klei-dev/grunt-injector
*
* Copyright (c) 2013 Joakim Bengtson
* Licensed under the MIT license.
*/
'use strict';
var path = require('path'),
fs = require('fs'),
_ = require('lodash'),
ext = function (file) {
return path.extname(file).slice(1);
};
module.exports = function(grunt) {
grunt.registerMultiTask('injector', 'Inject references to files into other files (think scripts and stylesheets into an html file)', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
min: false,
template: null,
bowerPrefix: null,
relative: false,
prefix: '',
clean: false,
postfix: '',
addRootSlash: (function (that) {
var addRootSlash = true;
if (that.data.options) {
addRootSlash = that.data.options.addRootSlash || !that.data.options.relative;
}
return addRootSlash;
})(this),
starttag: '<!-- injector:{{ext}} -->',
endtag: '<!-- endinjector -->',
lineEnding: null,
transform: function (filePath) {
var e = ext(filePath);
var pathToInject = filePath + options.postfix;
if (e === 'css') {
return '<link rel="stylesheet" href="' + pathToInject + '">';
} else if (e === 'js') {
return '<script src="' + pathToInject + '"></script>';
} else if (e === 'html') {
return '<link rel="import" href="' + pathToInject + '">';
}
}
});
var useDestTpl = false;
if (!options.template && !options.templateString) {
grunt.log.writeln('Missing option `template`, using `dest` as template instead'.grey);
useDestTpl = true;
}
var filesToInject = {};
if (!options.lineEnding) {
var that = this;
options.lineEnding = getDefaultLineEnding(options, that, grunt);
}
// Iterate over all specified file groups and gather files to inject:
this.files.forEach(function(f) {
var template = options.templateString || options.template || options.destFile || f.dest,
destination = options.destFile || f.dest;
if (!options.templateString && !grunt.file.exists(template)) {
grunt.log.error('Could not find template "' + template + '". Injection not possible');
return false;
}
// Group by destination:
if (!filesToInject[destination]) {
filesToInject[destination] = {};
}
// ...and template:
if (!filesToInject[destination][template]) {
filesToInject[destination][template] = [];
}
var files = filesToInject[destination][template];
f.src.forEach(function(filepath) {
// Warn on and remove invalid source files.
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return;
}
// Special handling of bower.json:
if (path.basename(filepath) === 'bower.json') {
files.push.apply(files, getFilesFromBower(filepath).map(function (fpath) {
return {path: fpath, ignore: path.dirname(filepath), key: (options.bowerPrefix || '') + ext(fpath)};
}));
} else {
files.push({path: filepath, key: ext(filepath)});
}
});
// Clear existing content between injectors
var templateContent = options.templateString || grunt.file.read(template),
templateOriginal = templateContent;
var re = getInjectorTagsRegExp(options.starttag, options.endtag);
templateContent = templateContent.replace(re, function (match, indent, starttag, content, endtag) {
return indent + starttag + options.lineEnding + indent + endtag;
});
if (templateContent !== templateOriginal || !grunt.file.exists(destination)) {
grunt.file.write(destination, templateContent);
}
});
/**
* Inject all gathered files per destination, template and starttag:
*/
_.forIn(filesToInject, function (templates, destination) {
_.forIn(templates, function (files, template) {
// Remove possible duplicates:
files = _.uniq(files);
files.forEach(function (obj) {
// Get start and end tag for each file:
obj.starttag = getTag(options.starttag, obj.key);
obj.endtag = getTag(options.endtag, obj.key);
// Fix filename (remove ignorepaths and such):
var file = obj.path;
file = makeMinifiedIfNeeded(options.min, file);
if (options.relative) {
var base = path.dirname(destination);
file = path.relative(base, file);
}
file = unixify(file);
if (options.ignorePath || obj.ignore) {
file = removeBasePath(toArray(options.ignorePath).concat(toArray(obj.ignore)), file);
}
if (options.addRootSlash) {
file = addRootSlash(file);
} else {
file = removeRootSlash(file);
}
obj.file = options.prefix + file;
});
// Read template:
var templateContent = options.templateString || grunt.file.read(template),
templateOriginal = templateContent;
// Inject per start tag:
_.forIn(_.groupBy(files, 'starttag'), function (sources, starttag) {
var endtag = sources[0].endtag,
key = sources[0].key;
// Transform to injection content:
sources.forEach(function (obj, i) {
obj.transformed = options.transform(obj.file, i, sources.length);
});
sources = removeEmptySources(sources);
// Sort files if needed:
if (typeof options.sort === 'function') {
sources.sort(function (a, b) {
return options.sort(a.file, b.file);
});
}
// Do the injection:
var re = getInjectorTagsRegExp(starttag, endtag);
templateContent = templateContent.replace(re, function (match, indent, starttag, content, endtag) {
grunt.log.writeln('Injecting ' + key.green + ' files ' + ('(' + sources.length + ' files)').grey);
return indent + starttag + getIndentedTransformations(sources, indent, options.lineEnding) + endtag;
});
});
// Clean the injection:
if (options.clean) {
var re = new RegExp('(<!\\-\\- injector:\\S. \\-\\->)(\\n|\\r|.)*?(<!\\-\\- endinjector \\-\\->)');
templateContent = templateContent.replace(re, function (match, starttag, content, endtag) {
grunt.log.writeln(('Cleaning all files from the injector list').green);
return starttag + endtag;
});
}
// Write the destination file.
if (templateContent !== templateOriginal || !grunt.file.exists(destination)) {
grunt.file.write(destination, templateContent);
} else {
grunt.log.ok('Nothing changed');
}
});
});
});
};
function getInjectorTagsRegExp (starttag, endtag) {
return new RegExp('([\t ]*)(' + escapeForRegExp(starttag) + ')(\\n|\\r|.)*?(' + escapeForRegExp(endtag) + ')', 'gi');
}
function getTag (tag, ext) {
return tag.replace(new RegExp( escapeForRegExp('{{ext}}'), 'g'), ext);
}
function getFilesFromBower (bowerFile) {
// Load bower dependencies via `wiredep` programmatic access
var dependencies = require('wiredep')({
'bowerJson': JSON.parse(fs.readFileSync(bowerFile, 'utf8')),
'directory': getBowerComponentsDir(bowerFile)
}
);
// Pluck out just the JS and CSS Dependencies
var filteredDependencies = _.pick(dependencies,'css','js');
// Concatenate into a filepaths array
return Object.keys(filteredDependencies).reduce(function (files, key) {
return files.concat(filteredDependencies[key]);
}, []);
}
function getBowerComponentsDir (bowerFile) {
var bowerBaseDir = path.dirname(bowerFile),
bowerRcFile = path.join(bowerBaseDir, '.bowerrc'),
dir = 'bower_components';
if (fs.existsSync(bowerRcFile)) {
try {
dir = JSON.parse(fs.readFileSync(bowerRcFile, 'utf8')).directory;
} catch (e) {
}
}
return path.join(bowerBaseDir, dir);
}
function unixify (path) {
return path.replace(/\\/g, '/');
}
function makeMinifiedIfNeeded (doMinify, filepath) {
if (!doMinify) {
return filepath;
}
var ext = path.extname(filepath);
var minFile = filepath.slice(0, -ext.length) + '.min' + ext;
if (fs.existsSync(minFile)) {
return minFile;
}
return filepath;
}
function toArray (arr) {
if (!Array.isArray(arr)) {
return arr ? [arr] : [];
}
return arr;
}
function addRootSlash (filepath) {
return filepath.replace(/^\/*([^\/])/, '/$1');
}
function removeRootSlash (filepath) {
return filepath.replace(/^\/+/, '');
}
function removeBasePath (basedir, filepath) {
return toArray(basedir).reduce(function (path, remove) {
if (remove && path.indexOf(remove) === 0) {
return path.slice(remove.length);
} else {
return path;
}
}, filepath);
}
function escapeForRegExp (str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
// Remove the entry whose transformed string is empty since we don't want to inject empty string.
function removeEmptySources (sources) {
return _.reject(sources, function (obj) {
return _.isEmpty(obj.transformed);
});
}
function getIndentedTransformations (sources, indent, lineEnding) {
var transformations = sources.map(function (s) {
return s.transformed;
});
transformations.unshift('');
transformations.push('');
return transformations.join(lineEnding + indent);
}
function getDefaultLineEnding(options, that, grunt) {
var contents = '';
// when destination file is a template
var destination = options.template || options.templateString;
// if destination file not found, try to guess from destFile
if (typeof destination === 'undefined') {
if (options.destFile && grunt.file.exists(that.files[0].dest)) {
destination = options.destFile;
} else {
//if the destination file does not exist yet
// try to figure out lineEnding through src files
if (!grunt.file.exists(that.files[0].dest)) {
destination = that.filesSrc[0];
} else {
destination = that.files[0].dest;
}
}
}
if (typeof destination === 'undefined') {
grunt.log.error('No template found, unable to guess line ending character.');
} else {
if (options.templateString) {
contents = options.templateString;
} else {
contents = String(grunt.file.read(destination));
}
}
return /\r\n/.test(contents) ? '\r\n' : '\n';
}