forked from dargmuesli/jonas-thelemann
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgulpfile.js
executable file
·530 lines (451 loc) · 14.7 KB
/
gulpfile.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
'use strict';
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const gAutoprefixer = require('gulp-autoprefixer');
const gBabelMinify = require('gulp-babel-minify');
const gBrowserify = require('browserify');
const gBuffer = require('gulp-buffer');
const gCached = require('gulp-cached');
const gComposer = require('gulp-composer');
const gDateDiff = require('date-diff');
const gDel = require('del');
const gEslint = require('gulp-eslint');
const gGulp = require('gulp');
const gJsdoc2md = require('gulp-jsdoc-to-markdown');
const gMergeStream = require('merge-stream');
const gSymlink = require('gulp-symlink');
const gPhplint = require('gulp-phplint');
const gPluginError = require('plugin-error');
const gRename = require('gulp-rename');
const gSass = require('gulp-sass');
const gSourcemaps = require('gulp-sourcemaps');
const gTap = require('gulp-tap');
const gThrough = require('through2');
const gVfs = require('vinyl-fs');
const gYarn = require('gulp-yarn');
const gZip = require('gulp-zip');
// const debug = require('gulp-debug');
// .pipe(debug())
let pkg = JSON.parse(fs.readFileSync('./package.json'));
const distFolder = 'dist/' + pkg.name + '/';
const distCredsFolder = distFolder + 'credentials/';
const distServFolder = distFolder + 'server/';
const distServResFolder = distServFolder + 'resources/';
const distServResDargBaseFolder = distServResFolder + 'dargmuesli/base/';
const distServResPackCompFolder = distServResFolder + 'packages/composer/';
const distServResPackYarnFolder = distServResFolder + 'packages/yarn/';
const productionFolder = 'production/';
const srcFolder = 'src/';
const srcStaticFolder = srcFolder + 'static/';
const srcJsFolder = srcFolder + 'js/';
const srcCssSassStyle = srcFolder + 'css/sass/style/';
const prodCredsGlob = productionFolder + pkg.name + '/credentials/**';
const srcStaticGlob = srcStaticFolder + '**';
const vendorGlob = 'vendor/**';
const distGlob = distFolder + '**';
let buildInProgress = false;
gGulp.src = gVfs.src;
gGulp.dest = gVfs.dest;
let sitemapExcludes = [
'!' + srcStaticFolder + 'tools/**/index.php'
];
let yarnArray = [
{
source: 'node_modules/chart.js/dist/Chart{.min,}.js',
target: 'chart.js/'
},
{
source: 'node_modules/dragula/dist/*.{css,js}',
target: 'dragula/'
},
{
source: 'node_modules/jquery/dist/jquery*.js',
target: 'jquery/'
},
{
source: 'node_modules/jquery-validation/dist/{localization/,jquery.validate}*.js',
target: 'jquery-validation/'
},
{
source: 'node_modules/js-cookie/src/*.js',
target: 'js-cookie/'
},
{
source: 'node_modules/later/later{.min,}.js',
target: 'later/'
},
{
source: 'node_modules/materialize-css/dist/**',
target: 'materialize-css/'
},
{
source: ['node_modules/moment/moment*.js', 'node_modules/moment/min/moment*.js'],
target: 'moment/'
},
{
source: ['node_modules/moment-timezone/moment-timezone.js', 'node_modules/moment-timezone/builds/*.js'],
target: 'moment-timezone/'
},
{
source: 'node_modules/prismjs/{components/*.js,plugins/**,themes/*.css,prism.js}',
target: 'prismjs/'
}
];
function composerClean() {
// Delete all files from composer package resources dist folder
return gDel(distServResPackCompFolder + '*');
}
exports.composerClean = composerClean;
function composerSrc() {
// Copy all composer libraries to composer package resources dist folder
return gGulp.src(vendorGlob)
.pipe(gGulp.dest(distServResPackCompFolder));
}
exports.composerSrc = composerSrc;
function composerUpdate() {
// Update composer
return gComposer('update', {
'async': false
});
}
exports.composerUpdate = composerUpdate;
function composerWatch() {
// Watch for any changes in composer files to copy changes
gGulp.watch([vendorGlob, 'composer.json'])
.on('all', function () {
composer_update();
composer_src();
});
}
exports.composerWatch = composerWatch;
function credentials() {
// Copy credentials to dist folder
return gGulp.src(prodCredsGlob, { dot: true })
.pipe(gCached('credentials'))
.pipe(gGulp.dest(distCredsFolder));
}
exports.credentials = credentials;
function credentialsWatch() {
// Watch for any changes in credential files to copy changes
// Does currently not work as dotfiles cannot be watched with chokidar
gGulp.watch(prodCredsGlob)
.on('all', function () {
credentials();
});
}
exports.credentialsWatch = credentialsWatch;
function cssCompressed() {
return gGulp.src(srcCssSassStyle + 'style.scss', { allowEmpty: true })
.pipe(gRename({
extname: '.min.css'
}))
.pipe(gSourcemaps.init())
.pipe(gSass({
outputStyle: 'compressed'
}).on('error', gSass.logError))
.pipe(gAutoprefixer())
.pipe(gSourcemaps.write('.'))
.pipe(gGulp.dest(distServResDargBaseFolder));
}
exports.cssCompressed = cssCompressed;
function cssExtended() {
return gGulp.src(srcCssSassStyle + 'style.scss', { allowEmpty: true })
.pipe(gSourcemaps.init())
.pipe(gSass({
outputStyle: 'expanded'
}).on('error', gSass.logError))
.pipe(gAutoprefixer())
.pipe(gSourcemaps.write('.'))
.pipe(gGulp.dest(distServResDargBaseFolder));
}
exports.cssExtended = cssExtended;
function cssSrcWatch() {
// Watch for any changes in source files to copy changes
gGulp.watch(srcCssSassStyle)
.on('all', function () {
css_compressed();
css_extended();
});
}
exports.cssSrcWatch = cssSrcWatch;
function distClean() {
// Delete all files from dist folder
return gDel([distFolder + '**', '!' + distFolder.replace(/\/$/, ''), path.dirname(distFolder) + '/' + pkg.name + '.zip']);
}
exports.distClean = distClean;
function getChangeFreq(lastModification) {
let interval = new gDateDiff(new Date(), new Date(lastModification));
if (interval.years() < 5) {
if (interval.years() < 1) {
if (interval.months() < 1) {
if (interval.days() < 7) {
if (interval.days() < 1) {
return 'hourly';
} else {
return 'daily';
}
} else {
return 'weekly';
}
} else {
return 'monthly';
}
} else {
return 'yearly';
}
} else {
return 'never';
}
}
function jsDoc() {
return gGulp.src(srcJsFolder + '**/*.js')
.pipe(gJsdoc2md())
.pipe(gRename(function (path) {
path.extname = '.md'
}))
.pipe(gGulp.dest('docs/js/'));
}
exports.jsDoc = jsDoc;
function jsLint() {
return gGulp.src(srcJsFolder + '**/*.js')
// Lint JavaScript
.pipe(gEslint())
// Output to console
.pipe(gEslint.format())
// Fail on error
.pipe(gEslint.failAfterError());
}
exports.jsLint = jsLint;
function jsSrc() {
return gGulp.src(srcJsFolder + 'functions.js', { allowEmpty: true, read: false })
.pipe(gTap(function (file) {
file.contents = gBrowserify(file.path, { debug: true, standalone: 'Dargmuesli' }).transform('babelify', { presets: ['@babel/preset-env'] }).bundle();
}))
.pipe(gBuffer())
.pipe(gGulp.dest(distServResDargBaseFolder))
.pipe(gRename({
extname: '.min.js'
}))
.pipe(gBabelMinify())
.pipe(gGulp.dest(distServResDargBaseFolder));
}
exports.jsSrc = jsSrc;
function jsSrcWatch() {
// Watch for any changes in source files to copy changes
gGulp.watch(srcJsFolder)
.on('all', function () {
js_src();
});
}
exports.jsSrcWatch = jsSrcWatch;
function phpLint() {
return gGulp.src(srcFolder + '**/*.php')
// Lint and suppress output of valid files
.pipe(gPhplint('', { skipPassedFiles: true }))
// Fail on error
.pipe(gPhplint.reporter(function (file) {
let report = file.phplintReport || {};
if (report.error) {
throw new gPluginError('gulp-eslint', {
plugin: 'PHPLintError',
message: report.message + ' on line ' + report.line + ' of ' + report.filename
});
}
}));
}
exports.phpLint = phpLint;
function sitemap() {
let sitemapPath = path.resolve(distServFolder + 'sitemap/sitemap.xml');
let targetPath = __dirname + '/' + srcStaticFolder;
path.dirname(sitemapPath)
.split(path.sep)
.reduce((currentPath, folder) => {
currentPath += folder + path.sep;
if (!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
return currentPath;
}, '');
fs.writeFile(sitemapPath, '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', (error) => { if (error) throw error; });
return gGulp.src([srcStaticFolder + '**/index.php'].concat(sitemapExcludes))
.pipe(
gThrough.obj(function (file, enc, cb) {
if (!fs.existsSync(file.dirname + '/.hidden') && file.dirname.indexOf('migrations') == -1) {
exec('git log -1 --format="%aI" -- ' + file.path, function (exec_error, stdout) {
let loc = file.dirname.replace(path.resolve(targetPath), 'https://' + pkg.name).replace(/\\/g, '/').replace();
let priority = (Math.round((1 - ((loc.match(/\//g) || []).length - 2) * 0.1) * 10) / 10).toFixed(1);
let url = `
<url>
<loc>${loc}/</loc>
<lastmod>${stdout.trim()}</lastmod>
<changefreq>${getChangeFreq(stdout.trim())}</changefreq>
<priority>${priority > 0 ? priority : 0}</priority>
</url>`;
fs.appendFile(sitemapPath, url, (error) => { if (error) throw error; cb(); });
if (exec_error) {
console.error(`exec error: ${exec_error}`);
return;
}
});
} else {
cb();
}
this.push(file);
})
)
.on('end', function () { fs.appendFile(sitemapPath, '\n</urlset>', (error) => { if (error) throw error; }); });
}
exports.sitemap = sitemap;
function staticSrc() {
// Copy static files to dist folder
buildInProgress = true;
return new Promise(function (resolve, reject) {
gGulp.src(srcStaticGlob, { dot: true })
.pipe(gCached('staticSrc'))
.on('error', reject)
.pipe(gGulp.dest(distServFolder))
.on('end', resolve);
}).then(function () {
buildInProgress = false;
});
}
exports.staticSrc = staticSrc;
function staticSrcWatch() {
// Watch for any changes in source files to copy changes
gGulp.watch(srcStaticGlob)
.on('all', function () {
staticSrc();
});
}
exports.staticSrcWatch = staticSrcWatch;
function symlinks(callback) {
// Create all necessary symlinks
// "gulp-symlink" is still required as Gulp's/Vinyl-fs's symlink function is incapable of changing the symlink's name
const streamArray = [];
if (typeof symlinkArray !== 'undefined' && symlinkArray) {
symlinkArray.forEach(element => {
streamArray.push(
gGulp.src(element.source)
.pipe(gSymlink(element.target))
);
});
}
if (streamArray.length != 0) {
return gMergeStream(streamArray);
} else {
return callback();
}
}
exports.symlinks = symlinks;
function yarnClean() {
// Delete all files from yarn package resources dist folder
return gDel(distServResPackYarnFolder + '*');
}
exports.yarnClean = yarnClean;
function yarnSrc(callback) {
// Copy front-end javascript libraries to yarn package resources dist folder
const streamArray = [];
if (typeof yarnArray !== 'undefined' && yarnArray) {
yarnArray.forEach(element => {
streamArray.push(
gGulp.src(element.source)
.pipe(gGulp.dest(distServResPackYarnFolder + element.target)),
);
});
}
if (streamArray.length != 0) {
return gMergeStream(streamArray);
} else {
return callback();
}
}
exports.yarnSrc = yarnSrc;
function yarnUpdate() {
// Update package dependencies
return gGulp.src('package.json')
.pipe(gYarn({ args: '--no-cache --frozen-lockfile' }));
}
exports.yarnUpdate = yarnUpdate;
function yarnWatch() {
// Watch for any changes in yarn files to copy changes
gGulp.watch(['package.json'])
.on('all', function () {
yarn_update();
yarn_src();
});
}
exports.yarnWatch = yarnWatch;
function zip() {
// Build a zip file containing the dist folder
return gGulp.src(distGlob, { dot: true })
.pipe(gZip(pkg.name + '.zip'))
.pipe(gGulp.dest(path.dirname(distFolder)));
}
exports.zip = zip;
function zipWaiter() {
// Do not zip while a build is still in progress
if (buildInProgress) {
setTimeout(zipWaiter, 100);
} else {
zip();
}
}
function zipWatch() {
// Watch for any changes to start a zip rebuild
gGulp.watch(distGlob)
.on('all', function (event, path) {
console.log(event + ': "' + path + '". Running tasks...');
zipWaiter();
});
}
exports.zipWatch = zipWatch;
// Build tasks
gGulp.task(
'build',
gGulp.series(
distClean,
gGulp.series(
gGulp.parallel(
credentials,
cssCompressed,
cssExtended,
jsDoc,
jsLint,
jsSrc,
phpLint,
sitemap,
staticSrc
),
// Yarn needs to be in series with phpLint
// as the Yarn task does not return on linting errors.
gGulp.parallel(
gGulp.series(
composerUpdate,
composerSrc
),
gGulp.series(
yarnUpdate,
yarnSrc
)
)
),
symlinks,
zip
)
);
gGulp.task(
'default',
gGulp.series(
'build',
gGulp.parallel(
composerWatch,
credentialsWatch,
cssSrcWatch,
jsSrcWatch,
staticSrcWatch,
yarnWatch,
zipWatch
)
)
);