This repository has been archived by the owner on May 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tools.js
1107 lines (961 loc) · 29.5 KB
/
tools.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
// generator-ego (https://github.com/egodigital/generator-ego)
// Copyright (C) 2018 e.GO Digital GmbH, Aachen, Germany
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
const _ = require('lodash');
const ejs = require('ejs');
const fs = require('fs');
const fsExtra = require('fs-extra');
const htmlEntities = require('html-entities').AllHtmlEntities;
const got = require('got');
const minimatch = require('minimatch');
const ora = require('ora');
const os = require('os');
const path = require('path');
const sanitizeFilename = require('sanitize-filename');
const signale = require('signale');
const xmlJS = require('xml-js');
const zip = require('node-zip');
/**
* Class with tools for the 'tools' property of a generator instance.
*/
module.exports = class {
/**
* Initializes a new instance of that class.
*
* @param {Object} generator The underlying generator.
*/
constructor(generator) {
this.generator = generator;
}
/**
* Keeps sure a value is an array.
*
* @param {any} val The input value.
* @param {Boolean} [noEmpty] Remove items, which are (null) or (undefined). Default: (true)
*
* @return {Array} The output value.
*/
asArray(val, noEmpty) {
if (arguments.length < 2) {
noEmpty = true;
}
if (!Array.isArray(val)) {
val = [ val ];
}
return val.filter(x => {
if (noEmpty) {
return !_.isNil(x);
}
return true;
});
}
/**
* Asks if a 'git init' should be executed in a specific directory.
*
* @param {string} dir The directory where to execute the command in.
*
* @return {Promise<boolean>} The promise that indicates if command has been executed or not.
*/
async askForGitInit(dir) {
const DO_GIT_INIT = (await this.generator.prompt([{
type: 'confirm',
name: 'ego_confirm',
message: 'Initialize a Git repository?',
default: true
}]))['ego_confirm'];
if (DO_GIT_INIT) {
this.log(`Running 'git init' ...`);
this.generator.spawnCommandSync('git', ['init'], {
'cwd': dir
});
const GIT_ORIGIN = String(
(await this.prompt([{
type: 'input',
name: 'ego_git_origin',
message: 'Enter the (optional) URL of your Git remote repository (origin):',
}]))['ego_git_origin']
).trim();
if ('' !== GIT_ORIGIN) {
this.generator.spawnCommandSync('git', ['remote', 'add', 'origin', GIT_ORIGIN], {
'cwd': dir
});
}
return true;
}
return false;
}
/**
* Asks for project name and title.
*
* @return {Object|false} The object with the data or (false) if cancelled.
*/
async askForNameAndTitle() {
const ME = this;
let name = String(
(await this.prompt([{
type: 'input',
name: 'ego_name',
message: 'Enter the NAME of your project:',
validate: (val) => {
return '' !== String(val).trim();
}
}]))['ego_name']
).trim();
if ('' === name) {
return false;
}
let title = String(
(await this.prompt([{
type: 'input',
name: 'ego_title',
message: "Enter the project's TITLE:",
default: name,
}]))['ego_title']
).trim();
if ('' === title) {
title = name;
}
name = name.toLowerCase();
return {
name: name,
fileName: sanitizeFilename(name),
getDestinationDir: function(throwIfExist) {
if (arguments.length < 1) {
throwIfExist = true;
}
const DEST_DIR = path.resolve(
path.join(
ME.generator.destinationPath(
this.fileName
),
)
);
if (throwIfExist) {
if (fs.existsSync(DEST_DIR)) {
throw new Error('[ERROR] Target directory already exists!');
}
}
return DEST_DIR;
},
mkDestinationDir() {
const DEST_DIR = this.getDestinationDir(true);
fs.mkdirSync(DEST_DIR);
ME.log(`Created target directory '${ DEST_DIR }'.`);
return DEST_DIR;
},
title: title,
};
}
/**
* Asks for opening Visual Studio Code for a specific directory.
*
* @param {string} dir The directory (or file) to open.
* @param {Array} [files] One or more additional file to open.
*/
async askForOpenVSCode(dir, files) {
const OPEN_VSCODE = (await this.generator.prompt([{
type: 'confirm',
name: 'ego_confirm',
message: 'Open Visual Studio Code?',
default: true,
}]))['ego_confirm'];
if (!files) {
files = [];
}
if (OPEN_VSCODE) {
this.generator
.spawnCommand('code', [ dir ].concat(files));
return true;
}
return false;
}
/**
* Compares two values.
*
* @param {any} x The left value.
* @param {any} y The right value.
*
* @return {Number} 0 => both are equal; 1 => x > y; -1 => x < y
*/
compareValues(x, y) {
return this.compareValuesBy(x, y,
i => i);
}
/**
* Compares two values by using a selector.
*
* @param {any} x The left value.
* @param {any} y The right value.
* @param {Function} selector The function that selects the values for x and y to compare.
*
* @return {Number} 0 => both are equal; 1 => x > y; -1 => x < y
*/
compareValuesBy(x, y, selector) {
const VAL_X = selector(x);
const VAL_Y = selector(y);
if (VAL_X !== VAL_Y) {
if (VAL_X < VAL_Y) {
return -1;
}
if (VAL_X > VAL_Y) {
return 1;
}
}
return 0;
}
/**
* Prompts for a message to confirm.
*
* @param {String} message The message,
* @param {Object} [opts] Custom options.
*
* @return {Promise<Boolean>} The promise with the selected value.
*/
async confirm(message, opts) {
if (arguments.length < 2) {
opts = {};
}
return (await this.prompt([{
'type': 'confirm',
'name': 'ego_confirm',
'message': this.toStringSafe(message),
'default': opts.default,
}]))['ego_confirm'];
}
/**
* Copies files from one destination to another by using patterns.
*
* @param {String} from The source directory.
* @param {String} to The target directory.
* @param {String|Array} [patterns] The (minimatch) patters, that describes, what elements to use. Default: '**'
* @param {String|Array} [excludes] The (minimatch) patters, that describes, what elements to exclude.
*/
copy(from, to, patterns, excludes) {
this.log(`Copying files to '${ to }' ...`);
this.copyInner(from, to, {
'excludes': excludes,
'path': '/',
'patterns': patterns,
});
}
/**
* Copies all files from a source directory to a destination.
*
* @param {string} from The source directory.
* @param {string} to The target directory.
*/
copyAll(from, to) {
this.log(`Copying files to '${ to }' ...`);
this.copyAllInner(from, to);
}
copyAllInner(from, to) {
from = path.resolve(
from
);
to = path.resolve(
to
);
if (!fsExtra.existsSync(to)) {
fsExtra.mkdirSync(to);
}
for (const ITEM of fsExtra.readdirSync(from)) {
const FROM_ITEM = path.resolve(
path.join(
from, ITEM
)
);
const TO_ITEM = path.resolve(
path.join(
to, ITEM
)
);
const STAT = fsExtra.statSync(FROM_ITEM);
if (STAT.isDirectory()) {
this.copyAllInner(FROM_ITEM, TO_ITEM);
} else {
fsExtra.copySync(FROM_ITEM, TO_ITEM);
}
}
}
copyInner(from, to, opts) {
from = path.resolve(
from
);
to = path.resolve(
to
);
const INCLUDE_PATTERNS = this.asArray(opts.patterns)
.map(p => String(p))
.filter(p => '' !== p.trim());
if (INCLUDE_PATTERNS.length < 1) {
INCLUDE_PATTERNS.push('**');
}
for (const ITEM of fsExtra.readdirSync(from)) {
const FROM_ITEM = path.resolve(
path.join(
from, ITEM
)
);
const STAT = fsExtra.statSync(FROM_ITEM);
// with and without beginning slashed
const FROM_ITEMS_RELATIVE = [
opts.path + ITEM
];
FROM_ITEMS_RELATIVE.push(
FROM_ITEMS_RELATIVE[0].substr(1)
);
if (STAT.isDirectory()) {
// add expressions with ending slash
FROM_ITEMS_RELATIVE.push(
FROM_ITEMS_RELATIVE[0] + '/'
);
FROM_ITEMS_RELATIVE.push(
FROM_ITEMS_RELATIVE[1].substr(1) + '/'
);
}
const TO_ITEM = path.resolve(
path.join(
to, ITEM
)
);
if (STAT.isDirectory()) {
this.copyInner(FROM_ITEM, TO_ITEM, {
'excludes': opts.excludes,
'path': opts.path + ITEM + '/',
'patterns': opts.patterns,
});
} else {
if (!FROM_ITEMS_RELATIVE.some(x => this.doesMatch(x, opts.excludes))) {
// not excluded
if (FROM_ITEMS_RELATIVE.some(x => this.doesMatch(x, INCLUDE_PATTERNS))) {
// included
// keep sure the target directory exists
const TARGET_DIR = path.dirname(
TO_ITEM
);
if (!fsExtra.existsSync(TARGET_DIR)) {
fsExtra.mkdirsSync(TARGET_DIR);
}
fsExtra.copySync(FROM_ITEM, TO_ITEM);
}
}
}
}
}
/**
* Copies a rendered README.md file to a destination.
*
* @param {string} from The source directory.
* @param {string} to The destination directory.
* @param {any} [data] Data for rendering.
*/
copyREADME(from, to, data) {
this.log(`Setting up 'README.md' ...`);
const CONTENT = fs.readFileSync(
from + '/README.md',
'utf8'
);
fs.writeFileSync(
to + '/README.md',
ejs.render(CONTENT, data),
'utf8'
);
}
/**
* Creates a '.env' file in a specific directory.
*
* @param {string} outDir The directory where to create the file to.
* @param {Object} values Key-value pair of variables.
*/
createEnv(outDir, values) {
this.log(`Creating '.env' ...`);
const LINES = [];
for (const KEY in values) {
LINES.push(
`${String(KEY).toUpperCase().trim()}=${String(values[KEY])}`
);
}
LINES.push('');
fs.writeFileSync(
String(outDir) + '/.env',
LINES.join("\n"),
'utf8'
);
}
/**
* Creates a '.gitignore' file in a specific directory.
*
* @param {string} outDir The directory where to create the file to.
* @param {Array} entries The list of entries for the file.
*/
createGitIgnore(outDir, entries) {
this.log(`Creating '.gitignore' ...`);
fs.writeFileSync(
String(outDir) + '/.gitignore',
entries.join("\n"),
'utf8'
);
}
/**
* Checks if a value matches a (minimatch) pattern.
*
* @param {any} val The input value.
* @param {String|Array} patterns One or more patterns.
*/
doesMatch(val, patterns) {
val = String(val);
return this.asArray(patterns)
.map(p => String(p))
.filter(p => '' !== p.trim())
.some(p => minimatch(val, p, { dot: true }));
}
/**
* Downloads a file.
*
* @param {String} url The URL of the file.
*
* @return {Buffer} The downloaded data.
*/
async download(url) {
url = String(url);
this.log(`Downloading file '${ url }' ...`);
const RESPONSE = await got(url);
if (RESPONSE.statusCode >= 400 && RESPONSE.statusCode < 500) {
throw new Error(`Client error: [${ RESPONSE.statusCode }] '${ RESPONSE.statusMessage }'`);
}
if (RESPONSE.statusCode >= 500 && RESPONSE.statusCode < 600) {
throw new Error(`Server error: [${ RESPONSE.statusCode }] '${ RESPONSE.statusMessage }'`);
}
if (RESPONSE.statusCode >= 600) {
throw new Error(`Unknown error: [${ RESPONSE.statusCode }] '${ RESPONSE.statusMessage }'`);
}
if (204 == RESPONSE.statusCode) {
return Buffer.alloc(0);
}
if (200 != RESPONSE.statusCode) {
throw new Error(`Unexpected response: [${ RESPONSE.statusCode }] '${ RESPONSE.statusMessage }'`);
}
return RESPONSE.body;
}
/**
* Downloads a Git repository to a destination.
*
* @param {String} repo The (source of the) repository.
* @param {String} dest The destination folder.
* @param {Object} [opts] Custom options.
*/
async downloadGitRepo(repo, dest, opts) {
const ME = this;
if (arguments.length < 3) {
opts = {};
}
repo = String(repo);
dest = path.resolve(
String(dest)
);
const GIT_FOLDER = path.resolve(
path.join(
dest, '.git'
)
);
// first clone ...
this.log(`Downloading Git repo from '${repo}' ...`);
this.generator.spawnCommandSync('git', ['clone', '--depth=1', repo, '.'], {
'cwd': dest
});
// ... then remove '.git' folder
fsExtra.removeSync(GIT_FOLDER);
const YO_EGO_FILE = path.resolve(
path.join(
dest, '.yo-ego.js'
)
);
if (fs.existsSync(YO_EGO_FILE)) {
this.log(`Executing Git repo hooks in '${path.basename(YO_EGO_FILE)}' ...`);
delete require.cache[YO_EGO_FILE];
const YO_EGO_MODULE = require(YO_EGO_FILE);
if (YO_EGO_MODULE) {
if (YO_EGO_MODULE.downloaded) {
await Promise.resolve(
YO_EGO_MODULE.downloaded
.apply(ME.generator, [{
dir: dest,
'event': 'downloaded',
generator: ME.generator,
repository: repo,
tag: opts.tag
}])
);
}
}
fs.unlinkSync(YO_EGO_FILE);
}
}
/**
* Encodes a string for HTML output.
*
* @param {string} str The input string.
*
* @return {string} The encoded string.
*/
encodeHtml(str) {
const HTML = new htmlEntities();
return HTML.encode(
String(str)
);
}
/**
* Creates an object from XML data.
*
* @param {String|Buffer} xml The raw XML data.
* @param {Boolean} [compact] Returns compact data or not. Default: (false)
*
* @return {Object} The XML object.
*/
fromXml(xml, compact) {
if (arguments.length < 2) {
compact = false;
}
if (Buffer.isBuffer(xml)) {
xml = xml.toString('utf8');
} else {
xml = this.toStringSafe(xml);
}
return JSON.parse(
xmlJS.xml2json(xml, {
compact: compact,
spaces: 2,
})
);
}
/**
* Checks if current user has SSH keys stored inside its home directory.
*
* @return {Boolean} Has SSH keys or not.
*/
hasSSHKeys() {
const PRIV_KEY = path.join(
os.homedir(), '.ssh/id_rsa'
);
const PUB_KEY = path.join(
os.homedir(), '.ssh/id_rsa.pub'
);
return this.isFile(PRIV_KEY) &&
this.isFile(PUB_KEY);
}
/**
* Returns a full, joined path relative to the '.generator-ego'
* folder, inside the current user's home directory.
*
* @param {string[]} [paths] The paths (parts) to join.
*
* @return {string} The full, joined path.
*/
homePath() {
const ARGS = [];
for (let i = 0; i < arguments.length; i++) {
ARGS.push(
this.toStringSafe(arguments[i])
);
}
const GENERATOR_DIR = path.resolve(
path.join(
os.homedir(), '.generator-ego'
)
);
return path.resolve(
path.join
.apply(path, [ GENERATOR_DIR ].concat( ARGS ))
);
}
/**
* Checks if a path exists and is a directory.
*
* @param {String} path The path to check.
*
* @return {Boolean} Path does exist and is a directory or not.
*/
isDir(path) {
return this.isExistingFileSystemItem(
path, s => s.isDirectory()
);
}
isExistingFileSystemItem(path, statSelector) {
path = this.toStringSafe(path);
if (fsExtra.existsSync(path)) {
return statSelector(
fsExtra.statSync(path)
);
}
return false;
}
/**
* Checks if a path exists and is a file.
*
* @param {String} path The path to check.
*
* @return {Boolean} Path does exist and is a file or not.
*/
isFile(path) {
return this.isExistingFileSystemItem(
path, s => s.isFile()
);
}
/**
* Short "path" to 'log()' method of underlying generator.
*
* @return this
*/
log() {
this.generator
.log
.apply(this.generator, arguments);
return this;
}
/**
* Invokes a function for log interactivly.
*
* @param {String} scope The scope.
* @param {Function} func The function to invoke.
* The underlying, interactive Signale logger is submitted to that functions as first argument.
*
* @return {Promise} The promise with the result of the function.
*/
async logInteractive(scope, func) {
const INTERACTIVE_LOGGER = new signale.Signale({
interactive: true
});
INTERACTIVE_LOGGER.scope(this.toStringSafe(scope));
try {
return await Promise.resolve(
func.apply(this.generator,
[ INTERACTIVE_LOGGER ])
);
} finally {
INTERACTIVE_LOGGER.unscope();
process.stdout.write(
os.EOL
);
}
}
/**
* Invokes a function for log interactivly (synchronously).
*
* @param {String} scope The scope.
* @param {Function} func The function to invoke.
* The underlying, interactive Signale logger is submitted to that functions as first argument.
*
* @return {any} The result of the function.
*/
logInteractiveSync(scope, func) {
const INTERACTIVE_LOGGER = new signale.Signale({
interactive: true
});
INTERACTIVE_LOGGER.scope(this.toStringSafe(scope));
try {
return func.apply(this.generator,
[ INTERACTIVE_LOGGER ]);
} finally {
INTERACTIVE_LOGGER.unscope();
process.stdout.write(
os.EOL
);
}
}
/**
* Creates a folder inside the destination path.
*
* @param {String} name The name of the target folder.
* @param {Boolean} [throwIfExist] Throw an exception if folder already exists or not. Default: true
*
* @return {String} The path of the created folder.
*/
mkDestinationDir(name, throwIfExist) {
const DEST_DIR = path.resolve(
path.join(
this.generator.destinationPath(
sanitizeFilename(
this.toStringSafe(name).trim()
)
),
)
);
return this.withSpinnerSync(`Creating destination directory '${ DEST_DIR }' ...`, (spinner) => {
try {
if (throwIfExist) {
if (fs.existsSync(DEST_DIR)) {
throw new Error('[ERROR] Destination directory already exists!');
}
}
fs.mkdirSync(DEST_DIR);
spinner.succeed(`Created destination directory '${ DEST_DIR }'.`);
return DEST_DIR;
} catch (e) {
spinner.fail(`Could not created destination directory '${ DEST_DIR }': ${ this.toStringSafe(e) }`);
process.exit(1);
}
});
}
/**
* Short "path" to 'prompt()' method of underlying generator.
*/
prompt() {
return this.generator
.prompt
.apply(this.generator, arguments);
}
/**
* Prompts for an item of a (string) list.
*
* @param {String} message The message,
* @param {Array} list The list of items.
* @param {Object} [opts] Custom options.
*
* @return {Promise<String>} The promise with the selected item.
*/
async promptList(message, list, opts) {
if (arguments.length < 3) {
opts = {};
}
return (await this.prompt([{
'type': 'list',
'name': 'ego_item',
'message': this.toStringSafe(message),
'choices': this.asArray(list),
'default': opts.default,
}]))['ego_item'];
}
/**
* Prompt for selecting items.
*
* @param {String} message The message.
* @param {Object} items The items, which can be selected.
*
* @return {Promise<Array>} The promise with the array of selected values.
*/
async promptMultiSelect(message, items) {
return (await this.prompt([{
'type': 'checkbox',
'name': 'ego_checked_items',
'message': this.toStringSafe(message),
'choices': items,
}]))['ego_checked_items'];
}
/**
* Prompts for a string.
*
* @param {String} message The message,
* @param {Object} [opts] Custom options.
*
* @return {Promise<string>} The promise with the input value.
*/
async promptString(message, opts) {
if (arguments.length < 2) {
opts = {};
}
let validator = opts.validator;
if (validator) {
if (true === validator) {
validator = (val) => {
return '' !== this.toStringSafe(val)
.trim();
};
}
}
let defaultValue = this.toStringSafe(opts.default);
const PROMPT_OPTS = {
type: 'input',
name: 'ego_value',
message: this.toStringSafe(message),
validate: validator
};
if ('' !== defaultValue) {
PROMPT_OPTS.default = defaultValue;
}
return (await this.prompt([
PROMPT_OPTS
]))['ego_value'];
}
/**
* Opens a module in generator's context.
*
* @param {String} id The ID/path of the module.
*
* @return {Object} The module.
*/
require(id) {
return require(id);
}
/**
* Runs 'npm install' inside a directory.
*
* @param {string} dir The directory where to execute the command in.
*/
runNPMInstall(dir) {
this.log(`Installing NPM modules ...`);
this.generator.spawnCommandSync('npm', ['install'], {
'cwd': dir
});
}
/**
* A promise version of 'setTimeout()' function.
*
* @param {Number} ms The time to wait, in milliseconds.
*/
sleep(ms) {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
resolve();
}, ms);
} catch (e) {
reject(e);
}
});
}
/**
* Creates a clone of an object and sort its keys.
*
* @param {any} obj The object.
* @param {Function} [keyComparer] The custom key comparer.
*
* @return {any} The cloned object.
*/
sortObjectByKey(obj, keyComparer) {
if (arguments.length < 2) {
keyComparer = (key) => {
return this.toStringSafe(key)
.toLowerCase()
.trim();
};
}
if (!obj) {
return obj;
}
// extract keys and sort them
const KEYS = Object.keys(
obj
).sort((x, y) => {
return this.compareValuesBy(x, y,
keyComparer);
});
// create new object
const NEW_OBJ = {};
for (const K of KEYS) {
NEW_OBJ[K] = obj[K];
}
return NEW_OBJ;
}
/**
* Converts a value to a string.
*
* @param {any} val The input value.
* @param {String} [defaultValue] The custom default value. Default: ''
*
* @return {String} The output value.
*/
toStringSafe(val, defaultValue) {