-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathgenerator.ts
1412 lines (1285 loc) · 52.3 KB
/
generator.ts
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
/**
* Copyright 2013-2024 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { basename, dirname, extname, isAbsolute, join, join as joinPath, relative } from 'path';
import { relative as posixRelative } from 'path/posix';
import { createHash } from 'crypto';
import { fileURLToPath } from 'url';
import { existsSync, readFileSync, rmSync, statSync } from 'fs';
import assert from 'assert';
import { requireNamespace } from '@yeoman/namespace';
import type { GeneratorMeta } from '@yeoman/types';
import chalk from 'chalk';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { defaults, get, kebabCase, merge, mergeWith, set, snakeCase } from 'lodash-es';
import { simpleGit } from 'simple-git';
import type { CopyOptions } from 'mem-fs-editor';
import type { Data as TemplateData, Options as TemplateOptions } from 'ejs';
import semver, { lt as semverLessThan } from 'semver';
import YeomanGenerator, { type ComposeOptions, type Storage } from 'yeoman-generator';
import type Environment from 'yeoman-environment';
import latestVersion from 'latest-version';
import SharedData from '../base/shared-data.js';
import { CUSTOM_PRIORITIES, PRIORITY_NAMES, PRIORITY_PREFIX, QUEUES } from '../base/priorities.js';
import type { Logger } from '../base/support/index.js';
import { createJHipster7Context, formatDateForChangelog, joinCallbacks, removeFieldsWithNullishValues } from '../base/support/index.js';
import type {
CascatedEditFileCallback,
EditFileCallback,
EditFileOptions,
JHipsterGeneratorFeatures,
JHipsterGeneratorOptions,
ValidationResult,
WriteFileOptions,
} from '../base/api.js';
import {
type JHipsterArguments,
type JHipsterCommandDefinition,
type JHipsterConfigs,
type JHipsterOptions,
convertConfigToOption,
} from '../../lib/command/index.js';
import { packageJson } from '../../lib/index.js';
import type { BaseApplication } from '../base-application/types.js';
import { GENERATOR_BOOTSTRAP } from '../generator-list.js';
import NeedleApi from '../needle-api.js';
import baseCommand from '../base/command.js';
import { GENERATOR_JHIPSTER, YO_RC_FILE } from '../generator-constants.js';
import { loadConfig, loadDerivedConfig } from '../../lib/internal/index.js';
import { getGradleLibsVersionsProperties } from '../gradle/support/dependabot-gradle.js';
import { dockerPlaceholderGenerator } from '../docker/utils.js';
import { getConfigWithDefaults } from '../../lib/jhipster/index.js';
import { extractArgumentsFromConfigs } from '../../lib/command/index.js';
import type BaseApplicationGenerator from '../base-application/generator.js';
import type { ApplicationConfiguration } from '../../lib/types/application/yo-rc.js';
const {
INITIALIZING,
PROMPTING,
CONFIGURING,
COMPOSING,
COMPOSING_COMPONENT,
LOADING,
PREPARING,
POST_PREPARING,
DEFAULT,
WRITING,
POST_WRITING,
INSTALL,
POST_INSTALL,
END,
} = PRIORITY_NAMES;
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const asPriority = (priorityName: string) => `${PRIORITY_PREFIX}${priorityName}`;
const relativeDir = (from: string, to: string) => {
const rel = posixRelative(from, to);
return rel ? `${rel}/` : '';
};
const deepMerge = (source1: any, source2: any) => mergeWith({}, source1, source2, (a, b) => (Array.isArray(a) ? a.concat(b) : undefined));
/**
* This is the base class for a generator for every generator.
*/
export default class CoreGenerator extends YeomanGenerator<JHipsterGeneratorOptions, JHipsterGeneratorFeatures> {
static asPriority = asPriority;
static INITIALIZING = asPriority(INITIALIZING);
static PROMPTING = asPriority(PROMPTING);
static CONFIGURING = asPriority(CONFIGURING);
static COMPOSING = asPriority(COMPOSING);
static COMPOSING_COMPONENT = asPriority(COMPOSING_COMPONENT);
static LOADING = asPriority(LOADING);
static PREPARING = asPriority(PREPARING);
static POST_PREPARING = asPriority(POST_PREPARING);
static DEFAULT = asPriority(DEFAULT);
static WRITING = asPriority(WRITING);
static POST_WRITING = asPriority(POST_WRITING);
static INSTALL = asPriority(INSTALL);
static POST_INSTALL = asPriority(POST_INSTALL);
static END = asPriority(END);
context?: Record<string, any>;
useVersionPlaceholders?: boolean;
skipChecks?: boolean;
ignoreNeedlesError?: boolean;
experimental?: boolean;
debugEnabled?: boolean;
jhipster7Migration?: boolean | 'verbose' | 'silent';
relativeDir = relativeDir;
relative = posixRelative;
readonly sharedData!: SharedData<any>;
readonly logger: Logger;
jhipsterConfig!: Record<string, any>;
/**
* @deprecated
*/
jhipsterTemplatesFolders!: string[];
blueprintStorage?: Storage;
/** Allow to use a specific definition at current command operations */
generatorCommand?: JHipsterCommandDefinition;
/**
* @experimental
* Additional commands to be considered
*/
generatorsToCompose: string[] = [];
private _jhipsterGenerator?: string;
private _needleApi?: NeedleApi;
// Override the type of `env` to be a full Environment
declare env: Environment;
declare log: Logger;
declare _meta?: GeneratorMeta;
constructor(args: string | string[], options: JHipsterGeneratorOptions, features: JHipsterGeneratorFeatures) {
super(args, options, {
skipParseOptions: true,
tasksMatchingPriority: true,
taskPrefix: PRIORITY_PREFIX,
unique: 'namespace',
...features,
});
if (!this.options.help) {
/* Force config to use 'generator-jhipster' namespace. */
this._config = this._getStorage('generator-jhipster');
/* JHipster config using proxy mode used as a plain object instead of using get/set. */
this.jhipsterConfig = this.config.createProxy();
this.sharedData = this.createSharedData({ help: this.options.help }) as any;
/* Options parsing must be executed after forcing jhipster storage namespace and after sharedData have been populated */
this.parseJHipsterOptions(baseCommand.options);
// Don't write jhipsterVersion to .yo-rc.json when reproducible
if (
this.options.namespace.startsWith('jhipster:') &&
!this.options.namespace.startsWith('jhipster:bootstrap') &&
this.getFeatures().storeJHipsterVersion !== false &&
!this.options.reproducibleTests &&
!this.jhipsterConfig.jhipsterVersion
) {
this.storeCurrentJHipsterVersion();
}
}
this.logger = this.log as any;
if (this.options.help) {
return;
}
this.registerPriorities(CUSTOM_PRIORITIES);
if (this.getFeatures().jhipsterBootstrap ?? true) {
// jhipster:bootstrap is always required. Run it once the environment starts.
this.env.queueTask('environment:run', async () => this.composeWithJHipster(GENERATOR_BOOTSTRAP).then(), {
once: 'queueJhipsterBootstrap',
startQueue: false,
});
}
// Add base template folder.
this.jhipsterTemplatesFolders = [this.templatePath()];
this.jhipster7Migration = this.features.jhipster7Migration ?? false;
if (this.features.queueCommandTasks === true) {
this.on('before:queueOwnTasks', () => {
this.queueCurrentJHipsterCommandTasks();
});
}
}
/**
* Override yeoman generator's usage function to fine tune --help message.
*/
usage(): string {
return super.usage().replace('yo jhipster:', 'jhipster ');
}
storeCurrentJHipsterVersion(): void {
this.jhipsterConfig.jhipsterVersion = packageJson.version;
}
/**
* @deprecated
*/
get needleApi() {
if (this._needleApi === undefined || this._needleApi === null) {
this._needleApi = new NeedleApi(this);
}
return this._needleApi;
}
/**
* JHipster config with default values fallback
*/
get jhipsterConfigWithDefaults(): Readonly<ApplicationConfiguration & Record<string, any>> {
const configWithDefaults = getConfigWithDefaults(removeFieldsWithNullishValues(this.config.getAll()));
defaults(configWithDefaults, {
skipFakeData: false,
skipCheckLengthOfIdentifier: false,
enableGradleEnterprise: false,
pages: [],
});
return configWithDefaults as ApplicationConfiguration;
}
/**
* Warn or throws check failure based on current skipChecks option.
* @param message
*/
handleCheckFailure(message: string) {
if (this.skipChecks) {
this.log.warn(message);
} else {
throw new Error(`${message}
You can ignore this error by passing '--skip-checks' to jhipster command.`);
}
}
/**
* Check if the JHipster version used to generate an existing project is less than the passed version argument
*
* @param {string} version - A valid semver version string
*/
isJhipsterVersionLessThan(version) {
const jhipsterOldVersion = this.sharedData.getControl().jhipsterOldVersion;
return this.isVersionLessThan(jhipsterOldVersion, version);
}
/**
* Wrapper for `semver.lt` to check if the oldVersion exists and is less than the newVersion.
* Can be used by blueprints.
*/
isVersionLessThan(oldVersion: string | null, newVersion: string) {
return oldVersion ? semverLessThan(oldVersion, newVersion) : false;
}
/**
* Get arguments for the priority
*/
getArgsForPriority(priorityName: string) {
const control = this.sharedData.getControl();
if (priorityName === POST_WRITING || priorityName === PREPARING || priorityName === POST_PREPARING) {
const source = this.sharedData.getSource();
return [{ control, source }];
}
if (priorityName === WRITING) {
if (existsSync(this.destinationPath(YO_RC_FILE))) {
try {
const oldConfig = JSON.parse(readFileSync(this.destinationPath(YO_RC_FILE)).toString())[GENERATOR_JHIPSTER];
const newConfig: any = this.config.getAll();
const keys = [...new Set([...Object.keys(oldConfig), ...Object.keys(newConfig)])];
const configChanges = Object.fromEntries(
keys
.filter(key =>
Array.isArray(newConfig[key])
? newConfig[key].length === oldConfig[key].length &&
newConfig[key].find((element, index) => element !== oldConfig[key][index])
: newConfig[key] !== oldConfig[key],
)
.map(key => [key, { newValue: newConfig[key], oldValue: oldConfig[key] }]),
);
return [{ control, configChanges }];
} catch {
// Fail to parse
}
}
}
return [{ control }];
}
/**
* Check if the generator should ask for prompts.
*/
shouldAskForPrompts({ control }): boolean {
return !control.existingProject || this.options.askAnswered === true;
}
/**
* Override yeoman-generator method that gets methods to be queued, filtering the result.
*/
getTaskNames(): string[] {
let priorities = super.getTaskNames();
if (!this.features.disableSkipPriorities && this.options.skipPriorities) {
// Make sure yeoman-generator will not throw on empty tasks due to filtered priorities.
this.customLifecycle = this.customLifecycle || priorities.length > 0;
priorities = priorities.filter(priorityName => !this.options.skipPriorities!.includes(priorityName));
}
return priorities;
}
queueCurrentJHipsterCommandTasks() {
this.queueTask({
queueName: QUEUES.INITIALIZING_QUEUE,
taskName: 'parseCurrentCommand',
cancellable: true,
async method() {
try {
await this.getCurrentJHipsterCommand();
} catch {
return;
}
await this.parseCurrentJHipsterCommand();
},
});
this.queueTask({
queueName: QUEUES.PROMPTING_QUEUE,
taskName: 'promptCurrentCommand',
cancellable: true,
async method() {
try {
const command = await this.getCurrentJHipsterCommand();
if (!command.configs) return;
} catch {
return;
}
const taskArgs = this.getArgsForPriority(PRIORITY_NAMES.INITIALIZING);
const [{ control }] = taskArgs;
if (!control) throw new Error(`Control object not found in ${this.options.namespace}`);
if (!this.shouldAskForPrompts({ control })) return;
await this.promptCurrentJHipsterCommand();
},
});
this.queueTask({
queueName: QUEUES.CONFIGURING_QUEUE,
taskName: 'configureCurrentCommand',
cancellable: true,
async method() {
try {
const command = await this.getCurrentJHipsterCommand();
if (!command.configs) return;
} catch {
return;
}
await this.configureCurrentJHipsterCommandConfig();
},
});
this.queueTask({
queueName: QUEUES.COMPOSING_QUEUE,
taskName: 'composeCurrentCommand',
cancellable: true,
async method() {
try {
await this.getCurrentJHipsterCommand();
} catch {
return;
}
await this.composeCurrentJHipsterCommand();
},
});
this.queueTask({
queueName: QUEUES.LOADING_QUEUE,
taskName: 'loadCurrentCommand',
cancellable: true,
async method() {
try {
const command = await this.getCurrentJHipsterCommand();
if (!command.configs) return;
const taskArgs = this.getArgsForPriority(PRIORITY_NAMES.LOADING);
const [{ application }] = taskArgs as any;
loadConfig.call(this, command.configs, { application: application ?? this });
loadDerivedConfig(command.configs, { application });
} catch {
// Ignore non existing command
}
},
});
}
/**
* Get the current Command Definition for the generator.
* `generatorCommand` takes precedence.
*/
async getCurrentJHipsterCommand(): Promise<JHipsterCommandDefinition> {
if (!this.generatorCommand) {
const { command } = ((await this._meta?.importModule?.()) ?? {}) as any;
if (!command) {
throw new Error(`Command not found for generator ${this.options.namespace}`);
}
this.generatorCommand = command;
return command;
}
return this.generatorCommand;
}
/**
* Parse command definition arguments, options and configs.
* Blueprints with command override takes precedence.
*/
async parseCurrentJHipsterCommand() {
const generatorCommand = await this.getCurrentJHipsterCommand();
this.parseJHipsterCommand(generatorCommand);
}
/**
* Prompts for command definition configs.
* Blueprints with command override takes precedence.
*/
async promptCurrentJHipsterCommand() {
const generatorCommand = await this.getCurrentJHipsterCommand();
if (!generatorCommand.configs) {
throw new Error(`Configs not found for generator ${this.options.namespace}`);
}
return this.prompt(this.prepareQuestions(generatorCommand.configs) as any);
}
/**
* Configure the current JHipster command.
* Blueprints with command override takes precedence.
*/
async configureCurrentJHipsterCommandConfig() {
const generatorCommand = await this.getCurrentJHipsterCommand();
if (!generatorCommand.configs) {
throw new Error(`Configs not found for generator ${this.options.namespace}`);
}
for (const def of Object.values(generatorCommand.configs)) {
def.configure?.(this);
}
}
/**
* Load the current JHipster command storage configuration into the context.
* Blueprints with command override takes precedence.
*/
async loadCurrentJHipsterCommandConfig(context: any) {
const generatorCommand = await this.getCurrentJHipsterCommand();
if (!generatorCommand.configs) {
throw new Error(`Configs not found for generator ${this.options.namespace}`);
}
loadConfig.call(this, generatorCommand.configs, { application: context });
}
/**
* @experimental
* Compose the current JHipster command compose.
* Blueprints commands compose without generators will be composed.
*/
async composeCurrentJHipsterCommand() {
const generatorCommand = await this.getCurrentJHipsterCommand();
for (const compose of generatorCommand.compose ?? []) {
await this.composeWithJHipster(compose);
}
for (const compose of this.generatorsToCompose) {
await this.composeWithJHipster(compose);
}
}
parseJHipsterCommand(commandDef: JHipsterCommandDefinition) {
if (commandDef.arguments) {
this.parseJHipsterArguments(commandDef.arguments);
} else if (commandDef.configs) {
this.parseJHipsterArguments(extractArgumentsFromConfigs(commandDef.configs));
}
if (commandDef.options || commandDef.configs) {
this.parseJHipsterOptions(commandDef.options, commandDef.configs);
}
}
parseJHipsterOptions(options: JHipsterOptions | undefined, configs: JHipsterConfigs | boolean = {}, common = false) {
if (typeof configs === 'boolean') {
common = configs;
configs = {};
}
Object.entries(options ?? {})
.concat(Object.entries(configs).map(([name, def]) => [name, convertConfigToOption(name, def)]) as any)
.forEach(([optionName, optionDesc]) => {
if (!optionDesc?.type || !optionDesc.scope || (common && optionDesc.scope === 'generator')) return;
let optionValue;
// Hidden options are test options, which doesn't rely on commander for options parsing.
// We must parse environment variables manually
if (this.options[optionDesc.name ?? optionName] === undefined && optionDesc.env && process.env[optionDesc.env]) {
optionValue = process.env[optionDesc.env];
} else {
optionValue = this.options[optionDesc.name ?? optionName];
}
if (optionValue !== undefined) {
optionValue = optionDesc.type !== Array && optionDesc.type !== Function ? optionDesc.type(optionValue) : optionValue;
if (optionDesc.scope === 'storage') {
this.config.set(optionName, optionValue);
} else if (optionDesc.scope === 'blueprint') {
this.blueprintStorage!.set(optionName, optionValue);
} else if (optionDesc.scope === 'control') {
this.sharedData.getControl()[optionName] = optionValue;
} else if (optionDesc.scope === 'generator') {
this[optionName] = optionValue;
} else if (optionDesc.scope === 'context') {
this.context![optionName] = optionValue;
} else if (optionDesc.scope !== 'none') {
throw new Error(`Scope ${optionDesc.scope} not supported`);
}
} else if (optionDesc.default !== undefined && optionDesc.scope === 'generator' && this[optionName] === undefined) {
this[optionName] = optionDesc.default;
}
});
}
parseJHipsterArguments(jhipsterArguments: JHipsterArguments = {}) {
const hasPositionalArguments = Boolean(this.options.positionalArguments);
let positionalArguments: unknown[] = hasPositionalArguments ? this.options.positionalArguments! : this._args;
const argumentEntries = Object.entries(jhipsterArguments);
if (hasPositionalArguments && positionalArguments.length > argumentEntries.length) {
throw new Error('More arguments than allowed');
}
argumentEntries.find(([argumentName, argumentDef]) => {
if (positionalArguments.length > 0) {
let argument;
if (hasPositionalArguments || argumentDef.type !== Array) {
// Positional arguments already parsed or a single argument.
argument = Array.isArray(positionalArguments) ? positionalArguments.shift() : positionalArguments;
} else {
// Varags argument.
argument = positionalArguments;
positionalArguments = [];
}
// Replace varargs empty array with undefined.
argument = Array.isArray(argument) && argument.length === 0 ? undefined : argument;
if (argument !== undefined) {
const convertedValue = !argumentDef.type || argumentDef.type === Array ? argument : argumentDef.type(argument);
if (argumentDef.scope === undefined || argumentDef.scope === 'generator') {
this[argumentName] = convertedValue;
} else if (argumentDef.scope === 'context') {
this.context![argumentName] = convertedValue;
} else if (argumentDef.scope === 'storage') {
this.config.set(argumentName, convertedValue);
} else if (argumentDef.scope === 'blueprint') {
this.blueprintStorage!.set(argumentName, convertedValue);
}
}
} else {
if (argumentDef.required) {
throw new Error(`Missing required argument ${argumentName}`);
}
return true;
}
return false;
});
// Arguments should only be parsed by the root generator, cleanup to don't be forwarded.
this.options.positionalArguments = [];
}
prepareQuestions(configs: JHipsterConfigs = {}) {
return Object.entries(configs)
.filter(([_name, def]) => def?.prompt)
.map(([name, def]) => {
let promptSpec = typeof def.prompt === 'function' ? def.prompt(this as any, def) : { ...def.prompt };
let storage: any;
if ((def.scope ?? 'storage') === 'storage') {
storage = this.config;
if (promptSpec.default === undefined) {
promptSpec = { ...promptSpec, default: () => (this as any).jhipsterConfigWithDefaults?.[name] };
}
} else if (def.scope === 'blueprint') {
storage = this.blueprintStorage;
} else if (def.scope === 'generator') {
storage = {
getPath: path => get(this, path),
setPath: (path, value) => set(this, path, value),
};
} else if (def.scope === 'context') {
storage = {
getPath: path => get(this.context, path),
setPath: (path, value) => set(this.context!, path, value),
};
}
return {
name,
choices: def.choices,
...promptSpec,
storage,
};
});
}
/**
* Generate a date to be used by Liquibase changelogs.
*
* @param {Boolean} [reproducible=true] - Set true if the changelog date can be reproducible.
* Set false to create a changelog date incrementing the last one.
* @return {String} Changelog date.
*/
dateFormatForLiquibase(reproducible?: boolean) {
const control = this.sharedData.getControl();
reproducible = reproducible ?? Boolean(control.reproducible);
// Use started counter or use stored creationTimestamp if creationTimestamp option is passed
const creationTimestamp = this.options.creationTimestamp ? this.config.get('creationTimestamp') : undefined;
let now = new Date();
// Miliseconds is ignored for changelogDate.
now.setMilliseconds(0);
// Run reproducible timestamp when regenerating the project with reproducible option or an specific timestamp.
if (reproducible || creationTimestamp) {
if (control.reproducibleLiquibaseTimestamp) {
// Counter already started.
now = control.reproducibleLiquibaseTimestamp;
} else {
// Create a new counter
const newCreationTimestamp: string = (creationTimestamp as string) ?? this.config.get('creationTimestamp');
now = newCreationTimestamp ? new Date(newCreationTimestamp) : now;
now.setMilliseconds(0);
}
now.setMinutes(now.getMinutes() + 1);
control.reproducibleLiquibaseTimestamp = now;
// Reproducible build can create future timestamp, save it.
const lastLiquibaseTimestamp = this.jhipsterConfig.lastLiquibaseTimestamp;
if (!lastLiquibaseTimestamp || now.getTime() > lastLiquibaseTimestamp) {
this.config.set('lastLiquibaseTimestamp', now.getTime());
}
} else {
// Get and store lastLiquibaseTimestamp, a future timestamp can be used
let lastLiquibaseTimestamp = this.jhipsterConfig.lastLiquibaseTimestamp;
if (lastLiquibaseTimestamp) {
lastLiquibaseTimestamp = new Date(lastLiquibaseTimestamp);
if (lastLiquibaseTimestamp >= now) {
now = lastLiquibaseTimestamp;
now.setSeconds(now.getSeconds() + 1);
now.setMilliseconds(0);
}
}
this.jhipsterConfig.lastLiquibaseTimestamp = now.getTime();
}
return formatDateForChangelog(now);
}
/**
* Alternative templatePath that fetches from the blueprinted generator, instead of the blueprint.
*/
jhipsterTemplatePath(...path: string[]) {
let existingGenerator: string;
try {
existingGenerator = this._jhipsterGenerator ?? requireNamespace(this.options.namespace).generator;
} catch {
if (this.options.namespace) {
const split = this.options.namespace.split(':', 2);
existingGenerator = split.length === 1 ? split[0] : split[1];
} else {
throw new Error('Could not determine the generator name');
}
}
this._jhipsterGenerator = existingGenerator;
return this._jhipsterGenerator
? this.fetchFromInstalledJHipster(this._jhipsterGenerator, 'templates', ...path)
: this.templatePath(...path);
}
/**
* Compose with a jhipster generator using default jhipster config.
* @return {object} the composed generator
*/
async composeWithJHipster<const G extends string>(gen: G, options?: ComposeOptions<BaseApplicationGenerator>) {
assert(typeof gen === 'string', 'generator should to be a string');
let generator: string = gen;
if (!isAbsolute(generator)) {
const namespace = generator.includes(':') ? generator : `jhipster:${generator}`;
if (await this.env.get(namespace)) {
generator = namespace;
} else {
throw new Error(`Generator ${generator} was not found`);
}
}
return this.composeWith(generator, {
forwardOptions: false,
...options,
generatorOptions: {
...this.options,
positionalArguments: undefined,
...options?.generatorOptions,
} as any,
});
}
/**
* Compose with a jhipster generator using default jhipster config, but queue it immediately.
*/
async dependsOnJHipster(generator: string, options?: ComposeOptions<BaseApplicationGenerator>) {
return this.composeWithJHipster(generator, {
...options,
schedule: false,
});
}
/**
* Remove File
* @param file
*/
removeFile(...path: string[]) {
const destinationFile = this.destinationPath(...path);
const relativePath = relative((this.env as any).logCwd, destinationFile);
// Delete from memory fs to keep updated.
this.fs.delete(destinationFile);
try {
if (destinationFile && statSync(destinationFile).isFile()) {
this.log.info(`Removing legacy file ${relativePath}`);
rmSync(destinationFile, { force: true });
}
} catch {
this.log.info(`Could not remove legacy file ${relativePath}`);
}
return destinationFile;
}
/**
* Remove Folder
* @param path
*/
removeFolder(...path: string[]) {
const destinationFolder = this.destinationPath(...path);
const relativePath = relative((this.env as any).logCwd, destinationFolder);
// Delete from memory fs to keep updated.
this.fs.delete(`${destinationFolder}/**`);
try {
if (statSync(destinationFolder).isDirectory()) {
this.log.info(`Removing legacy folder ${relativePath}`);
rmSync(destinationFolder, { recursive: true });
}
} catch {
this.log.log(`Could not remove folder ${destinationFolder}`);
}
}
/**
* Fetch files from the generator-jhipster instance installed
*/
fetchFromInstalledJHipster(...path: string[]) {
if (path) {
return joinPath(__dirname, '..', ...path);
}
return path;
}
/**
* Utility function to write file.
*
* @param source
* @param destination - destination
* @param data - template data
* @param options - options passed to ejs render
* @param copyOptions
*/
writeFile(source: string, destination: string, data: TemplateData = this, options?: TemplateOptions, copyOptions: CopyOptions = {}) {
// Convert to any because ejs types doesn't support string[] https://github.com/DefinitelyTyped/DefinitelyTyped/pull/63315
const root: any = this.jhipsterTemplatesFolders ?? this.templatePath();
try {
return this.renderTemplate(source, destination, data, { root, ...options }, { noGlob: true, ...copyOptions });
} catch (error) {
throw new Error(`Error writing file ${source} to ${destination}: ${error}`, { cause: error });
}
}
/**
* write the given files using provided options.
*/
async writeFiles<DataType = any>(options: WriteFileOptions<DataType, this>): Promise<string[]> {
const paramCount = Object.keys(options).filter(key => ['sections', 'blocks', 'templates'].includes(key)).length;
assert(paramCount > 0, 'One of sections, blocks or templates is required');
assert(paramCount === 1, 'Only one of sections, blocks or templates must be provided');
const { sections, blocks, context = this, templates } = options as any;
const { rootTemplatesPath, customizeTemplatePath = file => file, transform: methodTransform = [] } = options;
const { _: commonSpec = {} } = sections || {};
const { transform: sectionTransform = [] } = commonSpec;
const startTime = new Date().getMilliseconds();
const { customizeTemplatePaths: contextCustomizeTemplatePaths = [] } = context as BaseApplication;
const templateData = this.jhipster7Migration
? createJHipster7Context(this, context, { log: this.jhipster7Migration === 'verbose' ? msg => this.log.info(msg) : () => {} })
: context;
/* Build lookup order first has preference.
* Example
* rootTemplatesPath = ['reactive', 'common']
* jhipsterTemplatesFolders = ['/.../generator-jhispter-blueprint/server/templates', '/.../generator-jhispter/server/templates']
*
* /.../generator-jhispter-blueprint/server/templates/reactive/templatePath
* /.../generator-jhispter-blueprint/server/templates/common/templatePath
* /.../generator-jhispter/server/templates/reactive/templatePath
* /.../generator-jhispter/server/templates/common/templatePath
*/
let rootTemplatesAbsolutePath;
if (!rootTemplatesPath) {
rootTemplatesAbsolutePath = (this as any).jhipsterTemplatesFolders;
} else if (typeof rootTemplatesPath === 'string' && isAbsolute(rootTemplatesPath)) {
rootTemplatesAbsolutePath = rootTemplatesPath;
} else {
rootTemplatesAbsolutePath = (this as any).jhipsterTemplatesFolders
.map(templateFolder => ([] as string[]).concat(rootTemplatesPath).map(relativePath => join(templateFolder, relativePath)))
.flat();
}
const normalizeEjs = file => file.replace('.ejs', '');
const resolveCallback = (maybeCallback, fallback?) => {
if (maybeCallback === undefined) {
if (typeof fallback === 'function') {
return resolveCallback(fallback);
}
return fallback;
}
if (typeof maybeCallback === 'boolean' || typeof maybeCallback === 'string') {
return maybeCallback;
}
if (typeof maybeCallback === 'function') {
return (maybeCallback as any).call(this, templateData) || false;
}
throw new Error(`Type not supported ${maybeCallback}`);
};
const renderTemplate = async ({ condition, sourceFile, destinationFile, options, noEjs, transform, binary }) => {
if (condition !== undefined && !resolveCallback(condition, true)) {
return undefined;
}
const extension = extname(sourceFile);
const isBinary = binary || ['.png', '.jpg', '.gif', '.svg', '.ico'].includes(extension);
const appendEjs = noEjs === undefined ? !isBinary && extension !== '.ejs' : !noEjs;
let targetFile;
if (typeof destinationFile === 'function') {
targetFile = resolveCallback(destinationFile);
} else {
targetFile = appendEjs ? normalizeEjs(destinationFile) : destinationFile;
}
let sourceFileFrom;
if (Array.isArray(rootTemplatesAbsolutePath)) {
// Look for existing templates
let existingTemplates = rootTemplatesAbsolutePath
.map(rootPath => this.templatePath(rootPath, sourceFile))
.filter(templateFile => existsSync(appendEjs ? `${templateFile}.ejs` : templateFile));
if (existingTemplates.length === 0 && this.getFeatures().jhipster7Migration) {
existingTemplates = rootTemplatesAbsolutePath
.map(rootPath => this.templatePath(rootPath, appendEjs ? sourceFile : `${sourceFile}.ejs`))
.filter(templateFile => existsSync(templateFile));
}
if (existingTemplates.length > 1) {
const moreThanOneMessage = `Multiples templates were found for file ${sourceFile}, using the first
templates: ${JSON.stringify(existingTemplates, null, 2)}`;
if (existingTemplates.length > 2) {
this.log.warn(`Possible blueprint conflict detected: ${moreThanOneMessage}`);
} else {
this.log.debug(moreThanOneMessage);
}
}
sourceFileFrom = existingTemplates.shift();
} else if (typeof rootTemplatesAbsolutePath === 'string') {
sourceFileFrom = this.templatePath(rootTemplatesAbsolutePath, sourceFile);
} else {
sourceFileFrom = this.templatePath(sourceFile);
}
const file = customizeTemplatePath.call(this, { sourceFile, resolvedSourceFile: sourceFileFrom, destinationFile: targetFile });
if (!file) {
return undefined;
}
sourceFileFrom = file.resolvedSourceFile;
targetFile = file.destinationFile;
let templatesRoots: string[] = [].concat(rootTemplatesAbsolutePath);
for (const contextCustomizeTemplatePath of contextCustomizeTemplatePaths) {
const file = contextCustomizeTemplatePath.call(
this,
{
namespace: this.options.namespace,
sourceFile,
resolvedSourceFile: sourceFileFrom,
destinationFile: targetFile,
templatesRoots,
},
context,
);
if (!file) {
return undefined;
}
sourceFileFrom = file.resolvedSourceFile;
targetFile = file.destinationFile;
templatesRoots = file.templatesRoots;
}
if (sourceFileFrom === undefined) {
throw new Error(`Template file ${sourceFile} was not found at ${rootTemplatesAbsolutePath}`);
}
try {
if (!appendEjs && extname(sourceFileFrom) !== '.ejs') {
await (this as any).copyTemplateAsync(sourceFileFrom, targetFile);
} else {
let useAsync = true;
if (context.entityClass) {
if (!context.baseName) {
throw new Error('baseName is required at templates context');
}
const sourceBasename = basename(sourceFileFrom);
const seed = `${context.entityClass}-${sourceBasename}${context.fakerSeed ?? ''}`;
Object.values((this.sharedData as any).getApplication()?.sharedEntities ?? {}).forEach((entity: any) => {
entity.resetFakerSeed(seed);
});
// Async calls will make the render method to be scheduled, allowing the faker key to change in the meantime.
useAsync = false;
}
const renderOptions = {
...(options?.renderOptions ?? {}),
// Set root for ejs to lookup for partials.
root: templatesRoots,
// ejs caching cause problem https://github.com/jhipster/generator-jhipster/pull/20757
cache: false,
};
const copyOptions = { noGlob: true };
if (appendEjs) {
sourceFileFrom = `${sourceFileFrom}.ejs`;
}
if (useAsync) {
await (this as any).renderTemplateAsync(sourceFileFrom, targetFile, templateData, renderOptions, copyOptions);
} else {
(this as any).renderTemplate(sourceFileFrom, targetFile, templateData, renderOptions, copyOptions);
}
}
} catch (error) {
throw new Error(`Error rendering template ${sourceFileFrom} to ${targetFile}: ${error}`, { cause: error });
}
if (!isBinary && transform?.length) {
this.editFile(targetFile, ...transform);
}
return targetFile;
};
let parsedBlocks = blocks;
if (sections) {
assert(typeof sections === 'object', 'sections must be an object');
const parsedSections = Object.entries(sections)
.map(([sectionName, sectionBlocks]) => {