-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathgulpfile.js
1085 lines (890 loc) · 30.1 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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*global require, process, __dirname*/
'use strict';
// REQUIRES -------------------------------------------------------------------
var
path = require('path'),
globule = require('globule'),
http = require ('http'),
fs = require('fs'),
ncp = require('ncp').ncp,
chalk = require('chalk'),
_ = require('lodash'),
prompt = require('inquirer').prompt,
sequence = require('run-sequence'),
ProgressBar = require('progress'),
stylish = require('jshint-stylish'),
open = require('open'),
ghdownload = require('github-download'),
browserSync = require('browser-sync'),
psi = require('psi'),
gulp = require('gulp'),
plugins = require('gulp-load-plugins')({
config: path.join(__dirname, 'package.json')
}),
flags = require('minimist')(process.argv.slice(2))
;
// VARS -----------------------------------------------------------------------
var
gitConfig = {
user: 'flovan',
repo: 'headstart-boilerplate',
ref: '1.2.1'
},
cwd = process.cwd(),
tmpFolder = '.tmp',
assetsFolder = 'assets',
stdoutBuffer = [],
lrStarted = false,
htmlminOptions = {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
useShortDoctype: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
minifyJS: true,
minifyCSS: true
},
isProduction = ( flags.production || flags.p ) || false,
isServe = ( flags.serve || flags.s ) || false,
isOpen = ( flags.open || flags.o ) || false,
isEdit = ( flags.edit || flags.e ) || false,
isVerbose = flags.verbose || false,
isTunnel = ( flags.tunnel || flags.t ) || false,
tunnelUrl = null,
isPSI = flags.psi || false,
config = null,
bar = null
;
// LOGGING --------------------------------------------------------------------
//
if (!isVerbose) {
// To get a better grip on logging by either gulp-util, console.log or direct
// writing to process.stdout, a hook is applied to stdout when not running
// in --vebose mode
require('./lib/hook.js')(process.stdout).hook('write', function (msg, encoding, fd, write) {
// Validate message
msg = validForWrite(msg);
// If the message is not suited for output, block it
if (!msg) {
return;
}
if (msg.length === 1) return;
// There is no progress bar, so just write
if (_.isNull(bar)) {
write(msg);
return;
}
// There is a progress bar, but it hasn't completed yet, so buffer
if (!bar.complete) {
stdoutBuffer.push(msg);
return;
}
// There is a buffer, prepend a newline to the array
if(stdoutBuffer.length) {
stdoutBuffer.unshift('\n');
}
// Write out the buffer untill its empty
while (stdoutBuffer.length) {
write(stdoutBuffer.shift());
}
// Finally, just write out
write(msg);
});
// Map console.warn to console.log to make sure gulp-sassgraph errors
// get validated by the code above
/*console.warn = console.log; /*function () {
var args = Array.prototype.slice.call(arguments);
console.error('passing this to console.log: ', args);
console.log.apply(console, args);
}*/
}
// INIT -----------------------------------------------------------------------
//
gulp.task('init', function (cb) {
// Get all files in working directory
// Exclude . files (such as .DS_Store on OS X)
var cwdFiles = _.remove(fs.readdirSync(cwd), function (file) {
return file.substring(0,1) !== '.';
});
// If there are any files
if (cwdFiles.length > 0) {
// Make sure the user knows what is about to happen
console.log(chalk.yellow.inverse('\nThe current directory is not empty!'));
prompt({
type: 'confirm',
message: 'Initializing will empty the current directory. Continue?',
name: 'override',
default: false
}, function (answer) {
if (answer.override) {
// Make really really sure that the user wants this
prompt({
type: 'confirm',
message: 'Removed files are gone forever. Continue?',
name: 'overridconfirm',
default: false
}, function (answer) {
if (answer.overridconfirm) {
// Clean up directory, then start downloading
console.log(chalk.grey('\nEmptying current directory'));
sequence('clean-tmp', 'clean-cwd', downloadBoilerplateFiles);
}
// User is unsure, quit process
else process.exit(0);
});
}
// User is unsure, quit process
else process.exit(0);
});
}
// No files, start downloading
else {
console.log('\n');
downloadBoilerplateFiles();
}
cb(null);
});
// BUILD ----------------------------------------------------------------------
//
gulp.task('build', function (cb) {
// Load the config.json file
console.log(chalk.grey('\nLoading config.json...'));
fs.readFile('config.json', 'utf8', function (err, data) {
if (err) {
console.log(chalk.red('✘ Cannot find config.json. Have you initiated Headstart through `headstart init?'), err);
process.exit(0);
}
// Try parsing the config data as JSON
try {
config = JSON.parse(data);
} catch (err) {
console.log(chalk.red('✘ The config.json file is not valid json. Aborting.'), err);
process.exit(0);
}
// Allow customization of gulp-htmlmin through `config.json`
if (!_.isNull(config.htmlminOptions)) {
htmlminOptions = _.assign({}, htmlminOptions, config.htmlminOptions);
}
assetsFolder = config.assetsFolder || assetsFolder;
// Instantiate a progressbar when not in verbose mode
if (!isVerbose) {
bar = new ProgressBar(chalk.grey('Building ' + (isProduction ? 'production' : 'development') + ' version [:bar] :percent done'), {
complete: '#',
incomplete: '-',
total: 8
});
updateBar();
} else {
console.log(chalk.grey('Building ' + (isProduction ? 'production' : 'development') + ' version...'));
}
// Run build tasks
// Serve files if Headstart was run with the --serve flag
sequence(
'clean-export',
[
'sass-main',
'scripts-main',
'images',
'other'
],
'templates',
'manifest',
'uncss',
function () {
console.log(chalk.green((!isProduction ? '\n' : '') + '✔ Build complete'));
if(isServe) {
gulp.start('server');
}
cb(null);
}
);
});
});
// CLEAN ----------------------------------------------------------------------
//
gulp.task('clean-export', function (cb) {
// Remove export folder and files
return gulp.src([
config.export_templates,
config.export_assets + '/' + assetsFolder
], {read: false})
.pipe(plugins.rimraf({force: true}))
.on('end', updateBar)
;
});
gulp.task('clean-cwd', function (cb) {
// Remove cwd files
return gulp.src(cwd + '/*', {read: false})
.pipe(plugins.rimraf({force: true}))
;
});
gulp.task('clean-tmp', function (cb) {
// Remove temp folder
return gulp.src(tmpFolder, {read: false})
.pipe(plugins.rimraf({force: true}))
;
});
gulp.task('clean-rev', function (cb) {
verbose(chalk.grey('Running task "clean-rev"'));
// Clean all revision files but the latest ones
return gulp.src(config.export_assets + '/' + assetsFolder + '/**/*.*', {read: false})
.pipe(plugins.revOutdated(1))
.pipe(plugins.rimraf({force: true}))
;
});
// SASS -----------------------------------------------------------------------
//
gulp.task('sass-main', ['sass-ie'], function (cb) {
// Flag to catch empty streams
// https://github.com/floatdrop/gulp-watch/issues/87
var isEmptyStream = true;
verbose(chalk.grey('Running task "sass-main"'));
// Process the .scss files
// While serving, this task opens a continuous watch
return gulp.src([
assetsFolder + '/sass/*.{scss, sass, css}',
'!' + assetsFolder + '/sass/*ie.{scss, sass, css}'
])
.pipe(plugins.plumber())
.pipe(plugins.rubySass({ style: (isProduction ? 'compressed' : 'nested') }))
.pipe(plugins.if(config.combineMediaQueries, plugins.combineMediaQueries()))
.pipe(plugins.autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(plugins.if(config.revisionCaching, plugins.rev()))
// TODO: When minifyCSS bug is fixed, drop the noAdvanced feature
// (https://github.com/jakubpawlowicz/clean-css/issues/375)
.pipe(plugins.if(isProduction, plugins.minifyCss({ compatibility: 'ie8', noAdvanced: true })))
.pipe(plugins.if(isProduction, plugins.rename({suffix: '.min'})))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/css'))
.on('data', function (cb) {
// If revisioning is on, run templates again so the refresh contains
// the newer stylesheet
if (lrStarted && config.revisionCaching) {
gulp.start('templates');
}
// Continue the stream
this.resume();
})
.on('end', updateBar)
.pipe(plugins.if(lrStarted && !config.revisionCaching, browserSync.reload({stream:true})))
;
});
gulp.task('sass-ie', function (cb) {
// Flag to catch empty streams
// https://github.com/floatdrop/gulp-watch/issues/87
var isEmptyStream = true;
verbose(chalk.grey('Running task "sass-ie"'));
// Process the .scss files
// While serving, this task opens a continuous watch
return gulp.src([
assetsFolder + '/sass/*ie.{scss, sass, css}'
])
.pipe(plugins.plumber())
.pipe(plugins.rubySass({ style: (isProduction ? 'compressed' : 'nested') }))
.pipe(plugins.rename({suffix: '.min'}))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/css'))
;
});
// UNCSS ----------------------------------------------------------------------
//
// Clean up unused CSS styles
gulp.task('uncss', function (cb) {
// Quit this task if not configured through config
if (!isProduction || !config.useUncss) {
updateBar();
cb(null);
return;
}
verbose(chalk.grey('Running task "uncss-main"'));
// Grab all templates / partials / layout parts / etc
var templates = globule.find([config.export_templates + '/**/*.*']);
// Grab all css files and run them through Uncss, then overwrite
// the originals with the new ones
return gulp.src(config.export_assets + '/' + assetsFolder + '/css/*.css')
.pipe(plugins.bytediff.start())
.pipe(plugins.uncss({
html: templates || [],
ignore: config.uncssIgnore || []
}))
.pipe(plugins.bytediff.stop(function (data) {
updateBar();
data.percent = Math.round(data.percent*100);
data.savings = Math.round(data.savings/1024);
return chalk.grey('' + data.fileName + ' is now ') + chalk.green(data.percent + '% ' + (data.savings > 0 ? 'smaller' : 'larger')) + chalk.grey(' (saved ' + data.savings + 'KB)');
}))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/css'))
;
});
// SCRIPTS --------------------------------------------------------------------
//
// JSHint options: http://www.jshint.com/docs/options/
gulp.task('hint-scripts', function (cb) {
// Quit this task if hinting isn't turned on
if (!config.hint) {
cb(null);
return;
}
verbose(chalk.grey('Running task "hint-scripts"'));
// Hint all non-lib js files and exclude _ prefixed files
return gulp.src([
assetsFolder + '/js/*.js',
assetsFolder + '/js/core/*.js',
'!_*.js'
])
.pipe(plugins.plumber())
.pipe(plugins.jshint('.jshintrc'))
.pipe(plugins.jshint.reporter(stylish))
;
});
gulp.task('scripts-main', ['hint-scripts', 'scripts-view', 'scripts-ie'], function () {
var files = [
assetsFolder + '/js/libs/jquery*.js',
assetsFolder + '/js/libs/ender*.js',
(isProduction ? '!' : '') + assetsFolder + '/js/libs/dev/*.js',
assetsFolder + '/js/libs/**/*.js',
// TODO: remove later
assetsFolder + '/js/core/**/*.js',
//
assetsFolder + '/js/*.js',
'!' + assetsFolder + '/js/view-*.js',
'!**/_*.js'
];
verbose(chalk.grey('Running task "scripts-main"'));
if (isProduction) {
var numFiles = globule.find(files).length;
console.log(chalk.green('✄ Concatenated ' + numFiles + ' JS files'));
}
// Process .js files
// Files are ordered for dependency sake
return gulp.src(files, {base: '' + assetsFolder + '/js'})
.pipe(plugins.plumber())
.pipe(plugins.deporder())
.pipe(plugins.if(isProduction, plugins.stripDebug()))
.pipe(plugins.if(isProduction, plugins.concat('core-libs.js')))
.pipe(plugins.if(config.revisionCaching, plugins.rev()))
.pipe(plugins.if(isProduction, plugins.rename({extname: '.min.js'})))
.pipe(plugins.if(isProduction, plugins.uglify()))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/js'))
.on('end', updateBar)
;
});
gulp.task('scripts-view', function (cb) {
verbose(chalk.grey('Running task "scripts-view"'));
return gulp.src(assetsFolder + '/js/view-*.js')
.pipe(plugins.plumber())
.pipe(plugins.if(config.revisionCaching, plugins.rev()))
.pipe(plugins.if(isProduction, plugins.rename({suffix: '.min'})))
.pipe(plugins.if(isProduction, plugins.stripDebug()))
.pipe(plugins.if(isProduction, plugins.uglify()))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/js'))
;
});
gulp.task('scripts-ie', function (cb) {
verbose(chalk.grey('Running task "scripts-ie"'));
// Process .js files
// Files are ordered for dependency sake
gulp.src([
assetsFolder + '/js/ie/head/**/*.js',
'!**/_*.js'
])
.pipe(plugins.plumber())
.pipe(plugins.deporder())
.pipe(plugins.concat('ie-head.js'))
.pipe(plugins.if(isProduction, plugins.stripDebug()))
.pipe(plugins.rename({extname: '.min.js'}))
.pipe(plugins.uglify())
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/js'));
gulp.src([
assetsFolder + '/js/ie/body/**/*.js',
'!**/_*.js'
])
.pipe(plugins.plumber())
.pipe(plugins.deporder())
.pipe(plugins.concat('ie-body.js'))
.pipe(plugins.if(isProduction, plugins.stripDebug()))
.pipe(plugins.rename({extname: '.min.js'}))
.pipe(plugins.uglify())
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/js'));
cb(null);
});
// IMAGES ---------------------------------------------------------------------
//
gulp.task('images', function (cb) {
verbose(chalk.grey('Running task "images"'));
// Make a copy of the favicon.png, and make a .ico version for IE
// Move to root of export folder
gulp.src(assetsFolder + '/images/icons/favicon.png')
.pipe(plugins.rename({extname: '.ico'}))
//.pipe(plugins.if(config.revisionCaching, plugins.rev()))
.pipe(gulp.dest(config.export_misc))
;
// Grab all image files, filter out the new ones and copy over
// In --production mode, optimize them first
return gulp.src([
assetsFolder + '/images/**/*',
'!_*'
])
.pipe(plugins.plumber())
.pipe(plugins.newer(config.export_assets + '/' + assetsFolder + '/images'))
.pipe(plugins.if(isProduction, plugins.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
//.pipe(plugins.if(config.revisionCaching, plugins.rev()))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder + '/images'))
.pipe(plugins.if(lrStarted, browserSync.reload({stream:true})))
;
});
// OTHER ----------------------------------------------------------------------
//
gulp.task('other', ['misc'], function (cb) {
verbose(chalk.grey('Running task "other"'));
// Make sure other files and folders are copied over
// eg. fonts, videos, ...
return gulp.src([
assetsFolder + '/**/*',
'!' + assetsFolder + '/sass',
'!' + assetsFolder + '/sass/**/*',
'!' + assetsFolder + '/js/**/*',
'!' + assetsFolder + '/images/**/*',
'!_*'
])
.pipe(plugins.plumber())
//.pipe(plugins.if(config.revisionCaching, plugins.rev()))
.pipe(gulp.dest(config.export_assets + '/' + assetsFolder))
.on('end', updateBar)
;
});
// MISC -----------------------------------------------------------------------
//
gulp.task('misc', function (cb) {
// In --production mode, copy over all the other stuff
if (isProduction) {
verbose(chalk.grey('Running task "misc"'));
// Make a functional version of the htaccess.txt
gulp.src('misc/htaccess.txt')
.pipe(plugins.rename('.htaccess'))
.pipe(gulp.dest(config.export_misc))
;
gulp.src(['misc/*', '!misc/htaccess.txt', '!_*'])
.pipe(gulp.dest(config.export_misc))
;
}
cb(null);
});
// TEMPLATES ------------------------------------------------------------------
//
gulp.task('templates', ['clean-rev'], function (cb) {
verbose(chalk.grey('Running task "templates"'));
// If assebly is off, export all folders and files
if (!config.assemble_templates) {
gulp.src(['templates/**/*', '!templates/*.*', '!_*'])
.pipe(gulp.dest(config.export_templates));
}
// Find number of "root" templates to parse and keep count
var numTemplates = globule.find(['templates/*.*', '!_*']).length,
count = 0,
unvalidatedFiles = [];
// Go over all root template files
gulp.src(['templates/*.*', '!_*'])
.pipe(plugins.tap(function (htmlFile) {
var
// Extract bits from filename
baseName = path.basename(htmlFile.path),
nameParts = baseName.split('.'),
ext = _.without(nameParts, _.first(nameParts)).join('.'),
viewBaseName = _.last(nameParts[0].split('view-')),
// Make sure Windows paths work down below
cwdParts = cwd.replace(/\\/g, '/').split('/'),
// Make a collection of file globs
// Production will get 1 file only
// Development gets raw base files
injectItems = isProduction ?
[
config.export_assets + '/' + assetsFolder + '/js/core-libs*.min.js',
config.export_assets + '/' + assetsFolder + '/js/view-' + viewBaseName + '*.min.js'
]
:
[
config.export_assets + '/' + assetsFolder + '/js/libs/jquery*.js',
config.export_assets + '/' + assetsFolder + '/js/libs/ender*.js',
(isProduction ? '!' : '') + config.export_assets + '/' + assetsFolder + '/js/libs/dev/*.js',
config.export_assets + '/' + assetsFolder + '/js/libs/*.js',
config.export_assets + '/' + assetsFolder + '/js/core/*.js',
config.export_assets + '/' + assetsFolder + '/js/**/*.js',
'!' + config.export_assets + '/' + assetsFolder + '/**/_*.js',
'!' + config.export_assets + '/' + assetsFolder + '/js/ie*.js'
]
;
// Include the css
injectItems.push(config.export_assets + '/' + assetsFolder + '/css/main*.css');
injectItems.push(config.export_assets + '/' + assetsFolder + '/css/view-' + viewBaseName + '*.css');
// Put items in a stream and order dependencies
injectItems = gulp.src(injectItems)
.pipe(plugins.plumber())
.pipe(plugins.ignore.include(function (file) {
var fileBase = path.basename(file.path);
// Exclude filenames with "view-" not matching the current view
if (fileBase.indexOf('view-') > -1 && fileBase.indexOf('.js') > -1 && fileBase.indexOf(viewBaseName) < 0) {
return false;
}
// Pass through all the other files
return true;
}))
.pipe(plugins.deporder(baseName));
// On the current template
gulp.src('templates/' + baseName)
.pipe(plugins.plumber())
// Piping plugins.newer() blocks refreshes on partials and layout parts :(
//.pipe(plugins.newer(config.export_templates + '/' + baseName))
.pipe(plugins.if(config.assemble_templates, plugins.compileHandlebars({
templateName: baseName
}, {
batch: ['templates/layout', 'templates/partials'],
helpers: {
equal: function (v1, v2, options) {
return (v1 == v2) ? options.fn(this) : options.inverse(this);
}
}
})))
.pipe(plugins.inject(injectItems, {
ignorePath: [
_.without(cwdParts, cwdParts.splice(-1)[0]).join('/')
].concat(config.export_assets.split('/')),
addRootSlash: false,
addPrefix: config.template_asset_prefix || ''
}))
.pipe(plugins.if(config.w3c && ext === 'html', plugins.w3cjs({
doctype: 'HTML5',
charset: 'utf-8'
})))
.pipe(plugins.if(config.minifyHTML, plugins.htmlmin(htmlminOptions)))
.pipe(gulp.dest(config.export_templates))
.on('end', function () {
// Since above changes are made in a tapped stream
// We have to count to make sure everything is parsed
count = count + 1;
if (count == numTemplates) {
// Reload when serving
if (lrStarted) {
browserSync.reload(/*{stream:true}*/);
}
// Update the loadbar
updateBar();
// Report unvalidated files
if (unvalidatedFiles.length) {
console.log(chalk.yellow('✘ Couldn\'t validate: ' + unvalidatedFiles.join(', ')));
console.log(chalk.yellow.inverse('W3C validation only works for HTML files'));
}
// Report the end of this task
cb(null);
}
})
;
if (config.w3c && ext !== 'html') {
unvalidatedFiles.push(baseName);
}
}))
;
});
// MANIFEST -------------------------------------------------------------------
//
gulp.task('manifest', function (cb) {
// Quit this task if the revisions aren't turned on
if (!config.revisionCaching) {
updateBar();
cb(null);
return;
}
verbose(chalk.grey('Running task "manifest"'));
return gulp.src([
config.export_assets + '/' + assetsFolder + '/js/*',
config.export_assets + '/' + assetsFolder + '/css/*'
])
.pipe(plugins.manifest({
filename: 'app.manifest',
exclude: 'app.manifest'
}))
.pipe(gulp.dest(config.export_misc))
.on('end', updateBar)
;
});
// SERVER ---------------------------------------------------------------------
//
gulp.task('server', ['browsersync'], function (cb) {
verbose(chalk.grey('Running task "server"'));
console.log(chalk.grey('Watching files...'));
gulp.watch([assetsFolder + '/sass/**/*.{scss, sass, css}', '!' + assetsFolder + '/sass/*ie.{scss, sass, css}'], ['sass-main']).on('change', watchHandler);
gulp.watch([assetsFolder + '/js/**/view-*.js'], ['scripts-view', 'templates']).on('change', watchHandler);
gulp.watch([assetsFolder + '/js/**/*.js', '!**/view-*.js'], ['scripts-main', 'templates']).on('change', watchHandler);
gulp.watch([assetsFolder + '/images/**/*'], ['images']).on('change', watchHandler);
gulp.watch(['templates/**/*'], ['templates']).on('change', watchHandler);
cb(null);
});
gulp.task('browsersync', function (cb) {
verbose(chalk.grey('Running task "browsersync"'));
console.log(chalk.grey('Launching server...'));
// Grab the event emitter and add some listeners
var evt = browserSync.emitter;
evt.on('init', bsInitHandler);
evt.on('service:running', bsRunningHandler);
// Serve files and connect browsers
browserSync.init(null, {
server: _.isUndefined(config.proxy) ? {
baseDir: config.export_templates
} : false,
logConnections: false,
logLevel: 'silent', // 'debug'
browser: config.browser || 'default',
open: isOpen,
port: config.port || 3000,
proxy: config.proxy || false,
tunnel: isTunnel || null
}, function (err, data) {
// Use this callback to catch errors, which aren't transmitted
// through `init`
if (err !== null) {
console.log(
chalk.red('✘ Setting up a local server failed... Please try again. Aborting.\n') +
chalk.red(err)
);
process.exit(0);
}
cb(null);
});
});
// PAGESPEED INSIGHTS ---------------------------------------------------------
//
gulp.task('psi', function (cb) {
// Quit this task if no flag was set
if(!isPSI) {
cb(null);
return;
}
verbose(chalk.grey('Running task "psi"'));
console.log(chalk.grey('Running PageSpeed Insights (might take a while)...'));
// Define PSI options
var opts = {
url: tunnelUrl,
strategy: flags.strategy || "desktop",
threshold: 80
};
// Set the key if one was passed in
if (!!flags.key && _.isString(flags.key)) {
console.log(chalk.yellow.inverse('Using a key is not yet supported as it just crashes the process. For now, continue using `--psi` without a key.'));
// TODO: Fix key
//opts.key = flags.key;
}
// Run PSI
psi(opts, function (err, data) {
// If there was an error, log it and exit
if (err !== null) {
console.log(chalk.red('✘ Threshold of ' + opts.threshold + ' not met with score of ' + data.score));
} else {
console.log(chalk.green('✔ Threshold of ' + opts.threshold + ' exceeded with score of ' + data.score));
}
cb(null);
});
});
// HELPER FUNCTIONS -----------------------------------------------------------
//
// Download the boilerplate files
function downloadBoilerplateFiles () {
console.log(chalk.grey('Downloading boilerplate files...'));
// If a custom repo was passed in, use it
if (!!flags.base) {
// Check if there's a slash
if (flags.base.indexOf('/') < 0) {
console.log(chalk.red('✘ Please pass in a correct repository, eg. `username/repository` or `user/repo#branch. Aborting.\n'));
process.exit(0);
}
// Check if there's a reference
if (flags.base.indexOf('#') > -1) {
flags.base = flags.base.split('#');
gitConfig.ref = flags.base[1];
flags.base = flags.base[0];
} else {
gitConfig.ref = null;
}
// Extract username and repo
flags.base = flags.base.split('/');
gitConfig.user = flags.base[0];
gitConfig.repo = flags.base[1];
// Extra validation
if (gitConfig.user.length <= 0) {
console.log(chalk.red('✘ The passed in username is invald. Aborting.\n'));
process.exit(0);
}
if (gitConfig.repo.length <= 0) {
console.log(chalk.red('✘ The passed in repository is invald. Aborting.\n'));
process.exit(0);
}
}
// Download the boilerplate files to a temp folder
// This is to prevent a ENOEMPTY error
ghdownload(gitConfig, tmpFolder)
// Let the user know when something went wrong
.on('error', function (error) {
console.log(chalk.red('✘ An error occurred. Aborting.'), error);
process.exit(0);
})
// Download succeeded
.on('end', function () {
console.log(
chalk.green('✔ Download complete!\n') +
chalk.grey('Cleaning up...')
);
// Move to working directory, clean temp, finish init
ncp(tmpFolder, cwd, function (err) {
if (err) {
console.log(chalk.red('✘ Something went wrong. Please try again'), err);
process.exit(0);
}
sequence('clean-tmp', function () {
finishInit();
});
});
})
// TODO: Try to catch the error when a ZIP has "NOEND"
;
}
// Wrap up after running init and
// downloading the boilerplate files
function finishInit () {
// Ask the user if he wants to continue and
// have the files served and opened
prompt({
type: 'confirm',
message: 'Would you like to have these files served?',
name: 'build',
default: true
}, function (buildAnswer) {
if (buildAnswer.build) {
isServe = true;
prompt({
type: 'confirm',
message: 'Should they be opened in the browser?',
name: 'open',
default: true
}, function (openAnswer) {
if (openAnswer.open) isOpen = true;
prompt({
type: 'confirm',
message: 'Should they be opened in an editor?',
name: 'edit',
default: true
}, function (editAnswer) {
if (editAnswer.edit) isEdit = true;
gulp.start('build');
});
});
}
else process.exit(0);
});
}
// Update the loadbar if one is set
function updateBar () {
if (!isVerbose && bar !== null) {
bar.tick();
}
}
// Handle change events for Gulp watch instances
function watchHandler (e) {
console.log(chalk.grey('"' + e.path.split('/').pop() + '" was ' + e.type));
}
// Browser Sync `init` event handler
function bsInitHandler (data) {
// Store started state globally
lrStarted = true;
// Show some logs
console.log(chalk.cyan('🌐 Local access at'), chalk.magenta(data.options.urls.local));
console.log(chalk.cyan('🌐 Network access at'), chalk.magenta(data.options.urls.external));
if (isOpen) {
console.log(
chalk.cyan('☞ Opening in'),
chalk.magenta(config.browser)
);
}
// Open an editor if needed
if (isEdit) {
openEditor();
}
}
// Browser Sync `service:running event handler
function bsRunningHandler (data) {
if (data.tunnel) {
tunnelUrl = data.tunnel;
console.log(chalk.cyan('🌐 Public access at'), chalk.magenta(tunnelUrl));
if (isPSI) {
gulp.start('psi');
}
} else if (isPSI) {
console.log(chalk.red('✘ Running PSI cannot be started without a tunnel. Please restart Headstart with the `--tunnel` or `t` flag.'));
}
}
// Open files in editor
function openEditor () {