forked from loiane/es-na-palma-da-mao-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.babel.js
868 lines (750 loc) · 24.6 KB
/
gulpfile.babel.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
/*
eslint
"no-invalid-this": 1,
"angular/timeout-service": 0,
"angular/definedundefined": 0,
"angular/json-functions": 0,
"no-unused-vars": 1
*/
// ES6 gulpfile
// ref: https://markgoodyear.com/2015/06/using-es6-with-gulp/
import bluebird from 'bluebird';
import innerGulp from 'gulp';
import gulpHelp from 'gulp-help';
import yargs from 'yargs';
import runSequence from 'run-sequence';
import gulpHelpers from './gulp/helpers';
import fs from 'fs';
import path from 'path';
import git from 'gulp-git';
import tap from 'gulp-tap';
import gutil from 'gulp-util';
import es from 'event-stream';
import concat from 'gulp-concat';
import order from 'gulp-order';
import gulpif from 'gulp-if';
import bump from 'gulp-bump';
import inquirer from 'inquirer';
import github from 'octonode';
import gulpExec from 'gulp-exec';
import config from './config/gulp.config';
import del from 'del';
import spawn from 'win-spawn';
import semver from 'semver';
import Bundler from '@prodest/angular-lazy-bundler';
import ts from 'gulp-typescript';
import sourcemaps from 'gulp-sourcemaps';
import karma from 'karma';
import cheerio from 'gulp-cheerio';
import shell from 'gulp-shell';
//import 'gulp-cordova-build-android';
const gulp = gulpHelp( innerGulp ); // wrap in gulp help
const taskMaker = gulpHelpers.taskMaker( gulp );
const environment = gulpHelpers.environment();
const Promise = bluebird;
/**
* Realiza o parse dos argumentos da linha de comando
*/
let argv = yargs.alias( 't', 'transpile' )
.alias( 'w', 'watch' )
.alias( 's', 'serve' )
.alias( 'e', 'emulate' )
.alias( 'r', 'run' )
.alias( 'h', 'htmlmin' )
.alias( 'j', 'jsmin' )
.alias( 'b', 'bundle' )
.alias( 'p', 'password' )
.default( 'jsmin', false )
.default( 'bundle', false )
.default( 'htmlmin', false )
.default( 'watch', false )
.default( 'emulate', false )
.default( 'run', false )
.default( 'serve', false )
.default( 'transpile', false )
.default( 'password', '' ).argv;
////////////////////////////////////////// HELPERS /////////////////////////////////////////////////
/**
* github api client
*/
let client;
/**
* Lê um arquivo JSON
*
* @param {String} file - o path para o arquivo
*
* @returns {Object} - uma objeto JSON
*/
const readJsonFile = ( file ) => {
return JSON.parse( fs.readFileSync( file ) );
};
/**
* Adiciona novos 'src' ao pipeline do gulp
*
* @param {string} src - src para ser adicionado ao pipeline do gulp.
* @returns {Stream} - uma gulp stream
*
* @example
* gulp.src('')
* .pipe(addSrc('CHANGELOG.md'))
* .gulp.dest();
*/
const addSrc = ( src ) => {
let pass = es.through();
return es.duplex( pass, es.merge( gulp.src.apply( gulp.src, [ src ] ), pass ) );
};
/**
* Obtém o email(cadastrado no git) do usuário corrente
*
* @returns {Promise} - uma promise
*/
const getEmailAsync = Promise.promisify( git.exec.bind( git, {
args: 'config --get user.email',
quiet: false
} ) );
/**
* Obtém o nome da branch atual
*
* @returns {Promise} - uma promise
*/
const getCurrentBranchAsync = Promise.promisify( git.exec.bind( git, {
args: 'rev-parse --abbrev-ref HEAD',
quiet: false
} ) );
/**
* Tenta obter o username de um usuário à partir de seu email no git.
*
* @param {String} email - o email do usuário no git
*
* @returns {Promise} - uma promise
*/
const getUsernameAsync = ( email ) => {
return new Promise( ( resolve, reject ) => {
const query = {
q: `${email} in:email`
};
github.client()
.get( '/search/users', query, ( err, res, body ) => {
if ( err ) {
reject( gutil.colors.red( `Error: ${err}` ) );
} else {
const user = body.items[ 0 ];
resolve( user ? user.login : null );
}
} );
} );
};
/**
* Executa o prompt que pede ao usuário suas credenciais no github: username e password
*
* obs: Só exibe o prompt de username se um username não tiver sido fornecido.
*
* @param {String} [username] - O username do usuário
*
* @returns {Promise} - uma promise
*/
const prompCredentialsAsync = ( username ) => {
return new Promise( ( resolve ) => {
const questions = [
{
type: 'input',
message: 'Digite seu username do github',
name: 'username',
default: username,
validate: ( input ) => {
return input !== ''; // obrigatório
},
when: () => {
return !username; // Só exibe o prompt de username se um username não tiver sido fornecido.
}
}, {
type: 'password',
message: 'Digite sua senha do github',
name: 'password',
validate: ( input ) => {
return input !== ''; // obrigatório
}
}
];
inquirer.prompt( questions, ( answers ) => {
resolve( {
username: answers.username || username,
password: answers.password
} );
} );
} );
};
/**
* Autentica o usuário na api do github.
*
* @param {Object} tokenOrCredentials - Um token de autenticação ou as credenciais(login e senha)
* informados pelo usuário
*
* @returns {Promise} - uma promise
*/
const authenticateAsync = ( tokenOrCredentials ) => {
return new Promise( ( resolve, reject ) => {
// cria client node para api do github, usando credenciais do usuário
client = github.client( tokenOrCredentials );
// tenta fazer um requisição que necessita de autenticação para poder verificar
// o sucesso da mesma
client.get( '/user', {}, ( err, status, body, headers ) => { //eslint-disable-line no-unused-vars
if ( err ) {
reject( `${gutil.colors.red( 'autenticação no github falhou! ' )} resposta do server: ${gutil.colors.yellow( err )}` );
}
resolve( gutil.colors.green( 'Autenticou no github com sucesso!' ) );
} );
} );
};
/**
* Executa um comando do ionic. Pressupõe o ionic instalado localmente.
*
* @param {String} command - O comando do Ionic CLI sendo executado
* @param {String[]} args - Array de strings contendo os argumentos para command
* @param {Function} cb - Callback a ser executado quando o command finalizar
*
* @returns {void}
*/
const ionic = ( command, args, cb ) => {
const script = path.resolve( './node_modules/ionic/bin/', 'ionic' );
const flags = process.argv.splice( 3 );
const ionicArgs = [ command ].concat( args || [] ).concat( flags );
const child = spawn( script, ionicArgs, { stdio: 'inherit' } );
child.on( 'close', ( code ) => {
cb( !!code );
} );
};
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// TASKS ////////////////////////////////////////////////////
gulp.task( 'ionic:serve', ( cb ) => {
ionic( 'serve', [ '--flag' ], cb );
} );
gulp.task( 'ionic:emulate', ( cb ) => {
if ( argv.emulate === true ) {
argv.emulate = 'android'; // usa android por default
}
ionic( `emulate ${argv.emulate}`, [ '--livereload', '--consolelogs' ], cb );
} );
gulp.task( 'ionic:run', ( cb ) => {
if ( argv.run === true ) {
argv.run = 'android'; // usa android por default
}
ionic( `run ${argv.run}`, [], cb );
} );
taskMaker.defineTask( 'css', {
taskName: 'css',
src: config.paths.css,
dest: config.paths.output.app,
debug: config.debugOptions
} );
taskMaker.defineTask( 'clean', {
taskName: 'clean',
src: config.paths.output.temp,
debug: config.debugOptions
} );
taskMaker.defineTask( 'babel', {
taskName: 'transpile-app-js',
src: config.paths.js.app,
dest: config.paths.output.app,
ngAnnotate: true,
compilerOptions: config.babelOptions,
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'app-js',
src: config.paths.js.app,
dest: config.paths.output.app,
changed: { extension: '.js' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'app-ts',
src: config.paths.ts.app,
dest: config.paths.output.app,
changed: { extension: '.ts' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'html',
src: config.paths.html,
dest: config.paths.output.app,
changed: { extension: '.html' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'packageJson',
src: config.paths.packageJson,
dest: config.paths.output.root,
changed: { extension: '.json' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'systemConfig',
src: config.paths.systemConfig,
dest: config.paths.output.root,
changed: { extension: '.js' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'system.yuml',
src: config.paths.systemYuml,
dest: config.paths.output.root,
changed: { extension: '.js' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'assets',
src: config.paths.assets,
dest: config.paths.output.app,
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'json',
src: config.paths.json,
dest: config.paths.output.app,
changed: { extension: '.json' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'copy', {
taskName: 'index.html',
src: config.paths.index.src,
dest: config.paths.output.root,
rename: 'index.html',
changed: { extension: '.html' },
debug: config.debugOptions
} );
taskMaker.defineTask( 'htmlMinify', {
taskName: 'htmlmin',
src: config.paths.html,
dest: config.paths.output.app,
debug: config.debugOptions,
minimize: config.htmlMinOptions
} );
taskMaker.defineTask( 'htmlHint', {
taskName: 'html-hint',
src: config.paths.html,
debug: config.debugOptions
} );
taskMaker.defineTask( 'minify', {
taskName: 'jsmin',
src: config.paths.js.output,
dest: config.paths.output.app,
debug: config.debugOptions
} );
taskMaker.defineTask( 'tslint', {
taskName: 'tslint-src',
src: config.paths.ts.src,
debug: config.debugOptions
} );
taskMaker.defineTask( 'eslint', {
taskName: 'eslint-src',
src: config.paths.js.src,
dest: './src',
debug: config.debugOptions
} );
taskMaker.defineTask( 'eslint', {
taskName: 'eslint',
src: config.paths.js.all,
dest: './',
debug: config.debugOptions
} );
taskMaker.defineTask( 'eslint', {
taskName: 'eslint-gulp',
src: config.paths.gulp,
base: './',
dest: './',
debug: config.debugOptions
} );
taskMaker.defineTask( 'watch', {
taskName: 'watch',
src: config.paths.watch,
tasks: [ 'compile' ]
} );
taskMaker.defineTask( 'browserSync', {
taskName: 'serve',
browserSyncConfig: config.browserSyncConfig
} );
// no-op = empty function
gulp.task( 'noop', ( cb ) => {
cb();
} );
gulp.task( 'ensures-develop', false, ( cb ) => {
/**
* Loga o erro encontrado.
*
* @param {String} err - o erro disparado
*
* @returns {void}
*/
const onError = err => {
gutil.log( gutil.colors.red( err ) );
};
/**
* Dispara um erro se a branch atual não se chamar config.developBranch
*
* @param {String} branch - o nome da branch atual
*
* @returns {void}
*/
const throwErrorIfNotInMaster = branch => {
if ( branch.trim() !== config.developBranch ) {
throw new Error( `Branch atual: "${branch.trim()}". Acão permtida somente na branch de desenvolvimento: "${config.developBranch}".` );
}
cb();
};
getCurrentBranchAsync().then( throwErrorIfNotInMaster )
.catch( onError );
} );
gulp.task( 'ensures-master', false, ( cb ) => {
/**
* Loga o erro encontrado.
*
* @param {String} err - o erro disparado
*
* @returns {void}
*/
const onError = err => {
gutil.log( gutil.colors.red( err ) );
};
/**
* Dispara um erro se a branch atual não se chamar config.masterBranch
*
* @param {String} branch - o nome da branch atual
*
* @returns {void}
*/
const throwErrorIfNotInMaster = branch => {
if ( branch.trim() !== config.masterBranch ) {
throw new Error( `Branch atual: "${branch.trim()}". Só é possível criar um release da branch "${config.masterBranch}".` );
}
cb();
};
getCurrentBranchAsync().then( throwErrorIfNotInMaster )
.catch( onError );
} );
gulp.task( 'ensures-release-branch', false, ( cb ) => {
/**
* Loga o erro encontrado.
*
* @param {String} err - o erro disparado
*
* @returns {void}
*/
const onError = err => {
gutil.log( gutil.colors.red( err ) );
};
/**
* Dispara um erro se a branch atual não se chamar config.masterBranch
*
* @param {String} branch - o nome da branch atual
*
* @returns {void}
*/
const throwErrorIfNotInReleaseBranch = branch => {
if ( !branch.trim().startsWith( 'release-' ) ) {
throw new Error( `Branch atual: "${branch.trim()}". Só é possível preparar um release estando numa release branch (release-*).` );
}
cb();
};
getCurrentBranchAsync().then( throwErrorIfNotInReleaseBranch )
.catch( onError );
} );
gulp.task( 'bump', false, ( cb ) => {
runSequence( 'bump-npm', 'bump-cordova', cb );
} );
gulp.task( 'bump-cordova', false, ( cb ) => {
const pkg = readJsonFile( config.paths.packageJson );
gulp.src( config.paths.cordovaConfig )
.pipe( cheerio( {
parserOptions: {
xmlMode: true
},
run: ( $ ) => {
$( 'widget' ).attr( 'version', pkg.version );
}
} ) )
.pipe( gulp.dest( './' ) )
.on( 'end', cb );
} );
gulp.task( 'bump-npm', false, ( cb ) => {
let bumpType = 'patch';
if ( argv.patch ) {
bumpType = 'patch';
}
if ( argv.minor ) {
bumpType = 'minor';
}
if ( argv.major ) {
bumpType = 'major';
}
if ( argv.prerelease ) {
bumpType = 'prerelease';
}
bumpType = process.env.BUMP || bumpType;
let version = argv.version;
gulp.src( config.paths.packageJson )
.pipe( gulpif( version !== undefined, bump( {
version: version
} ), bump( {
type: bumpType
} ) ) )
.pipe( gulp.dest( './' ) )
.on( 'end', cb );
} );
gulp.task( 'commit', false, () => {
const pkg = readJsonFile( config.paths.packageJson );
const message = `feat(bump): Atualiza versão para ${pkg.version}`;
return gulp.src( [ config.paths.packageJson, config.paths.cordovaConfig ] )
.pipe( git.commit( message ) );
} );
gulp.task( 'tag', false, [ 'ensures-master' ], ( cb ) => {
const pkg = readJsonFile( config.paths.packageJson );
const v = `v${pkg.version}`;
const message = pkg.version;
git.tag( v, message, ( err ) => {
if ( err ) {
throw new Error( err );
}
cb();
} );
} );
gulp.task( 'push', false, [ 'ensures-master' ], ( cb ) => {
git.push( 'origin', config.masterBranch, ( err ) => {
if ( err ) {
throw new Error( err );
}
cb();
} );
} );
gulp.task( 'push-tags', false, [ 'ensures-master' ], ( cb ) => {
git.push( 'origin', config.masterBranch, { args: '--tags' }, ( err ) => {
if ( err ) {
throw new Error( err );
}
cb();
} );
} );
gulp.task( 'create-release-branch', false, [ 'ensures-develop', 'bump' ], ( cb ) => {
const pkg = readJsonFile( config.paths.packageJson );
const branchName = `release-v${pkg.version}`;
git.checkout( branchName, { args: '-b' }, ( err ) => {
if ( err ) {
throw new Error( err );
}
runSequence( 'commit', cb );
} );
} );
gulp.task( 'changelog', false, ( cb ) => {
const pkg = readJsonFile( config.paths.packageJson );
const options = argv;
const version = options.version || pkg.version;
const from = options.from || '';
gulp.src( '' )
.pipe( gulpExec( `node ./gulp/helpers/changelog-script.js ${version} ${from}`, {
pipeStdout: true
} ) )
.pipe( concat( 'updates.md' ) )
.pipe( addSrc( 'CHANGELOG.md' ) )
.pipe( order( [ 'updates.md', 'CHANGELOG.md' ] ) )
.pipe( concat( 'CHANGELOG.md' ) )
.pipe( gulp.dest( './' ) )
.on( 'end', cb );
} );
gulp.task( 'github:authenticate', false, [ 'ensures-master' ], () => {
const authToken = process.env.GITHUB_AUTH_TOKEN;
if ( authToken ) {
gutil.log( gutil.colors.blue( 'Autenticando no Github via token contido em "process.env.GITHUB_AUTH_TOKEN"' ) );
return authenticateAsync( authToken ).tap( gutil.log );
} else {
return getEmailAsync().then( getUsernameAsync )
.then( prompCredentialsAsync )
.then( authenticateAsync )
.tap( gutil.log );
}
} );
gulp.task( 'github:create-release', false, [ 'ensures-master', 'github:authenticate' ], () => {
const pkg = readJsonFile( config.paths.packageJson );
const v = `v${pkg.version}`;
const isPrerelease = !!semver.parse( pkg.version ).prerelease.length;
return gulp.src( config.paths.changelog )
.pipe( tap( ( file ) => {
let releaseBody = file.contents.toString();
const release = {
'tag_name': v,
'name': v,
'target_commitish': config.masterBranch,
'body': releaseBody.slice( releaseBody.indexOf( '###' ) ),
'prerelease': isPrerelease
};
client.post( '/repos/prodest/es-na-palma-da-mao-mobile/releases', release, ( err, res, body ) => { // eslint-disable-line no-unused-vars
if ( err ) {
gutil.log( gutil.colors.red( `Error: ${err}` ) );
} else {
del( config.paths.changelog );
}
} );
} ) );
} );
gulp.task( 'transpile-app-ts', function() {
let tsProject = ts.createProject( 'tsconfig.json', {
typescript: require( 'typescript' )
} );
return gulp.src( [ 'node_modules/@types/**/*.d.ts', config.paths.ts.app ] )
.pipe( sourcemaps.init() )
.pipe( tsProject( ts.reporter.defaultReporter() ) )
.pipe( sourcemaps.write() )
.pipe( gulp.dest( config.paths.output.app ) );
} );
gulp.task( 'delay', false, ( cb ) => {
setTimeout( cb, 3000 );
} );
gulp.task( 'create-release', 'Cria e publica uma nova release no Github e faz upload do changelog.', ( cb ) => {
return runSequence( 'ensures-master', 'test', 'changelog', 'tag', 'push', 'push-tags', 'delay', 'github:create-release', cb );
} );
gulp.task( 'tree-shaking', false, shell.task( [
'find ./www/jspm_packages -type f -not -regex ".*\\.css$" -not -regex ".*\\.woff$" -not -regex ".*\\.woff2$" -not -regex ".*\\/system.js$" -not -regex ".*\\/system-polyfills.js$" -not -regex ".*\\/system-csp-production.js$" -delete -or -type f -regex ".*/angular.*/.*" -delete'
] ) );
gulp.task( 'create-apk', false, shell.task( [
'cordova build android --release -- --keystore=espm.keystore --storePassword=' + argv.password + ' --alias=espm --password=' + argv.password
] ) );
gulp.task( 'compile', 'Compila a aplicação e copia o resultado para a pasta de distribuição.', ( cb ) => {
// Se flag argv.transpile seja informado, realiza o transpile do js e copia o resultado para
// a pasta de onde a app será executada. Caso argv.transpile NÃO seja informado, copia o código
// js como está a "transpilation" será delegada automaticamente para o systemJS, o que é bom
// em tempo de desenvolvimento mas que aumenta significativamente número e o tamanho das
// requisições.
const transpile = argv.transpile || environment.isProduction();
const jsmin = argv.jsmin || environment.isProduction();
const htmlmin = argv.htmlmin || environment.isProduction();
const bundle = argv.bundle || environment.isProduction();
// tasks que transformam/copiam arquivos para a pasta de distribuição
let compileTasks = [
'eslint-src',
'tslint-src',
'css',
'json',
'assets',
'system.yuml',
'packageJson',
'systemConfig',
'index.html',
transpile ? 'transpile-app-ts' : 'app-ts',
transpile ? 'transpile-app-js' : 'app-js',
htmlmin ? 'htmlmin' : 'html'
];
// tasks executadas nos arquivos copiados na pasta de distribuição.
if ( jsmin ) {
compileTasks.push( [ 'jsmin' ] );
}
if ( bundle ) {
compileTasks.push( 'bundle' );
compileTasks.push( 'tree-shaking' );
}
compileTasks.push( cb ); // adiciona callback no fim de copy tasks
runSequence.apply( null, compileTasks );
} );
gulp.task( 'recompile', 'Limpa diretório destino e compila aplicação.', ( cb ) => {
runSequence( 'clean', [ 'compile' ], cb );
} );
gulp.task( 'run', 'Executa a aplicação', ( cb ) => {
if ( environment.isProduction() ) {
runSequence( 'recompile', 'serve', cb );
} else if ( environment.isDevelopment() ) {
let serveTasks = [ 'noop' ];
if ( argv.emulate ) {
serveTasks.push( 'ionic:emulate' );
}
if ( argv.run ) {
serveTasks.push( 'ionic:run' );
}
if ( argv.serve ) {
serveTasks.push( 'serve' );
}
runSequence( 'recompile', serveTasks, argv.watch ? 'watch' : 'noop', cb );
} else {
gutil.log( gutil.colors.yellow( `Nenhuma task configurada para o ENV: ${environment.name}` ) );
}
} );
gulp.task( 'default', 'Executa task \'run\'', [ 'run' ] );
gulp.task( 'analyze', 'Analiza o código', ( cb ) => {
runSequence( 'eslint-src', 'tslint-src', 'transpile-app-ts', cb );
} );
////////////////////////////////////////////////////////////////////////////////////////////////////
gulp.task( 'bundle', ( done ) => {
const bundler = new Bundler( {
baseUrl: 'www',
source: 'www',
dest: 'www/bundles',
sourceMaps: false,
cssOptimize: true,
systemJsConfig: 'www/system.config.js'
} );
bundler.bundle( {
components: [
'shared/authentication',
'shared/toast',
'shared/loader',
'shared/routes',
'shared/http',
'shared/dialog',
'shared/fabric',
'shared/permissions',
'shared/push',
'shared/settings',
'shared/directives',
'shared',
'layout/menu',
'layout/messages/message',
'layout/messages/highlight',
'layout/messages/remark',
'layout/messages/error-message',
'layout/spinner',
'layout',
'home',
'login',
'dashboard',
'news/shared',
'news/highlights',
'news',
'calendar/shared',
'calendar',
'detran/shared/models',
'detran/shared',
'detran',
'app'
],
packages: [
'ionic', // carrega angular e ui-router junto
'ionic-native',
'angular-i18n/pt-br',
'angular-material',
'ionic-native-transitions',
'ngstorage',
'angular-ui-router',
'ui-router-extras',
'oclazyload',
'moment',
'moment/locale/pt-br.js',
'roboto',
'font-awesome',
'calendar',
'text',
'css',
'image',
'json'
]
}, 'principal' )
.then( () => bundler.bundleRemainingComponents() )
.then( () => bundler.saveConfig() )
.then( () => done() )
.catch( ( err ) => done( err ) );
} );
/**
* Run test once and exit
*/
gulp.task( 'test', ( cb ) => {
new karma.Server( {
configFile: `${__dirname}/config/karma.conf.js`,
singleRun: true
}, cb ).start();
} );