This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
gulp-utils.js
359 lines (322 loc) · 11.4 KB
/
gulp-utils.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
const gulp = require('gulp');
const through2 = require('through2');
const gutil = require('gulp-util');
const autoprefixer = require('autoprefixer');
const gulpPostcss = require('gulp-postcss');
const Buffer = require('buffer').Buffer;
const fs = require('fs');
const path = require('path');
const findModule = require('../config/ngModuleData.js');
exports.humanizeCamelCase = function(str) {
switch (str) {
case 'fabSpeedDial':
return 'FAB Speed Dial';
case 'fabToolbar':
return 'FAB Toolbar';
default:
return str.charAt(0).toUpperCase() + str.substring(1).replace(/[A-Z]/g, function($1) {
return ' ' + $1.toUpperCase();
});
}
};
/**
* Copy all the demo assets to the dist directory
* NOTE: this excludes the modules demo .js,.css, .html files
*/
exports.copyDemoAssets = function(component, srcDir, distDir) {
gulp.src(srcDir + component + '/demo*/')
.pipe(through2.obj(copyAssetsFor));
function copyAssetsFor(demo, enc, next){
const demoID = component + "/" + path.basename(demo.path);
const demoDir = demo.path + "/**/*";
const notJS = '!' + demoDir + '.js';
const notCSS = '!' + demoDir + '.css';
const notHTML= '!' + demoDir + '.html';
gulp.src([demoDir, notJS, notCSS, notHTML])
.pipe(gulp.dest(distDir + demoID));
next();
}
};
// Gives back a pipe with an array of the parsed data from all of the module's demos
// @param moduleName module name to parse
// @param fileTasks: tasks to run on the files found in the demo's folder
// Emits demo objects
exports.readModuleDemos = function(moduleName, fileTasks) {
const name = moduleName.split('.').pop();
return gulp.src('src/{components,services}/' + name + '/demo*/')
.pipe(through2.obj(function(demoFolder, enc, next) {
const demoId = name + path.basename(demoFolder.path);
const demo = {
ngModule: '',
id: demoId,
css:[], html:[], js:[]
};
gulp.src(demoFolder.path + '/**/*', { base: path.dirname(demoFolder.path) })
.pipe(fileTasks(demoId))
.pipe(through2.obj(function(file, enc, cb) {
if (/index.html$/.test(file.path)) {
demo.moduleName = moduleName;
demo.name = path.basename(demoFolder.path);
demo.label = exports.humanizeCamelCase(path.basename(demoFolder.path).replace(/^demo/, ''));
demo.id = demoId;
demo.index = toDemoObject(file);
} else {
const fileType = path.extname(file.path).substring(1);
if (fileType === 'js') {
demo.ngModule = demo.ngModule || findModule.any(file.contents.toString());
}
demo[fileType] && demo[fileType].push(toDemoObject(file));
}
cb();
}, function() {
next(null, demo);
}));
function toDemoObject(file) {
return {
contents: file.contents.toString(),
name: path.basename(file.path),
label: path.basename(file.path),
fileType: path.extname(file.path).substring(1),
outputPath: 'demo-partials/' + name + '/' + path.basename(demoFolder.path) + '/' + path.basename(file.path)
};
}
}));
};
const pathsForModules = {};
exports.pathsForModule = function(name) {
return pathsForModules[name] || lookupPath();
function lookupPath() {
gulp.src('src/{services,components,core}/**/*')
.pipe(through2.obj(function(file, enc, next) {
const module = findModule.any(file.contents);
if (module && module.name === name) {
const modulePath = file.path.split(path.sep).slice(0, -1).join(path.sep);
pathsForModules[name] = modulePath + '/**';
}
next();
}));
return pathsForModules[name];
}
};
/**
* @param {string} name module name
* @returns {*}
*/
exports.filesForModule = function(name) {
if (pathsForModules[name]) {
return srcFiles(pathsForModules[name]);
} else {
return gulp.src('src/{services,components,core}/**/*')
.pipe(through2.obj(function(file, enc, next) {
const module = findModule.any(file.contents);
if (module && (module.name === name)) {
const modulePath = file.path.split(path.sep).slice(0, -1).join(path.sep);
pathsForModules[name] = modulePath + '/**';
const self = this;
srcFiles(pathsForModules[name]).on('data', function(data) {
self.push(data);
});
}
next();
}));
}
function srcFiles(path) {
return gulp.src(path)
.pipe(through2.obj(function(file, enc, next) {
if (file.stat.isFile()) next(null, file);
else next();
}));
}
};
exports.appendToFile = function(filePath) {
let bufferedContents;
return through2.obj(function(file, enc, next) {
bufferedContents = file.contents.toString('utf8') + '\n';
next();
}, function(done) {
const existing = fs.readFileSync(filePath, 'utf8');
bufferedContents = existing + '\n' + bufferedContents;
const outputFile = new gutil.File({
cwd: process.cwd(),
base: path.dirname(filePath),
path: filePath,
contents: Buffer.from(bufferedContents)
});
this.push(outputFile);
done();
});
};
exports.buildNgMaterialDefinition = function() {
let srcBuffer = [];
const modulesSeen = [];
return through2.obj(function(file, enc, next) {
const module = findModule.material(file.contents);
if (module) modulesSeen.push(module.name);
srcBuffer.push(file);
next();
}, function(done) {
const self = this;
const requiredLibs = ['ng', 'ngAnimate', 'ngAria'];
const dependencies = JSON.stringify(requiredLibs.concat(modulesSeen));
const ngMaterialModule = "angular.module('ngMaterial', " + dependencies + ');';
const angularFile = new gutil.File({
base: process.cwd(),
path: process.cwd() + '/ngMaterial.js',
contents: Buffer.from(ngMaterialModule)
});
// Elevate ngMaterial module registration to first in queue
self.push(angularFile);
srcBuffer.forEach(function(file) {
self.push(file);
});
srcBuffer = [];
done();
});
};
function moduleNameToClosureName(name) {
// For Closure, all modules start with "ngmaterial". We specifically don't use `ng.`
// because it conflicts with other packages under `ng.`.
return 'ng' + name;
}
exports.addJsWrapper = function(enforce) {
return through2.obj(function(file, enc, next) {
const module = findModule.any(file.contents);
if (!!enforce || module) {
file.contents = Buffer.from([
enforce ? '(function(){' : '(function( window, angular, undefined ){',
'"use strict";\n',
file.contents.toString(),
enforce ? '})();' : '})(window, window.angular);'
].join('\n'));
}
this.push(file);
next();
});
};
exports.addClosurePrefixes = function() {
return through2.obj(function(file, enc, next) {
const module = findModule.any(file.contents);
if (module) {
const closureModuleName = moduleNameToClosureName(module.name);
const requires = (module.dependencies || []).sort().map(function(dep) {
if (dep.indexOf(module.name) === 0 || /material\..+/g.test(dep) === false) return '';
return 'goog.require(\'' + moduleNameToClosureName(dep) + '\');';
}).join('\n');
file.contents = Buffer.from([
'goog.provide(\'' + closureModuleName + '\');',
requires,
file.contents.toString(),
closureModuleName + ' = angular.module("' + module.name + '");'
].join('\n'));
}
this.push(file);
next();
});
};
exports.buildModuleBower = function(name, version) {
return through2.obj(function(file, enc, next) {
this.push(file);
const module = findModule.any(file.contents);
if (module) {
const bowerDeps = {};
(module.dependencies || []).forEach(function(dep) {
const convertedName = 'angular-material-' + dep.split('.').pop();
bowerDeps[convertedName] = version;
});
const bowerContents = JSON.stringify({
name: 'angular-material-' + name,
version: version,
dependencies: bowerDeps
}, null, 2);
const bowerFile = new gutil.File({
base: file.base,
path: file.base + '/bower.json',
contents: Buffer.from(bowerContents)
});
this.push(bowerFile);
}
next();
});
};
exports.hoistScssVariables = function() {
return through2.obj(function(file, enc, next) {
const contents = file.contents.toString().split('\n');
let lastVariableLine = -1;
let openCount = 0;
let closeCount = 0;
let openBlock = false;
for (let currentLine = 0; currentLine < contents.length; ++currentLine) {
const line = contents[currentLine];
if (openBlock || /^\s*\$/.test(line) && !/^\s+/.test(line)) {
openCount += (line.match(/\(/g) || []).length;
closeCount += (line.match(/\)/g) || []).length;
openBlock = openCount !== closeCount;
const variable = contents.splice(currentLine, 1)[0];
contents.splice(++lastVariableLine, 0, variable);
}
}
file.contents = Buffer.from(contents.join('\n'));
this.push(file);
next();
});
};
/**
* Find Sass @use module imports and ensure that they are at the very top of the Sass prior to
* running it through the Sass compiler. This also deduplicates @use statements to avoid errors.
*/
exports.hoistScssAtUseStatements = function() {
return through2.obj(function(file, enc, next) {
const contents = file.contents.toString().split('\n');
let lastAtUseLineNumber = -1;
const atUseStatements = [];
let openCount = 0;
let closeCount = 0;
let openBlock = false;
for (let currentLineNumber = 0; currentLineNumber < contents.length; ++currentLineNumber) {
const line = contents[currentLineNumber];
if (openBlock || /^\s*@use\s/.test(line) && !/^\s+/.test(line)) {
openCount += (line.match(/\(/g) || []).length;
closeCount += (line.match(/\)/g) || []).length;
openBlock = openCount !== closeCount;
// Don't move statements from line 0 to line 0.
if (currentLineNumber > 0) {
const atUseStatement = contents.splice(currentLineNumber, 1)[0];
// Don't write duplicate @use statements to avoid
// 'There's already a module with namespace x' errors.
if (!atUseStatements.includes(atUseStatement)) {
atUseStatements.push(atUseStatement);
contents.splice(++lastAtUseLineNumber, 0, atUseStatement);
}
}
}
}
file.contents = Buffer.from(contents.join('\n'));
this.push(file);
next();
});
};
exports.cssToNgConstant = function(ngModule, factoryName) {
return through2.obj(function(file, enc, next) {
const template = '(function(){ \nangular.module("%1").constant("%2", "%3"); \n})();\n\n';
const output = file.contents.toString().replace(/\n/g, '').replace(/"/g,'\\"');
const jsFile = new gutil.File({
base: file.base,
path: file.path.replace('css', 'js'),
contents: Buffer.from(
template.replace('%1', ngModule)
.replace('%2', factoryName)
.replace('%3', output)
)
});
this.push(jsFile);
next();
});
};
/**
* Use the configuration in the "browserslist" field of the package.json as recommended
* by the autoprefixer docs.
* @returns {NodeJS.ReadWriteStream | *}
*/
exports.autoprefix = function() {
return gulpPostcss([autoprefixer()]);
};