forked from highcharts/highcharts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgulpfile.old.js
1756 lines (1598 loc) · 55.4 KB
/
gulpfile.old.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
/* ************************************************************************** *
@@@@ @@@ @ @ @@@ @@@@@ @@@@@ @@@@ @ @@@@@ @
@ @ @ @ @@ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ @ @ @ @@@@ @ @ @ @ @
@ @ @ @ @ @@ @ @ @ @ @ @ @ @
@@@@ @@@ @ @ @@@ @ @@@@@ @@@@ @ @ @
DO NOT EDIT THIS FILE! IT IS FOR EMERGENCY CASES AND REFERENCE ONLY.
* ************************************************************************** */
/* eslint-env node, es6 */
/* eslint no-console:0, no-path-concat:0, valid-jsdoc:0, max-len: 0 */
/* eslint-disable func-style */
'use strict';
const colors = require('colors');
const exec = require('child_process').exec;
const glob = require('glob');
const gulp = require('gulp');
const argv = require('yargs').argv;
const fs = require('fs');
const yaml = require('js-yaml');
const {
join,
relative,
sep
} = require('path');
const {
getFilesInFolder
} = require('highcharts-assembler/src/build.js');
const {
getFile,
removeDirectory,
writeFile,
writeFilePromise
} = require('highcharts-assembler/src/utilities.js');
const {
scripts,
getBuildScripts
} = require('./tools/build.js');
const {
getCompareFileSizeTable,
getFileSizes
} = require('./tools/compareFilesize.js');
const compile = require('./tools/compile.js').compile;
const {
copyFile,
promisify
} = require('./tools/filesystem.js');
const {
asyncForeach,
uploadFiles
} = require('./tools/upload.js');
const ProgressBar = require('./tools/progress-bar.js');
/**
* Creates a set of ES6-modules which is distributable.
* @return {undefined}
*/
const buildESModules = () => {
const {
buildModules
} = require('highcharts-assembler/src/build.js');
buildModules({
base: './js/',
output: './code/',
type: 'classic'
});
};
const sass = require('node-sass');
const sassRender = promisify(sass.render);
/**
* Executes a single terminal command and returns when finished.
* Outputs stdout to the console.
* @param {string} command Command to execute in terminal
* @return {string} Returns all output to the terminal in the form of a string.
*/
const commandLine = command => new Promise((resolve, reject) => {
const cli = exec(command, (error, stdout) => {
if (error) {
console.log(error);
reject(error);
} else {
console.log('Command finished: ' + command);
resolve(stdout);
}
});
cli.stdout.on('data', data => console.log(data.toString()));
});
const compileSingleStyle = fileName => {
const input = './css/' + fileName;
const output = './code/css/' + fileName.replace('.scss', '.css');
return Promise
.resolve()
.then(() => sassRender({
file: input,
outputStyle: 'expanded'
}))
.then(result => writeFilePromise(output, result.css));
};
/**
* Left pad a string
* @param {string} str The string we want to pad.
* @param {string} char The character we want it to be padded with.
* @param {number} length The length of the resulting string.
* @return {string} The string with padding on left.
*/
const leftPad = (str, char, length) => char.repeat(length - str.length) + str;
/**
* Returns time of date as a string in the format of HH:MM:SS
* @param {Date} d The date object we want to get the time from
* @return {string} The string represantation of the Date object.
*/
const toTimeString = d => {
const pad = s => leftPad(s, '0', 2);
return pad('' + d.getHours()) + ':' + pad('' + d.getMinutes()) + ':' + pad('' + d.getSeconds());
};
/**
* Creates CSS files
*
* @return {Promise}
* Promise to keep
*/
function styles() {
const promisesCopyGfx = getFilesInFolder('./gfx', true)
.map(path => copyFile(join('./gfx', path), join('./code/gfx', path)));
const promisesCompileStyles = getFilesInFolder('./css', true)
.map(file => compileSingleStyle(file));
const promises = [].concat(promisesCopyGfx, promisesCompileStyles);
return Promise.all(promises).then(() => {
console.log('Built CSS files from SASS.'.cyan);
});
}
gulp.task('styles', styles);
/**
* @private
* Tests whether the code is in sync with source.
*
* @return {boolean}
* True, if code is out of sync.
*/
function shouldBuild() {
const getModifiedTime = fsPattern => {
let modifyTime = 0;
glob.sync(fsPattern)
.forEach(file => {
modifyTime = Math.max(modifyTime, fs.statSync(file).mtimeMs);
});
return modifyTime;
};
const buildPath = join(__dirname, 'code', '**', '*.js');
const sourcePath = join(__dirname, 'js', '**', '*.js');
const latestBuildTime = getModifiedTime(buildPath);
const latestSourceTime = getModifiedTime(sourcePath);
return (latestBuildTime <= latestSourceTime);
}
/**
* Updates node packages.
*
* @return {Promise}
* Promise to keep.
*/
function update() {
const configurationPath = join('node_modules', '_update.json');
const now = (new Date()).getTime();
let configuration = {
checkFrequency: 'weekly',
lastCheck: 0
};
if (fs.existsSync(configurationPath)) {
configuration = JSON.parse(fs.readFileSync(configurationPath));
}
let minimumTime = now;
switch (configuration.checkFrequency) {
default:
case 'weekly':
minimumTime -= Date.UTC(1970, 0, 8);
break;
case 'monthly':
minimumTime -= Date.UTC(1970, 0, 29);
break;
case 'daily':
minimumTime -= Date.UTC(1970, 0, 2);
break;
case 'hourly':
minimumTime -= Date.UTC(1970, 0, 1, 1);
break;
}
if (configuration.lastCheck <= minimumTime) {
configuration.lastCheck = now;
fs.writeFileSync(configurationPath, JSON.stringify(configuration));
console.log(
'[' + colors.gray(toTimeString(new Date())) + ']',
'Updating packages...'
);
return commandLine('npm i');
}
return Promise.resolve();
}
gulp.task('update', update);
/**
* Update the vendor files for distribution
*/
function updateVendor() {
console.log((
'Note: This task only copies the files into the vendor folder.\n' +
'To upgrade, run npm update jspdf-yworks && npm update svg2pdf.js`'
).yellow);
const promises = [
[
'./node_modules/jspdf-yworks/dist/jspdf.debug.js',
'./vendor/jspdf.src.js'
],
[
'./node_modules/jspdf-yworks/dist/jspdf.min.js',
'./vendor/jspdf.js'
],
[
'./node_modules/svg2pdf.js/dist/svg2pdf.js',
'./vendor/svg2pdf.src.js'
],
[
'./node_modules/svg2pdf.js/dist/svg2pdf.min.js',
'./vendor/svg2pdf.js'
]
].map(([source, target]) => copyFile(source, target));
return Promise.all(promises);
}
gulp.task('update-vendor', updateVendor);
/**
* Gulp task to run the building process of distribution files. By default it
* builds all the distribution files. Usage: "gulp build".
*
* - `--file` Optional command line argument. Use to build a one or sevral
* files. Usage: "gulp build --file highcharts.js,modules/data.src.js"
*
* - `--force` Optional CLI argument to force a rebuild of scripts.
*
* @todo add --help command to inform about usage.
*
* @return {Promise}
*/
function scriptsWatch() {
const options = {
debug: argv.d || false,
files: (
(argv.file) ?
argv.file.split(',') :
null
),
type: (argv.type) ? argv.type : null,
watch: argv.watch || false
};
const {
fnFirstBuild,
mapOfWatchFn
} = getBuildScripts(options);
if (shouldBuild() ||
(argv.force && !argv.watch) ||
process.env.HIGHCHARTS_DEVELOPMENT_GULP_SCRIPTS
) {
process.env.HIGHCHARTS_DEVELOPMENT_GULP_SCRIPTS = true;
fnFirstBuild();
delete process.env.HIGHCHARTS_DEVELOPMENT_GULP_SCRIPTS;
console.log('Built JS files from modules.'.cyan);
} else {
console.log('✓'.green, 'Code up to date.'.gray);
}
if (options.watch) {
Object.keys(mapOfWatchFn).forEach(key => {
const fn = mapOfWatchFn[key];
gulp.watch(key).on('change', path => fn({ path, type: 'change' }));
});
}
return Promise.resolve();
}
gulp.task('scripts', gulp.series('update', scriptsWatch));
/**
* Gulp task to execute ESLint. Pattern defaults to './js/**".'
* @parameter {string} -p Command line parameter to set pattern. To lint sample
* files, see the lintSamples function.
* @return undefined Returns nothing
*/
const lint = () => new Promise((resolve, reject) => {
const CLIEngine = require('eslint').CLIEngine;
const cli = new CLIEngine({
fix: argv.fix
});
const formatter = cli.getFormatter();
const pattern = (typeof argv.p === 'string') ? [argv.p] : ['./js/**/*.js'];
const report = cli.executeOnFiles(pattern);
if (argv.fix) {
CLIEngine.outputFixes(report);
console.log(formatter(report.results));
reject(new Error('ESLint error'));
} else {
console.log(formatter(report.results));
resolve();
}
});
gulp.task('lint', gulp.series('update', lint));
/**
* Gulp task to execute ESLint on samples.
* @parameter {string} -p Command line parameter to set pattern. Example usage
* gulp lint -p './samples/**'
* @return undefined Returns nothing
*/
const lintSamples = () => {
const CLIEngine = require('eslint').CLIEngine;
const cli = new CLIEngine({
ignorePattern: ['./samples/highcharts/common-js/*/demo.js']
});
const formatter = cli.getFormatter();
const report = cli.executeOnFiles([
'./samples/*/*/*/demo.js',
'./samples/*/*/*/test.js',
'./samples/*/*/*/unit-tests.js'
]);
console.log(formatter(report.results));
};
gulp.task('lint-samples', gulp.series('update', lintSamples));
/**
* Run the test suite.
*/
gulp.task('test', gulp.series('styles', 'scripts', done => {
const lastRunFile = __dirname + '/test/last-run.json';
const getModifiedTime = pattern => {
let mtimeMs = 0;
glob.sync(pattern).forEach(file => {
mtimeMs = Math.max(
mtimeMs,
fs.statSync(file).mtimeMs
);
});
return mtimeMs;
};
// Get the checksum of all code excluding comments. An idea for smarter
// checks. If the check sum hasn't changed since last test run, there's no
// need to run tests again.
/*
const getCodeHash = (pattern) => {
const crypto = require('crypto');
let hashes = [];
glob.sync(pattern).forEach(file => {
let s = fs.readFileSync(file, 'utf8');
if (typeof s === 'string') {
s = s.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, '');
s = crypto.createHash('md5').update(s).digest('hex');
hashes.push(s);
}
});
let hash = crypto
.createHash('md5')
.update(hashes.toString())
.digest('hex');
return hash;
};
*/
const shouldRun = () => {
// console.log(getCodeHash(__dirname + '/js/**/*.js'));
const lastBuildMTime = getModifiedTime(__dirname + '/code/**/*.js');
const sourceMTime = getModifiedTime(__dirname + '/js/**/*.js');
const unitTestsMTime = getModifiedTime(__dirname + '/samples/unit-tests/**/*.*');
let lastSuccessfulRun = 0;
if (fs.existsSync(lastRunFile)) {
lastSuccessfulRun = require(lastRunFile).lastSuccessfulRun;
}
/*
console.log(
'lastBuildMTime', new Date(lastBuildMTime),
'sourceMTime', new Date(sourceMTime),
'unitTestsMTime', new Date(unitTestsMTime),
'lastSuccessfulRun', new Date(lastSuccessfulRun)
);
*/
// Arguments passed, always run. No arguments gives [ '_', '$0' ]
if (Object.keys(argv).length > 2) {
return true;
}
if (lastBuildMTime < sourceMTime) {
throw new Error(
'\n✖'.red + ' The files have not been built since ' +
'the last source code changes. Run ' + 'gulp'.italic +
' and try again.'
);
} else if (
sourceMTime < lastSuccessfulRun &&
unitTestsMTime < lastSuccessfulRun
) {
console.log('\n✓'.green + ' Source code and unit tests not modified since the last successful test run.\n'.gray);
return false;
}
return true;
};
const checkSamplesConsistency = () => {
const products = [
{ product: 'highcharts' },
{ product: 'stock' },
{ product: 'maps' },
{ product: 'gantt', ignore: ['logistics'] }
];
/**
* @param {object} product The product information
* @param {string} product.product Product folder name.
* @param {array} [product.ignore=[]] List of samples that is not listed
* in index.htm, that still should exist in the demo folder.
*/
products.forEach(({ product, ignore = [] }) => {
const index = fs.readFileSync(
`./samples/${product}/demo/index.htm`,
'utf8'
)
// Remove comments from the html in index
.replace(/<!--[\s\S]*-->/gm, '');
const regex = /href="examples\/([a-z\-0-9]+)\/index.htm"/g;
const toc = [];
let matches;
while ((matches = regex.exec(index)) !== null) {
toc.push(matches[1]);
}
const folders = [];
fs.readdirSync(`./samples/${product}/demo`).forEach(dir => {
if (dir.indexOf('.') !== 0 && dir !== 'index.htm') {
folders.push(dir);
}
});
const missingTOC = folders.filter(
sample => !toc.includes(sample) && !ignore.includes(sample)
);
const missingFolders = toc.filter(
sample => !folders.includes(sample)
);
if (missingTOC.length) {
console.log(`Found demos that were not added to ./samples/${product}/demo/index.htm`.red);
missingTOC.forEach(sample => {
console.log(` - ./samples/${product}/demo/${sample}`.red);
});
throw new Error('Missing sample in index.htm');
}
if (missingFolders.length) {
console.log(`Found demos in ./samples/${product}/demo/index.htm that were not present in demo folder`.red);
missingFolders.forEach(sample => {
console.log(` - ./samples/${product}/demo/${sample}`.red);
});
throw new Error('Missing demo');
}
});
};
// Check that each demo.details has the correct js_wrap setting required for
// it to display correctly on jsFiddle.
const checkJSWrap = () => {
glob(
'samples/+(highcharts|stock|maps|gantt)/**/demo.html',
(err, files) => {
if (err) {
throw err;
}
let errors = 0;
files.forEach(f => {
const detailsFile = f.replace(/\.html$/, '.details');
try {
const details = yaml.safeLoad(
fs.readFileSync(detailsFile, 'utf-8')
);
if (details.js_wrap !== 'b') {
console.log(`js_wrap not found: ${detailsFile}`.red);
errors++;
}
} catch (e) {
console.log(`File not found: ${detailsFile}`.red);
errors++;
}
});
if (errors) {
throw new Error('Missing js_wrap setting');
}
}
);
};
if (argv.help) {
console.log(`
HIGHCHARTS TEST RUNNER
Available arguments for 'gulp test':
--browsers
Comma separated list of browsers to test. Available browsers are
'ChromeHeadless, Chrome, Firefox, Safari, Edge, IE' depending on what is
installed on the local system. Defaults to ChromeHeadless.
In addition, virtual browsers from Browserstack are supported. They are
prefixed by the operating system. Available BrowserStack browsers are
'Mac.Chrome, Mac.Firefox, Mac.Safari, Win.Chrome, Win.Edge, Win.Firefox,
Win.IE'.
A shorthand option, '--browsers all', runs all BroserStack machines.
--debug
Print some debugging info.
--tests
Comma separated list of tests to run. Defaults to '*.*' that runs all tests
in the 'samples/' directory.
Example: 'gulp test --tests unit-tests/chart/*' runs all tests in the chart
directory.
`);
return;
}
checkSamplesConsistency();
checkJSWrap();
if (shouldRun()) {
console.log('Run ' + 'gulp test --help'.cyan + ' for available options');
const Server = require('karma').Server;
const PluginError = require('plugin-error');
new Server({
configFile: __dirname + '/test/karma-conf.js',
singleRun: true
}, err => {
if (err === 0) {
done();
// Register last successful run (only when running without
// arguments)
if (Object.keys(argv).length <= 2) {
fs.writeFileSync(
lastRunFile,
JSON.stringify({ lastSuccessfulRun: Date.now() })
);
}
} else {
done(new PluginError('karma', {
message: 'Tests failed'
}));
}
}).start();
} else {
done();
}
}));
/**
* Run the nightly. The task spawns a child process running node.
*/
gulp.task('nightly', function () {
const spawn = require('child_process').spawn;
spawn('node', ['nightly.js'].concat(process.argv.slice(3)), {
cwd: 'utils/samples',
stdio: 'inherit'
});
});
/**
* Automated generation for internal Class reference.
* Run with --watch argument to watch for changes in the JS files.
*/
const generateClassReferences = ({ templateDir, destination }) => {
const jsdoc = require('gulp-jsdoc3');
const sourceFiles = [
'README.md',
'./js/parts/Utilities.js',
'./js/parts/Axis.js',
'./js/parts/Chart.js',
'./js/parts/Color.js',
'./js/parts/DataGrouping.js',
'./js/parts/DataLabels.js',
'./js/parts/Dynamics.js',
'./js/parts/Globals.js',
'./js/parts/Interaction.js',
'./js/parts/Legend.js',
'./js/parts/Options.js',
'./js/parts/PieSeries.js',
'./js/parts/Point.js',
'./js/parts/Pointer.js',
'./js/parts/PlotLineOrBand.js',
'./js/parts/Series.js',
'./js/parts/StockChart.js',
'./js/parts/SVGRenderer.js',
'./js/parts/Tick.js',
'./js/parts/Time.js',
'./js/parts-gantt/GanttChart.js',
'./js/parts-gantt/TreeGrid.js',
'./js/parts-map/GeoJSON.js',
'./js/parts-map/Map.js',
'./js/parts-map/MapNavigation.js',
'./js/parts-map/MapSeries.js',
'./js/parts-more/AreaRangeSeries.js',
'./js/modules/drilldown.src.js',
'./js/modules/exporting.src.js',
'./js/modules/export-data.src.js',
'./js/modules/data.src.js',
'./js/modules/offline-exporting.src.js',
'./js/modules/pattern-fill.src.js',
'./js/modules/sankey.src.js',
'./js/modules/sonification/*.js',
'./js/annotations/annotations.src.js'
/*
'./js/annotations/eventEmitterMixin.js',
'./js/annotations/MockPoint.js',
'./js/annotations/ControlPoint.js',
'./js/annotations/controllable/controllableMixin.js',
'./js/annotations/controllable/ControllableCircle.js',
'./js/annotations/controllable/ControllableImage.js',
'./js/annotations/controllable/ControllableLabel.js',
'./js/annotations/controllable/ControllablePath.js',
'./js/annotations/controllable/ControllableRect.js',
'./js/annotations/types/CrookedLine.js',
'./js/annotations/types/ElliottWave.js',
'./js/annotations/types/Tunnel.js',
'./js/annotations/types/Fibonacci.js',
'./js/annotations/types/InfinityLine.js',
'./js/annotations/types/Measure.js',
'./js/annotations/types/Pitchfork.js',
'./js/annotations/types/VerticalLine.js'*/
];
const optionsJSDoc = {
navOptions: {
theme: 'highsoft'
},
opts: {
destination,
private: false,
template: templateDir + '/template'
},
plugins: [
templateDir + '/plugins/add-namespace',
templateDir + '/plugins/markdown',
templateDir + '/plugins/sampletag'
],
templates: {
logoFile: 'img/highcharts-logo.svg',
systemName: 'Highcharts',
theme: 'highsoft'
}
};
const message = {
success: colors.green('Created class-reference')
};
return new Promise((resolve, reject) => {
gulp.src(sourceFiles, { read: false })
.pipe(jsdoc(optionsJSDoc, function (err) {
if (err) {
reject(err);
} else {
console.log(message.success);
resolve(message.success);
}
}));
});
};
/**
* Compile the JS files in the /code folder
*/
const compileScripts = (args = {}) => {
const sourceFolder = './code/';
// Compile all files ending with .src.js.
// Do not compile files in ./es-modules or ./js/es-modules.
const isSourceFile = path => (
path.endsWith('.src.js') && !path.includes('es-modules')
);
const files = (
(args.files) ?
args.files :
getFilesInFolder(sourceFolder, true, '').filter(isSourceFile)
);
return compile(files, sourceFolder);
};
/**
* Compile the JS files in the /code folder
*/
const compileLib = () => {
const sourceFolder = './vendor/';
const files = ['canvg.src.js', 'rgbcolor.src.js'];
return compile(files, sourceFolder)
.then(console.log);
};
const cleanCode = () => {
const {
removeFile
} = require('highcharts-assembler/src/utilities.js');
const codeFolder = './code/';
const files = getFilesInFolder(codeFolder, true, '');
const keep = ['.gitignore', '.htaccess', 'css/readme.md', 'js/modules/readme.md', 'js/readme.md', 'modules/readme.md', 'readme.txt'];
const promises = files
.filter(file => keep.indexOf(file) === -1)
.map(file => removeFile(codeFolder + file));
return Promise.all(promises)
.then(() => console.log('Successfully removed code directory.'));
};
const cleanDist = () => removeDirectory('./build/dist')
.then(() => {
console.log('Successfully removed dist directory.');
})
.catch(() => {
console.log('Tried to remove ./build/dist but it was never there. Moving on...');
});
const cleanApi = () => removeDirectory('./build/api')
.then(() => {
console.log('Successfully removed api directory.');
});
gulp.task('clean-api', cleanApi);
const copyToDist = () => {
const sourceFolder = 'code/';
const distFolder = 'build/dist/';
const folders = [{
from: 'gfx',
to: 'gfx'
}, {
from: 'css',
to: 'code/css'
}];
// Additional files to include in distribution. // Map of pathTo to pathFrom
let additionals = {
'code/lib/canvg.js': 'vendor/canvg.js',
'code/lib/canvg.src.js': 'vendor/canvg.src.js',
'code/lib/jspdf.js': 'vendor/jspdf.js',
'code/lib/jspdf.src.js': 'vendor/jspdf.src.js',
'code/lib/rgbcolor.js': 'vendor/rgbcolor.js',
'code/lib/rgbcolor.src.js': 'vendor/rgbcolor.src.js',
'code/lib/svg2pdf.js': 'vendor/svg2pdf.js',
'code/lib/svg2pdf.src.js': 'vendor/svg2pdf.src.js'
};
// Files that should not be distributed with certain products
const filter = {
highcharts: [
'highcharts-gantt.js',
'highmaps.js',
'highstock.js',
'indicators/',
'modules/canvasrenderer.experimental.js',
'modules/map.js',
'modules/map-parser.js'
].map(str => new RegExp(str)),
highstock: [
'highcharts.js',
'highcharts-gantt.js',
'highmaps.js',
'modules/broken-axis.js',
'modules/canvasrenderer.experimental.js',
'modules/gantt.js',
'modules/map.js',
'modules/map-parser.js'
].map(str => new RegExp(str)),
highmaps: [
'highcharts-gantt.js',
'highstock.js',
'indicators/',
'modules/broken-axis.js',
'modules/canvasrenderer.experimental.js',
'modules/gantt.js',
'modules/map-parser.js',
'modules/series-label.js',
'modules/solid-gauge.js'
].map(str => new RegExp(str)),
gantt: [
'highcharts-3d.js',
'highcharts-more.js',
'highmaps.js',
'highstock.js',
'indicators/',
'modules/map.js',
'modules/stock.js',
'modules/canvasrenderer.experimental.js',
'modules/map-parser.js',
'modules/series-label.js',
'modules/solid-gauge.js'
].map(str => new RegExp(str))
};
// Copy source files to the distribution packages.
const codeFiles = getFilesInFolder(sourceFolder, true, '')
.filter(path => (
path.endsWith('.js') ||
path.endsWith('.js.map') ||
path.endsWith('.css')
))
.reduce((obj, path) => {
const source = sourceFolder + path;
const filename = path.replace('.src.js', '.js').replace('js/', '');
['highcharts', 'highstock', 'highmaps', 'gantt'].forEach(lib => {
const filters = filter[lib];
const include = !filters.find(regex => regex.test(filename));
if (include) {
const target = distFolder + lib + '/code/' + path;
obj[target] = source;
}
});
return obj;
}, {});
// Add additional files in folders to copy list
additionals = folders.reduce((map, folder) => {
const { from, to } = folder;
getFilesInFolder(from, true, '')
.forEach(filename => {
map[join(to, filename)] = join(from, filename);
});
return map;
}, additionals);
const additionalFiles = Object.keys(additionals).reduce((obj, file) => {
['highcharts', 'highstock', 'highmaps', 'gantt'].forEach(lib => {
const source = additionals[file];
const target = `${distFolder}${lib}/${file}`;
obj[target] = source;
});
return obj;
}, {});
const files = Object.assign({}, additionalFiles, codeFiles);
const promises = Object.keys(files).map(target => {
const source = files[target];
return copyFile(source, target);
});
return Promise.all(promises);
};
const getBuildProperties = () => {
const {
regexGetCapture
} = require('highcharts-assembler/src/dependencies.js');
const buildProperties = getFile('./build.properties');
// @todo Get rid of build.properties and perhaps use package.json in stead.
return {
date: regexGetCapture(/highcharts\.product\.date=(.+)/, buildProperties),
version: regexGetCapture(/highcharts\.product\.version=(.+)/, buildProperties)
};
};
const createProductJS = () => {
const path = './build/dist/products.js';
const buildProperties = getBuildProperties();
// @todo Add reasonable defaults
const date = buildProperties.date || '';
const version = buildProperties.version || '';
const content = `var products = {
"Highcharts": {
"date": "${date}",
"nr": "${version}"
},
"Highstock": {
"date": "${date}",
"nr": "${version}"
},
"Highmaps": {
"date": "${date}",
"nr": "${version}"
},
"Highcharts Gantt": {
"date": "${date}",
"nr": "${version}"
}
}`;
writeFile(path, content);
};
/**
* Returns a string which tells the time difference between to dates.
* Difference is formatted as xh xm xs xms. Where x is a number.
* @param {Date} d1 First date
* @param {Date} d2 Second date
* @return {string} The time difference between the two dates.
*/
const timeDifference = (d1, d2) => {
const time = [];
const seconds = 1000;
const minutes = 60 * seconds;
const hours = 60 * minutes;
let diff = d2 - d1;
let x = 0;
if (diff > hours) {
x = Math.floor(diff / hours);
diff -= x * hours;
time.push(x + 'h');
}
if (diff > minutes || (time.length > 0 && diff > 0)) {
x = Math.floor(diff / minutes);
diff -= x * minutes;
time.push(x + 'm');
}
if (diff > seconds || (time.length > 0 && diff > 0)) {
x = Math.floor(diff / seconds);
diff -= x * seconds;
time.push(x + 's');
}
if (diff > 0 || time.length === 0) {
time.push(diff + 'ms');
}
return time.join(' ');
};
/**
* Mirrors the same feedback which gulp gives when executing its tasks.
* Says when a task started, when it finished, and how long it took.
* @param {string} name Name of task which is being executed.
* @param {string} task A function to execute
* @return {*} Returns whatever the task function returns when it is finished.
*/
const gulpify = (name, task) => {
// const colors = require('colors');
const isPromise = value => (
typeof value === 'object' &&
typeof value.then === 'function'
);
return function (...args) {
const d1 = new Date();
console.log('[' + colors.gray(toTimeString(d1)) + '] Starting \'' + colors.cyan(name) + '\'...');
let result = task(...args);
if (!isPromise(result)) {
result = Promise.resolve(result);
}
return result.then(() => {
const d2 = new Date();
console.log('[' + colors.gray(toTimeString(d2)) + '] Finished \'' + colors.cyan(name) + '\' after ' + colors.blue(timeDifference(d1, d2)));
});
};
};
const filesize = () => {
const sourceFolder = './code/';
// @todo Correct type names to classic and styled and rename the param to
// 'mode'
const types = argv.type ? [argv.type] : ['classic', 'css'];
const filenames = argv.file ? argv.file.split(',') : ['highcharts.src.js'];
const files = filenames.reduce((arr, name) => {
const p = types.map(t => (t === 'css' ? 'js/' : '') + name);
return arr.concat(p);
}, []);
const getGzipSize = content => {
const gzipSize = require('gzip-size');
return gzipSize.sync(content);
};
// const pad = (str, x) => ' '.repeat(x) + str;