-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
index.js
1114 lines (961 loc) · 34 KB
/
index.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
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const EventEmitter = require('events');
const assert = require('assert');
const _ = require('lodash');
const findUp = require('find-up');
const readPkgUp = require('read-pkg-up');
const chalk = require('chalk');
const makeDir = require('make-dir');
const minimist = require('minimist');
const runAsync = require('run-async');
const through = require('through2');
const FileEditor = require('mem-fs-editor');
const createDebug = require('debug');
const SubQueue = require('grouped-queue/lib/subqueue');
const Environment = require('yeoman-environment');
const Conflicter = require('./util/conflicter');
const Storage = require('./util/storage');
const promptSuggestion = require('./util/prompt-suggestion');
const EMPTY = '@@_YEOMAN_EMPTY_MARKER_@@';
const debug = createDebug('yeoman:generator');
// Ensure a prototype method is a candidate run by default
const methodIsValid = function(name) {
return name.charAt(0) !== '_' && name !== 'constructor';
};
/**
* Queue options.
* @typedef {Object} QueueOptions
* @property {string} [queueName] - Name of the queue.
* @property {boolean} [once] - Execute only once by namespace and taskName.
* @property {boolean} [run] - Run the queue if not running yet.
*/
/**
* Task options.
* @typedef {QueueOptions} TaskOptions
* @property {Function} [reject] - Reject callback.
*/
/**
* Priority object.
* @typedef {QueueOptions} Priority
* @property {string} priorityName - Name of the priority.
* @property {string} [before] - The queue which this priority should be added before.
*/
/**
* Complete Task object.
* @typedef {TaskOptions} Task
* @property {WrappedMethod} method - Function to be queued.
* @property {string} taskName - Name of the task.
*/
/**
* RunAsync creates a promise and executes wrappedMethod inside the promise.
* It replaces async property of the wrappedMethod's context with one RunAsync provides.
* async() simulates an async function by creating a callback.
*
* It supports promises/async and sync functions.
* - Promises/async: forward resolve/reject from the runAsync promise to the
* promise returned by the wrappedMethod.
* - Sync functions: resolves with the returned value.
* Can be a promise for chaining
* - Sync functions with callback (done = this.async()) calls:
* Reject with done(rejectValue) first argument
* Resolve with done(undefined, resolveValue) second argument
* - Callback must called when 'async()' was called inside a sync function.
* - Callback can be ignored when 'async()' was called inside a async function.
* @typedef {Function} WrappedMethod
*/
class Generator extends EventEmitter {
// If for some reason environment adds more queues, we should use or own for stability.
static get queues() {
return [
'initializing',
'prompting',
'configuring',
'default',
'writing',
'conflicts',
'install',
'end'
];
}
/**
* @classdesc The `Generator` class provides the common API shared by all generators.
* It define options, arguments, file, prompt, log, API, etc.
*
* It mixes into its prototype all the methods found in the `actions/` mixins.
*
* Every generator should extend this base class.
*
* @constructor
* @mixes actions/help
* @mixes actions/install
* @mixes actions/spawn-command
* @mixes actions/user
* @mixes nodejs/EventEmitter
*
* @param {string[]} args - Provide arguments at initialization
* @param {Object} options - Provide options at initialization
* @param {Priority[]} [options.customPriorities] - Custom priorities
*
* @property {Object} env - the current Environment being run
* @property {String} resolved - the path to the current generator
* @property {String} description - Used in `--help` output
* @property {String} appname - The application name
* @property {Storage} config - `.yo-rc` config file manager
* @property {Object} fs - An instance of {@link https://github.com/SBoudrias/mem-fs-editor Mem-fs-editor}
* @property {Function} log - Output content through Interface Adapter
*
* @example
* const Generator = require('yeoman-generator');
* module.exports = class extends Generator {
* writing() {
* this.fs.write(this.destinationPath('index.js'), 'const foo = 1;');
* }
* };
*/
constructor(args, options) {
super();
if (!Array.isArray(args)) {
options = args;
args = [];
}
options = options || {};
this.options = options;
this._initOptions = _.clone(options);
this._args = args || [];
this._options = {};
this._arguments = [];
this._composedWith = [];
this._transformStreams = [];
this.option('help', {
type: Boolean,
alias: 'h',
description: "Print the generator's options and usage"
});
this.option('skip-cache', {
type: Boolean,
description: 'Do not remember prompt answers',
default: false
});
this.option('skip-install', {
type: Boolean,
description: 'Do not automatically install dependencies',
default: false
});
this.option('force-install', {
type: Boolean,
description: 'Fail on install dependencies error',
default: false
});
this.resolved = this.options.resolved || __dirname;
// Make sure we have a full featured environment.
this.env = this.options.env || Environment.createEnv();
if (Object.getPrototypeOf(this.env) === Object.prototype) {
debug('Converting env from a simple object to an Environment');
const env = Environment.createEnv();
Object.assign(env, this.env);
this.env = env;
}
// Ensure the environment support features this yeoman-generator version require.
Environment.enforceUpdate(this.env);
this.description = this.description || '';
this.async = () => () => {};
this.fs = FileEditor.create(this.env.sharedFs);
this.conflicter = new Conflicter(this.env.adapter, this.options.force, {
bail: this.options.bail,
ignoreWhitespace: this.options.whitespace,
skipRegenerate: this.options.skipRegenerate,
dryRun: this.options.dryRun
});
// Mirror the adapter log method on the generator.
//
// example:
// this.log('foo');
// this.log.error('bar');
this.log = this.env.adapter.log;
// Add convenience debug object
this._debug = createDebug(this.options.namespace || 'yeoman:unknownnamespace');
// Determine the app root
this.contextRoot = this.env.cwd;
if (this.options.localConfigOnly) {
debug('Using local configurations only');
} else {
let rootPath = findUp.sync('.yo-rc.json', {
cwd: this.env.cwd
});
rootPath = rootPath ? path.dirname(rootPath) : this.env.cwd;
if (rootPath !== this.env.cwd) {
this.log(
[
'',
'Just found a `.yo-rc.json` in a parent directory.',
'Setting the project root at: ' + rootPath
].join('\n')
);
this.destinationRoot(rootPath);
}
}
this.appname = this.determineAppname();
this.config = this._getStorage();
this._globalConfig = this._getGlobalStorage();
// Ensure source/destination path, can be configured from subclasses
this.sourceRoot(path.join(path.dirname(this.resolved), 'templates'));
// Queues map: generator's queue name => grouped-queue's queue name (custom name)
this._queues = {};
// Add original queues.
Generator.queues.forEach(queue => {
this._queues[queue] = { priorityName: queue, queueName: queue };
});
// Add custom queues
if (Array.isArray(this.options.customPriorities)) {
const customPriorities = this.options.customPriorities.map(customPriority => {
// Keep backward compatibility with name
const newPriority = { priorityName: customPriority.name, ...customPriority };
delete newPriority.name;
return newPriority;
});
// Sort customPriorities, a referenced custom queue must be added before the one that reference it.
customPriorities.sort((a, b) => {
if (a.priorityName === b.priorityName) {
throw new Error(`Duplicate custom queue ${a.name}`);
}
if (a.priorityName === b.before) {
return -1;
}
if (b.priorityName === a.before) {
return 1;
}
return 0;
});
// Add queue to runLoop
customPriorities.forEach(customQueue => {
customQueue.queueName =
customQueue.queueName ||
`${this.options.namespace}#${customQueue.priorityName}`;
debug(`Registering custom queue ${customQueue.queueName}`);
this._queues[customQueue.priorityName] = customQueue;
if (this.env.runLoop.queueNames.includes(customQueue.queueName)) {
return;
}
// Backwards compatibilitiy with grouped-queue < 1.0.0
if (!this.env.runLoop.addSubQueue) {
this.env.runLoop.addSubQueue = function(name, before) {
if (this.__queues__[name]) {
// Sub-queue already exists
return;
}
if (!before) {
// Add at last place.
this.__queues__[name] = new SubQueue();
this.queueNames.push(name);
return;
}
if (!this.__queues__[before] || _.indexOf(this.queueNames, before) === -1) {
throw new Error('sub-queue ' + before + ' not found');
}
const current = this.__queues__;
const currentNames = Object.keys(current);
// Recreate the queue with new order.
this.__queues__ = {};
currentNames.forEach(currentName => {
if (currentName === before) {
this.__queues__[name] = new SubQueue();
}
this.__queues__[currentName] = current[currentName];
});
// Recreate queueNames
this.queueNames = Object.keys(this.__queues__);
};
}
let beforeQueue = customQueue.before
? this._queues[customQueue.before].queueName
: undefined;
this.env.runLoop.addSubQueue(customQueue.queueName, beforeQueue);
});
}
}
/**
* Convenience debug method
*
* @param {any} args parameters to be passed to debug
*/
debug(...args) {
this._debug(...args);
}
/**
* Prompt user to answer questions. The signature of this method is the same as {@link https://github.com/SBoudrias/Inquirer.js Inquirer.js}
*
* On top of the Inquirer.js API, you can provide a `{cache: true}` property for
* every question descriptor. When set to true, Yeoman will store/fetch the
* user's answers as defaults.
*
* @param {array} questions Array of question descriptor objects. See {@link https://github.com/SBoudrias/Inquirer.js/blob/master/README.md Documentation}
* @return {Promise} prompt promise
*/
prompt(questions) {
questions = promptSuggestion.prefillQuestions(this._globalConfig, questions);
questions = promptSuggestion.prefillQuestions(this.config, questions);
return this.env.adapter.prompt(questions).then(answers => {
if (!this.options['skip-cache'] && !this.options.skipCache) {
promptSuggestion.storeAnswers(this._globalConfig, questions, answers, false);
promptSuggestion.storeAnswers(this.config, questions, answers, true);
}
return answers;
});
}
/**
* Adds an option to the set of generator expected options, only used to
* generate generator usage. By default, generators get all the cli options
* parsed by nopt as a `this.options` hash object.
*
* @param {String} name - Option name
* @param {Object} config - Option options
* @param {any} config.type - Either Boolean, String or Number
* @param {string} [config.description] - Description for the option
* @param {any} [config.default] - Default value
* @param {any} [config.alias] - Option name alias (example `-h` and --help`)
* @param {any} [config.hide] - Boolean whether to hide from help
* @return {this} This generator
*/
option(name, config) {
config = config || {};
// Alias default to defaults for backward compatibility.
if ('defaults' in config) {
config.default = config.defaults;
}
config.description = config.description || config.desc;
_.defaults(config, {
name,
description: 'Description for ' + name,
type: Boolean,
hide: false
});
// Check whether boolean option is invalid (starts with no-)
const boolOptionRegex = /^no-/;
if (config.type === Boolean && name.match(boolOptionRegex)) {
const simpleName = name.replace(boolOptionRegex, '');
return this.emit(
'error',
new Error(
[
`Option name ${chalk.yellow(name)} cannot start with ${chalk.red('no-')}\n`,
`Option name prefixed by ${chalk.yellow('--no')} are parsed as implicit`,
` boolean. To use ${chalk.yellow('--' + name)} as an option, use\n`,
chalk.cyan(` this.option('${simpleName}', {type: Boolean})`)
].join('')
)
);
}
if (this._options[name] === null || this._options[name] === undefined) {
this._options[name] = config;
}
this.parseOptions();
return this;
}
/**
* Adds an argument to the class and creates an attribute getter for it.
*
* Arguments are different from options in several aspects. The first one
* is how they are parsed from the command line, arguments are retrieved
* based on their position.
*
* Besides, arguments are used inside your code as a property (`this.argument`),
* while options are all kept in a hash (`this.options`).
*
*
* @param {String} name - Argument name
* @param {Object} config - Argument options
* @param {any} config.type - String, Number, Array, or Object
* @param {string} [config.description] - Description for the argument
* @param {boolean} [config.required] - required` Boolean whether it is required
* @param {boolean} [config.optional] - Boolean whether it is optional
* @param {any} [config.default] - Default value for this argument
* @return {this} This generator
*/
argument(name, config) {
config = config || {};
// Alias default to defaults for backward compatibility.
if ('defaults' in config) {
config.default = config.defaults;
}
config.description = config.description || config.desc;
_.defaults(config, {
name,
required: config.default === null || config.default === undefined,
type: String
});
this._arguments.push(config);
this.parseOptions();
return this;
}
parseOptions() {
const minimistDef = {
string: [],
boolean: [],
alias: {},
default: {}
};
_.each(this._options, option => {
if (option.type === Boolean) {
minimistDef.boolean.push(option.name);
if (!('default' in option) && !option.required) {
minimistDef.default[option.name] = EMPTY;
}
} else {
minimistDef.string.push(option.name);
}
if (option.alias) {
minimistDef.alias[option.alias] = option.name;
}
// Only apply default values if we don't already have a value injected from
// the runner
if (option.name in this._initOptions) {
minimistDef.default[option.name] = this._initOptions[option.name];
} else if (option.alias && option.alias in this._initOptions) {
minimistDef.default[option.name] = this._initOptions[option.alias];
} else if ('default' in option) {
minimistDef.default[option.name] = option.default;
}
});
const parsedOpts = minimist(this._args, minimistDef);
// Parse options to the desired type
_.each(parsedOpts, (option, name) => {
// Manually set value as undefined if it should be.
if (option === EMPTY) {
parsedOpts[name] = undefined;
return;
}
if (this._options[name] && option !== undefined) {
parsedOpts[name] = this._options[name].type(option);
}
});
// Parse positional arguments to valid options
this._arguments.forEach((config, index) => {
let value;
if (index >= parsedOpts._.length) {
if (config.name in this._initOptions) {
value = this._initOptions[config.name];
} else if ('default' in config) {
value = config.default;
} else {
return;
}
} else if (config.type === Array) {
value = parsedOpts._.slice(index, parsedOpts._.length);
} else {
value = config.type(parsedOpts._[index]);
}
parsedOpts[config.name] = value;
});
// Make the parsed options available to the instance
Object.assign(this.options, parsedOpts);
this.args = parsedOpts._;
this.arguments = parsedOpts._;
// Make sure required args are all present
this.checkRequiredArgs();
}
checkRequiredArgs() {
// If the help option was provided, we don't want to check for required
// arguments, since we're only going to print the help message anyway.
if (this.options.help) {
return;
}
// Bail early if it's not possible to have a missing required arg
if (this.args.length > this._arguments.length) {
return;
}
this._arguments.forEach((config, position) => {
// If the help option was not provided, check whether the argument was
// required, and whether a value was provided.
if (config.required && position >= this.args.length) {
return this.emit(
'error',
new Error(`Did not provide required argument ${chalk.bold(config.name)}!`)
);
}
});
}
/**
* Schedule methods on a run queue.
*
* @param {Function|Object} method: Method to be scheduled or object with function properties.
* @param {String} [methodName]: Name of the method (task) to be scheduled.
* @param {String} [queueName]: Name of the queue to be scheduled on.
* @param {Function} [reject]: Reject callback.
*/
queueMethod(method, methodName, queueName, reject = () => {}) {
if (typeof queueName === 'function') {
reject = queueName;
queueName = 'default';
} else {
queueName = queueName || 'default';
}
if (!_.isFunction(method)) {
if (typeof methodName === 'function') {
reject = methodName;
methodName = undefined;
}
this.queueTaskGroup(method, {
queueName: methodName,
reject
});
return;
}
this.queueTask({
method,
taskName: methodName,
queueName,
reject
});
}
/**
* Schedule methods on a run queue.
*
* @param {Object} taskGroup: Object containing tasks.
* @param {TaskOptions} [taskOptions]: options.
*/
queueTaskGroup(taskGroup, taskOptions) {
const self = this;
// Run each queue items
_.each(taskGroup, (newMethod, newMethodName) => {
if (!_.isFunction(newMethod) || !methodIsValid(newMethodName)) return;
self.queueTask({
...taskOptions,
method: newMethod,
taskName: newMethodName
});
});
}
/**
* Schedule tasks on a run queue.
*
* @param {Task} task: Task to be queued.
*/
queueTask(task) {
const reject = task.reject || (() => {});
const queueName = task.queueName || 'default';
const methodName = task.taskName;
const method = task.method;
const once = task.once ? methodName : undefined;
const priority = Object.entries(this._queues).find(
([_, opts]) => opts.queueName === queueName
);
const priorityName = priority ? priority[0] : undefined;
const self = this;
let namespace = '';
if (self.options && self.options.namespace) {
namespace = self.options.namespace;
}
debug(`Queueing ${namespace}#${methodName} with options %o`, task);
self.env.runLoop.add(
queueName,
completed => {
debug(`Running ${namespace}#${methodName}`);
self.emit(`method:${methodName}`);
runAsync(function() {
self.async = () => this.async();
self.runningState = { namespace, queueName, methodName };
return method.apply(self, self.args);
})()
.then(function() {
delete self.runningState;
const eventName = `done$${namespace || 'unknownnamespace'}#${methodName}`;
debug(`Emiting event ${eventName}`);
self.env.emit(eventName, {
namespace,
generator: self,
queueName,
priorityName
});
completed();
})
.catch(err => {
debug(`An error occured while running ${namespace}#${methodName}`, err);
delete self.runningState;
// Ensure we emit the error event outside the promise context so it won't be
// swallowed when there's no listeners.
setImmediate(() => {
self.emit('error', err);
reject(err);
});
});
},
{ once, run: task.run }
);
}
/**
* Runs the generator, scheduling prototype methods on a run queue. Method names
* will determine the order each method is run. Methods without special names
* will run in the default queue.
*
* Any method named `constructor` and any methods prefixed by a `_` won't be scheduled.
*
* You can also supply the arguments for the method to be invoked. If none are
* provided, the same values used to initialize the invoker are used to
* initialize the invoked.
*
* @param {Function} [cb] Deprecated: prefer to use the promise interface
* @return {Promise} Resolved once the process finish
*/
run(cb) {
const promise = new Promise((resolve, reject) => {
const self = this;
this._running = true;
this.debug('Generator is starting');
this.emit('run');
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this));
const validMethods = methods.filter(methodIsValid);
if (!validMethods.length) {
this.emit(
'error',
new Error('This Generator is empty. Add at least one method for it to run.')
);
}
this.env.runLoop.once('end', () => {
this.debug('Generator has ended');
this.emit('end');
resolve();
});
function addInQueue(name) {
const property = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(self),
name
);
const item = property.value ? property.value : property.get.call(self);
const priority = self._queues[name];
let taskOptions = { ...priority, reject };
// Name points to a function; run it!
if (typeof item === 'function') {
taskOptions.taskName = name;
taskOptions.method = item;
return self.queueTask(taskOptions);
}
// Not a queue hash; stop
if (!priority) {
return;
}
self.queueTaskGroup(item, taskOptions);
}
validMethods.forEach(addInQueue);
const writeFiles = () => {
this.env.runLoop.add('conflicts', this._writeFiles.bind(this), {
once: 'write memory fs to disk'
});
};
this.env.sharedFs.on('change', writeFiles);
writeFiles();
// Add the default conflicts handling
this.env.runLoop.add('conflicts', done => {
this.conflicter.resolve(err => {
if (err) {
this.emit('error', err);
}
done();
});
});
_.invokeMap(this._composedWith, 'run');
});
// Maintain backward compatibility with the callback function
if (_.isFunction(cb)) {
promise.then(cb, cb);
}
return promise;
}
/**
* Compose this generator with another one.
* @param {String|Object|Array} generator The path to the generator module or an object (see examples)
* @param {Object} [options] The options passed to the Generator
* @param {boolean} [returnNewGenerator] Returns the created generator instead of returning this.
* @return {this|Object} This generator or the composed generator when returnNewGenerator=true
*
* @example <caption>Using a peerDependency generator</caption>
* this.composeWith('bootstrap', { sass: true });
*
* @example <caption>Using a direct dependency generator</caption>
* this.composeWith(require.resolve('generator-bootstrap/app/main.js'), { sass: true });
*
* @example <caption>Passing a Generator class</caption>
* this.composeWith({ Generator: MyGenerator, path: '../generator-bootstrap/app/main.js' }, { sass: true });
*/
composeWith(generator, options, returnNewGenerator = false) {
if (typeof options === 'boolean') {
returnNewGenerator = options;
options = {};
}
const returnCompose = ret => (returnNewGenerator ? ret : this);
let instantiatedGenerator;
if (Array.isArray(generator)) {
const generators = generator.map(gen => this.composeWith(gen, options));
return returnCompose(generators);
}
const instantiate = (Generator, path) => {
if (path === 'unknown') {
Generator.resolved = path;
} else {
Generator.resolved = require.resolve(path);
}
Generator.namespace = this.env.namespace(path);
return this.env.instantiate(Generator, {
options,
arguments: options.arguments
});
};
options = options || {};
// Pass down the default options so they're correctly mirrored down the chain.
options = _.extend(
{
skipInstall: this.options.skipInstall || this.options['skip-install'],
'skip-install': this.options.skipInstall || this.options['skip-install'],
skipCache: this.options.skipCache || this.options['skip-cache'],
'skip-cache': this.options.skipCache || this.options['skip-cache'],
forceInstall: this.options.forceInstall || this.options['force-install'],
'force-install': this.options.forceInstall || this.options['force-install']
},
options
);
if (typeof generator === 'string') {
try {
const GeneratorImport = require(generator); // eslint-disable-line import/no-dynamic-require
const Generator =
typeof GeneratorImport.default === 'function'
? GeneratorImport.default
: GeneratorImport;
instantiatedGenerator = instantiate(Generator, generator);
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
instantiatedGenerator = this.env.create(generator, {
options,
arguments: options.arguments
});
} else {
throw err;
}
}
} else {
assert(
generator.Generator,
`${chalk.red('Missing Generator property')}\n` +
`When passing an object to Generator${chalk.cyan(
'#composeWith'
)} include the generator class to run in the ${chalk.cyan(
'Generator'
)} property\n\n` +
`this.composeWith({\n` +
` ${chalk.yellow('Generator')}: MyGenerator,\n` +
` ...\n` +
`});`
);
assert(
typeof generator.path === 'string',
`${chalk.red('path property is not a string')}\n` +
`When passing an object to Generator${chalk.cyan(
'#composeWith'
)} include the path to the generators files in the ${chalk.cyan(
'path'
)} property\n\n` +
`this.composeWith({\n` +
` ${chalk.yellow('path')}: '../my-generator',\n` +
` ...\n` +
`});`
);
instantiatedGenerator = instantiate(generator.Generator, generator.path);
}
if (!instantiatedGenerator) {
return returnCompose(instantiatedGenerator);
}
if (this._running) {
instantiatedGenerator.run();
} else {
this._composedWith.push(instantiatedGenerator);
}
return returnCompose(instantiatedGenerator);
}
/**
* Determine the root generator name (the one who's extending Generator).
* @return {String} The name of the root generator
*/
rootGeneratorName() {
const pkg = readPkgUp.sync({ cwd: this.resolved }).pkg;
return pkg ? pkg.name : '*';
}
/**
* Determine the root generator version (the one who's extending Generator).
* @return {String} The version of the root generator
*/
rootGeneratorVersion() {
const pkg = readPkgUp.sync({ cwd: this.resolved }).pkg;
return pkg ? pkg.version : '0.0.0';
}
/**
* Return a storage instance.
* @param {String} storePath The path of the json file
* @param {String} [path] The name in which is stored inside the json
* @param {String} [lodashPath] Treat path as an lodash path
* @return {Storage} json storage
*/
createStorage(storePath, path, lodashPath = false) {
storePath = this.destinationPath(storePath);
return new Storage(path, this.fs, storePath, lodashPath);
}
/**
* Return a storage instance.
* @param {String} [rootName] The rootName in which is stored inside .yo-rc.json
* @return {Storage} Generator storage
* @private
*/
_getStorage(rootName = this.rootGeneratorName()) {
const storePath = path.join(this.destinationRoot(), '.yo-rc.json');
return new Storage(rootName, this.fs, storePath);
}
/**
* Setup a globalConfig storage instance.
* @return {Storage} Global config storage
* @private
*/
_getGlobalStorage() {
// When localConfigOnly === true simulate a globalConfig at local dir
const globalStorageDir = this.options.localConfigOnly
? this.destinationRoot()
: os.homedir();
const storePath = path.join(globalStorageDir, '.yo-rc-global.json');
const storeName = `${this.rootGeneratorName()}:${this.rootGeneratorVersion()}`;
return new Storage(storeName, this.fs, storePath);
}
/**
* Change the generator destination root directory.
* This path is used to find storage, when using a file system helper method (like
* `this.write` and `this.copy`)
* @param {String} rootPath new destination root path
* @return {String} destination root path
*/
destinationRoot(rootPath) {
if (typeof rootPath === 'string') {
this._destinationRoot = path.resolve(rootPath);
if (!fs.existsSync(rootPath)) {
makeDir.sync(rootPath);
}
process.chdir(rootPath);
this.env.cwd = rootPath;
// Reset the storage
this.config = this._getStorage();
}
return this._destinationRoot || this.env.cwd;
}
/**
* Change the generator source root directory.
* This path is used by multiples file system methods like (`this.read` and `this.copy`)
* @param {String} rootPath new source root path
* @return {String} source root path
*/
sourceRoot(rootPath) {
if (typeof rootPath === 'string') {
this._sourceRoot = path.resolve(rootPath);
}
return this._sourceRoot;
}
/**
* Join a path to the source root.
* @param {...String} dest - path parts
* @return {String} joined path
*/
templatePath(...dest) {
let filepath = path.join.apply(path, dest);
if (!path.isAbsolute(filepath)) {
filepath = path.join(this.sourceRoot(), filepath);
}