-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathblueprint.js
1484 lines (1246 loc) · 38.1 KB
/
blueprint.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';
/**
@module ember-cli
*/
var FileInfo = require('./file-info');
var Promise = require('../ext/promise');
var chalk = require('chalk');
var printableProperties = require('../utilities/printable-properties').blueprint;
var sequence = require('../utilities/sequence');
var printCommand = require('../utilities/print-command');
var fs = require('fs-extra');
var inflector = require('inflection');
var minimatch = require('minimatch');
var path = require('path');
var stat = Promise.denodeify(fs.stat);
var stringUtils = require('ember-cli-string-utils');
var compact = require('lodash/compact');
var intersect = require('lodash/intersection');
var uniq = require('lodash/uniq');
var zipObject = require('lodash/zipObject');
var includes = require('lodash/includes');
var any = require('lodash/some');
var cloneDeep = require('lodash/cloneDeep');
var keys = require('lodash/keys');
var merge = require('lodash/merge');
var values = require('lodash/values');
var walkSync = require('walk-sync');
var writeFile = Promise.denodeify(fs.outputFile);
var removeFile = Promise.denodeify(fs.remove);
var SilentError = require('silent-error');
var CoreObject = require('../ext/core-object');
var EOL = require('os').EOL;
var debug = require('debug')('ember-cli:blueprint');
var normalizeEntityName = require('ember-cli-normalize-entity-name');
function existsSync(path) {
try {
fs.accessSync(path);
return true;
}
catch (e) {
return false;
}
}
module.exports = Blueprint;
/**
A blueprint is a bundle of template files with optional install
logic.
Blueprints follow a simple structure. Let's take the built-in
`controller` blueprint as an example:
```
blueprints/controller
├── files
│ ├── app
│ │ └── __path__
│ │ └── __name__.js
└── index.js
blueprints/controller-test
├── files
│ └── tests
│ └── unit
│ └── controllers
│ └── __test__.js
└── index.js
```
## Files
`files` contains templates for the all the files to be
installed into the target directory.
The `__name__` token is subtituted with the dasherized
entity name at install time. For example, when the user
invokes `ember generate controller foo` then `__name__` becomes
`foo`. When the `--pod` flag is used, for example `ember
generate controller foo --pod` then `__name__` becomes
`controller`.
The `__path__` token is substituted with the blueprint
name at install time. For example, when the user invokes
`ember generate controller foo` then `__path__` becomes
`controller`. When the `--pod` flag is used, for example
`ember generate controller foo --pod` then `__path__`
becomes `foo` (or `<podModulePrefix>/foo` if the
podModulePrefix is defined). This token is primarily for
pod support, and is only necessary if the blueprint can be
used in pod structure. If the blueprint does not require pod
support, simply use the blueprint name instead of the
`__path__` token.
The `__test__` token is substituted with the dasherized
entity name and appended with `-test` at install time.
This token is primarily for pod support and only necessary
if the blueprint requires support for a pod structure. If
the blueprint does not require pod support, simply use the
`__name__` token instead.
## Template Variables (AKA Locals)
Variables can be inserted into templates with
`<%= someVariableName %>`.
For example, the built-in `util` blueprint
`files/app/utils/__name__.js` looks like this:
```js
export default function <%= camelizedModuleName %>() {
return true;
}
```
`<%= camelizedModuleName %>` is replaced with the real
value at install time.
The following template variables are provided by default:
- `dasherizedPackageName`
- `classifiedPackageName`
- `dasherizedModuleName`
- `classifiedModuleName`
- `camelizedModuleName`
`packageName` is the project name as found in the project's
`package.json`.
`moduleName` is the name of the entity being generated.
The mechanism for providing custom template variables is
described below.
## Index.js
Custom installation and uninstallation behaviour can be added
by overriding the hooks documented below. `index.js` should
export a plain object, which will extend the prototype of the
`Blueprint` class. If needed, the original `Blueprint` prototype
can be accessed through the `_super` property.
```js
module.exports = {
locals: function(options) {
// Return custom template variables here.
return {};
},
normalizeEntityName: function(entityName) {
// Normalize and validate entity name here.
return entityName;
},
fileMapTokens: function(options) (
// Return custom tokens to be replaced in your files
return {
__token__: function(options){
// logic to determine value goes here
return 'value';
}
}
},
filesPath: function(options) {
return path.join(this.path, 'files');
},
beforeInstall: function(options) {},
afterInstall: function(options) {},
beforeUninstall: function(options) {},
afterUninstall: function(options) {}
};
```
## Blueprint Hooks
As shown above, the following hooks are available to
blueprint authors:
- `locals`
- `normalizeEntityName`
- `fileMapTokens`
- `filesPath`
- `beforeInstall`
- `afterInstall`
- `beforeUninstall`
- `afterUninstall`
### locals
Use `locals` to add custom tempate variables. The method
receives one argument: `options`. Options is an object
containing general and entity-specific options.
When the following is called on the command line:
```sh
ember generate controller foo --type=array --dry-run
```
The object passed to `locals` looks like this:
```js
{
entity: {
name: 'foo',
options: {
type: 'array'
}
},
dryRun: true
}
```
This hook must return an object or a Promise which resolves to an object.
The resolved object will be merged with the aforementioned default locals.
### normalizeEntityName
Use the `normalizeEntityName` hook to add custom normalization and
validation of the provided entity name. The default hook does not
make any changes to the entity name, but makes sure an entity name
is present and that it doesn't have a trailing slash.
This hook receives the entity name as its first argument. The string
returned by this hook will be used as the new entity name.
### fileMapTokens
Use `fileMapTokens` to add custom fileMap tokens for use
in the `mapFile` method. The hook must return an object in the
following pattern:
```js
{
__token__: function(options){
// logic to determine value goes here
return 'value';
}
}
```
It will be merged with the default `fileMapTokens`, and can be used
to override any of the default tokens.
Tokens are used in the files folder (see `files`), and get replaced with
values when the `mapFile` method is called.
### filesPath
Use `filesPath` to define where the blueprint files to install are located.
This can be used to customize which set of files to install based on options
or environmental variables. It defaults to the `files` directory within the
blueprint's folder.
### beforeInstall & beforeUninstall
Called before any of the template files are processed and receives
the the `options` and `locals` hashes as parameters. Typically used for
validating any additional command line options or for any asynchronous
setup that is needed. As an example, the `controller` blueprint validates
its `--type` option in this hook. If you need to run any asynchronous code,
wrap it in a promise and return that promise from these hooks. This will
ensure that your code is executed correctly.
### afterInstall & afterUninstall
The `afterInstall` and `afterUninstall` hooks receives the same
arguments as `locals`. Use it to perform any custom work after the
files are processed. For example, the built-in `route` blueprint
uses these hooks to add and remove relevant route declarations in
`app/router.js`.
### Overriding Install
If you don't want your blueprint to install the contents of
`files` you can override the `install` method. It receives the
same `options` object described above and must return a promise.
See the built-in `resource` blueprint for an example of this.
@class Blueprint
@constructor
@extends CoreObject
@param {String} [blueprintPath]
*/
function Blueprint(blueprintPath) {
this.path = blueprintPath;
this.name = path.basename(blueprintPath);
}
Blueprint.__proto__ = CoreObject;
Blueprint.prototype.constructor = Blueprint;
Blueprint.prototype.availableOptions = [];
Blueprint.prototype.anonymousOptions = ['name'];
/**
Hook to specify the path to the blueprint's files. By default this is
`path.join(this.path, 'files)`.
@method filesPath
@param {Object} options
@return {String} Path to the blueprints files directory.
*/
Blueprint.prototype.filesPath = function() {
return path.join(this.path, 'files');
};
/**
Used to retrieve files for blueprint. The `file` param is an
optional string that is turned into a glob.
@method files
@return {Array} Contents of the blueprint's files directory
*/
Blueprint.prototype.files = function() {
if (this._files) { return this._files; }
var filesPath = this.filesPath(this.options);
if (existsSync(filesPath)) {
this._files = walkSync(filesPath);
} else {
this._files = [];
}
return this._files;
};
/**
@method srcPath
@param {String} file
@return {String} Resolved path to the file
*/
Blueprint.prototype.srcPath = function(file) {
return path.resolve(this.filesPath(this.options), file);
};
/**
Hook for normalizing entity name
@method normalizeEntityName
@param {String} entityName
@return {null}
*/
Blueprint.prototype.normalizeEntityName = function(entityName) {
return normalizeEntityName(entityName);
};
/**
Write a status and message to the UI
@private
@method _writeStatusToUI
@param {Function} chalkColor
@param {String} keyword
@param {String} message
*/
Blueprint.prototype._writeStatusToUI = function(chalkColor, keyword, message) {
if (this.ui) {
this.ui.writeLine(' ' + chalkColor(keyword) + ' ' + message);
}
};
/**
@private
@method _writeFile
@param {Object} info
@return {Promise}
*/
Blueprint.prototype._writeFile = function(info) {
if (!this.dryRun) {
return writeFile(info.outputPath, info.render());
}
};
/**
Actions lookup
@private
*/
Blueprint.prototype._actions = {
write: function(info) {
this._writeStatusToUI(chalk.green, 'create', info.displayPath);
return this._writeFile(info);
},
skip: function(info) {
var label = 'skip';
if (info.resolution === 'identical') {
label = 'identical';
}
this._writeStatusToUI(chalk.yellow, label, info.displayPath);
},
overwrite: function(info) {
this._writeStatusToUI(chalk.yellow, 'overwrite', info.displayPath);
return this._writeFile(info);
},
edit: function(info) {
this._writeStatusToUI(chalk.green, 'edited', info.displayPath);
},
remove: function(info) {
this._writeStatusToUI(chalk.red, 'remove', info.displayPath);
if (!this.dryRun) {
return removeFile(info.outputPath);
}
}
};
/**
Calls an action.
@private
@method _commit
@param {Object} result
@return {Promise}
@throws {Error} Action doesn't exist.
*/
Blueprint.prototype._commit = function(result) {
var action = this._actions[result.action];
if (action) {
return action.call(this, result);
} else {
throw new Error('Tried to call action \"' + result.action + '\" but it does not exist');
}
};
/**
Prints warning for pod unsupported.
@private
@method _checkForPod
*/
Blueprint.prototype._checkForPod = function(verbose) {
if (!this.hasPathToken && this.pod && verbose) {
this.ui.writeLine(chalk.yellow('You specified the pod flag, but this' +
' blueprint does not support pod structure. It will be generated with' +
' the default structure.'));
}
};
/**
@private
@method _normalizeEntityName
@param {Object} entity
*/
Blueprint.prototype._normalizeEntityName = function(entity) {
if (entity) {
entity.name = this.normalizeEntityName(entity.name);
}
};
/**
@private
@method _checkInRepoAddonExists
@param {String} inRepoAddon
*/
Blueprint.prototype._checkInRepoAddonExists = function(inRepoAddon) {
if (inRepoAddon) {
if (!inRepoAddonExists(inRepoAddon, this.project.root)) {
throw new SilentError('You specified the in-repo-addon flag, but the' +
' in-repo-addon \'' + inRepoAddon + '\' does not exist. Please' +
' check the name and try again.');
}
}
};
/**
@private
@method _process
@param {Object} options
@param {Function} beforeHook
@param {Function} process
@param {Function} afterHook
*/
Blueprint.prototype._process = function(options, beforeHook, process, afterHook) {
var self = this;
var intoDir = options.target;
return this._locals(options).then(function (locals) {
return Promise.resolve()
.then(beforeHook.bind(self, options, locals))
.then(process.bind(self, intoDir, locals)).map(self._commit.bind(self))
.then(afterHook.bind(self, options));
});
};
/**
@method install
@param {Object} options
@return {Promise}
*/
Blueprint.prototype.install = function(options) {
var ui = this.ui = options.ui;
var dryRun = this.dryRun = options.dryRun;
this.project = options.project;
this.pod = options.pod;
this.options = options;
this.hasPathToken = hasPathToken(this.files());
podDeprecations(this.project.config(), ui);
ui.writeLine('installing ' + this.name);
if (dryRun) {
ui.writeLine(chalk.yellow('You specified the dry-run flag, so no' +
' changes will be written.'));
}
this._normalizeEntityName(options.entity);
this._checkForPod(options.verbose);
this._checkInRepoAddonExists(options.inRepoAddon);
debug('START: processing blueprint: `%s`', this.name);
var start = new Date();
return this._process(
options,
this.beforeInstall,
this.processFiles,
this.afterInstall).finally(function() {
debug('END: processing blueprint: `%s` in (%dms)', this.name, new Date() - start);
}.bind(this));
};
/**
@method uninstall
@param {Object} options
@return {Promise}
*/
Blueprint.prototype.uninstall = function(options) {
var ui = this.ui = options.ui;
var dryRun = this.dryRun = options.dryRun;
this.project = options.project;
this.pod = options.pod;
this.options = options;
this.hasPathToken = hasPathToken(this.files());
podDeprecations(this.project.config(), ui);
ui.writeLine('uninstalling ' + this.name);
if (dryRun) {
ui.writeLine(chalk.yellow('You specified the dry-run flag, so no' +
' files will be deleted.'));
}
this._normalizeEntityName(options.entity);
this._checkForPod(options.verbose);
return this._process(
options,
this.beforeUninstall,
this.processFilesForUninstall,
this.afterUninstall);
};
/**
Hook for running operations before install.
@method beforeInstall
@return {Promise|null}
*/
Blueprint.prototype.beforeInstall = function() {};
/**
Hook for running operations after install.
@method afterInstall
@return {Promise|null}
*/
Blueprint.prototype.afterInstall = function() {};
/**
Hook for running operations before uninstall.
@method beforeUninstall
@return {Promise|null}
*/
Blueprint.prototype.beforeUninstall = function() {};
/**
Hook for running operations after uninstall.
@method afterUninstall
@return {Promise|null}
*/
Blueprint.prototype.afterUninstall = function() {};
/**
Hook for adding additional locals
@method locals
@return {Object|null}
*/
Blueprint.prototype.locals = function() {};
/**
Hook to add additional or override existing fileMapTokens.
@method fileMapTokens
@return {Object|null}
*/
Blueprint.prototype.fileMapTokens = function() {
};
/**
@private
@method _fileMapTokens
@param {Object} options
@return {Object}
*/
Blueprint.prototype._fileMapTokens = function(options) {
var standardTokens = {
__name__: function(options) {
if (options.pod && options.hasPathToken) {
return options.blueprintName;
}
return options.dasherizedModuleName;
},
__path__: function(options) {
var blueprintName = options.blueprintName;
if (blueprintName.match(/-test/)) {
blueprintName = options.blueprintName.slice(0, options.blueprintName.indexOf('-test'));
}
if (options.pod && options.hasPathToken) {
return path.join(options.podPath, options.dasherizedModuleName);
}
return inflector.pluralize(blueprintName);
},
__root__: function(options) {
if (options.inRepoAddon) {
return path.join('lib',options.inRepoAddon, 'addon');
}
if (options.inDummy) {
return path.join('tests','dummy','app');
}
if (options.inAddon) {
return 'addon';
}
return 'app';
},
__test__: function(options) {
if (options.pod && options.hasPathToken) {
return options.blueprintName;
}
return options.dasherizedModuleName + '-test';
}
};
var customTokens = this.fileMapTokens(options) || options.fileMapTokens || {};
return merge(standardTokens, customTokens);
};
/**
Used to generate fileMap tokens for mapFile.
@method generateFileMap
@param {Object} fileMapVariables
@return {Object}
*/
Blueprint.prototype.generateFileMap = function(fileMapVariables) {
var tokens = this._fileMapTokens(fileMapVariables);
var fileMapValues = values(tokens);
var tokenValues = fileMapValues.map(function(token) { return token(fileMapVariables); });
var tokenKeys = keys(tokens);
return zipObject(tokenKeys,tokenValues);
};
/**
@method buildFileInfo
@param {Function} destPath
@param {Object} templateVariables
@param {String} file
@return {FileInfo}
*/
Blueprint.prototype.buildFileInfo = function(destPath, templateVariables, file) {
var mappedPath = this.mapFile(file, templateVariables);
return new FileInfo({
action: 'write',
outputPath: destPath(mappedPath),
displayPath: path.normalize(mappedPath),
inputPath: this.srcPath(file),
templateVariables: templateVariables,
ui: this.ui
});
};
/**
@method isUpdate
@return {Boolean}
*/
Blueprint.prototype.isUpdate = function() {
if (this.project && this.project.isEmberCLIProject) {
return this.project.isEmberCLIProject();
}
};
/**
@private
@method _getFileInfos
@param {Array} files
@param {String} intoDir
@param {Object} templateVariables
@return {Array} file infos
*/
Blueprint.prototype._getFileInfos = function(files, intoDir, templateVariables) {
return files.map(this.buildFileInfo.bind(this, destPath.bind(null, intoDir), templateVariables));
};
/**
Add update files to ignored files
@private
@method _ignoreUpdateFiles
*/
Blueprint.prototype._ignoreUpdateFiles = function() {
if (this.isUpdate()) {
Blueprint.ignoredFiles = Blueprint.ignoredFiles.concat(Blueprint.ignoredUpdateFiles);
}
};
/**
@private
@method _getFilesForInstall
@param {Array} targetFiles
@return {Array} files
*/
Blueprint.prototype._getFilesForInstall = function(targetFiles) {
var files = this.files();
// if we've defined targetFiles, get file info on ones that match
return targetFiles && targetFiles.length > 0 && intersect(files, targetFiles) || files;
};
/**
@private
@method _checkForNoMatch
@param {Array} fileInfos
@param {String} rawArgs
*/
Blueprint.prototype._checkForNoMatch = function(fileInfos, rawArgs) {
if (fileInfos.filter(isFilePath).length < 1 && rawArgs) {
this.ui.writeLine(chalk.yellow('The globPattern \"' + rawArgs +
'\" did not match any files, so no file updates will be made.'));
}
};
function finishProcessingForInstall(infos) {
infos.forEach(markIdenticalToBeSkipped);
var infosNeedingConfirmation = infos.reduce(gatherConfirmationMessages, []);
return sequence(infosNeedingConfirmation).returns(infos);
}
function finishProcessingForUninstall(infos) {
infos.forEach(markToBeRemoved);
return infos;
}
/**
@method processFiles
@param {String} intoDir
@param {Object} templateVariables
*/
Blueprint.prototype.processFiles = function(intoDir, templateVariables) {
var files = this._getFilesForInstall(templateVariables.targetFiles);
var fileInfos = this._getFileInfos(files, intoDir, templateVariables);
this._checkForNoMatch(fileInfos, templateVariables.rawArgs);
this._ignoreUpdateFiles();
return Promise.filter(fileInfos, isValidFile).
map(prepareConfirm).
then(finishProcessingForInstall);
};
/**
@method processFilesForUninstall
@param {String} intoDir
@param {Object} templateVariables
*/
Blueprint.prototype.processFilesForUninstall = function(intoDir, templateVariables) {
var fileInfos = this._getFileInfos(this.files(), intoDir, templateVariables);
this._ignoreUpdateFiles();
return Promise.filter(fileInfos, isValidFile).
then(finishProcessingForUninstall);
};
/**
@method mapFile
@param {String} file
@return {String}
*/
Blueprint.prototype.mapFile = function(file, locals) {
var pattern, i;
var fileMap = locals.fileMap || { __name__: locals.dasherizedModuleName };
file = Blueprint.renamedFiles[file] || file;
for (i in fileMap) {
pattern = new RegExp(i, 'g');
file = file.replace(pattern, fileMap[i]);
}
return file;
};
/**
Looks for a __root__ token in the files folder. Must be present for
the blueprint to support addon tokens. The `server`, `blueprints`, and `test`
@private
@method supportsAddon
@return {Boolean}
*/
Blueprint.prototype.supportsAddon = function() {
return this.files().join().match(/__root__/);
};
/**
@private
@method _generateFileMapVariables
@param {Object} options
@return {Object}
*/
Blueprint.prototype._generateFileMapVariables = function(moduleName, locals, options) {
var originBlueprintName = options.originBlueprintName || this.name;
var podModulePrefix = this.project.config().podModulePrefix || '';
var podPath = podModulePrefix.substr(podModulePrefix.lastIndexOf('/') + 1);
var inAddon = this.project.isEmberCLIAddon() || !!options.inRepoAddon;
var inDummy = this.project.isEmberCLIAddon() ? options.dummy : false;
return {
pod: this.pod,
podPath: podPath,
hasPathToken: this.hasPathToken,
inAddon: inAddon,
inRepoAddon: options.inRepoAddon,
inDummy: inDummy,
blueprintName: this.name,
originBlueprintName: originBlueprintName,
dasherizedModuleName: stringUtils.dasherize(moduleName),
locals: locals
};
};
/**
@private
@method _locals
@param {Object} options
@return {Object}
*/
Blueprint.prototype._locals = function(options) {
var packageName = options.project.name();
var moduleName = options.entity && options.entity.name || packageName;
var sanitizedModuleName = moduleName.replace(/\//g, '-');
return new Promise(function(resolve) {
resolve(this.locals(options));
}.bind(this)).then(function (customLocals) {
var fileMapVariables = this._generateFileMapVariables(moduleName, customLocals, options);
var fileMap = this.generateFileMap(fileMapVariables);
var standardLocals = {
dasherizedPackageName: stringUtils.dasherize(packageName),
classifiedPackageName: stringUtils.classify(packageName),
dasherizedModuleName: stringUtils.dasherize(moduleName),
classifiedModuleName: stringUtils.classify(sanitizedModuleName),
camelizedModuleName: stringUtils.camelize(sanitizedModuleName),
decamelizedModuleName: stringUtils.decamelize(sanitizedModuleName),
fileMap: fileMap,
hasPathToken: this.hasPathToken,
targetFiles: options.targetFiles,
rawArgs: options.rawArgs
};
return merge({}, standardLocals, customLocals);
}.bind(this));
};
/**
Used to add a package to the project's `package.json`.
Generally, this would be done from the `afterInstall` hook, to
ensure that a package that is required by a given blueprint is
available.
@method addPackageToProject
@param {String} packageName
@param {String} target
@return {Promise}
*/
Blueprint.prototype.addPackageToProject = function(packageName, target) {
var packageObject = {name: packageName};
if (target) {
packageObject.target = target;
}
return this.addPackagesToProject([packageObject]);
};
/**
Used to add multiple packages to the project's `package.json`.
Generally, this would be done from the `afterInstall` hook, to
ensure that a package that is required by a given blueprint is
available.
Expects each array item to be an object with a `name`. Each object
may optionally have a `target` to specify a specific version.
@method addPackagesToProject
@param {Array} packages
@return {Promise}
*/
Blueprint.prototype.addPackagesToProject = function(packages) {
var task = this.taskFor('npm-install');
var installText = (packages.length > 1) ? 'install packages' : 'install package';
var packageNames = [];
var packageArray = [];
for (var i = 0; i < packages.length; i++) {
packageNames.push(packages[i].name);
var packageNameAndVersion = packages[i].name;
if (packages[i].target) {
packageNameAndVersion += '@' + packages[i].target;
}
packageArray.push(packageNameAndVersion);
}
this._writeStatusToUI(chalk.green, installText, packageNames.join(', '));
return task.run({
'save-dev': true,
verbose: false,
packages: packageArray
});
};
/**
Used to remove a package from the project's `package.json`.
Generally, this would be done from the `afterInstall` hook, to
ensure that any package conflicts can be resolved before the
addon is used.
@method removePackageFromProject
@param {String} packageName
@return {Promise}
*/
Blueprint.prototype.removePackageFromProject = function(packageName) {
var packageObject = {name: packageName};
return this.removePackagesFromProject([packageObject]);
};
/**
Used to remove multiple packages from the project's `package.json`.
Generally, this would be done from the `afterInstall` hook, to
ensure that any package conflicts can be resolved before the
addon is used.
Expects each array item to be an object with a `name` property.
@method removePackagesFromProject
@param {Array} packages
@return {Promise}
*/
Blueprint.prototype.removePackagesFromProject = function(packages) {
var task = this.taskFor('npm-uninstall');
var installText = (packages.length > 1) ? 'uninstall packages' : 'uninstall package';
var packageNames = [];
var packageArray = [];
for (var i = 0; i < packages.length; i++) {
packageNames.push(packages[i].name);
var packageNameAndVersion = packages[i].name;
packageArray.push(packageNameAndVersion);
}
this._writeStatusToUI(chalk.green, installText, packageNames.join(', '));
return task.run({
'save-dev': true,
verbose: false,
packages: packageArray
});
};
/**
Used to retrieve a task with the given name. Passes the new task
the standard information available (like `ui`, `analytics`, `project`, etc).