-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathartifact-generator.js
235 lines (214 loc) · 6.84 KB
/
artifact-generator.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
// Copyright IBM Corp. and LoopBack contributors 2017,2020. All Rights Reserved.
// Node module: @loopback/cli
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
const BaseGenerator = require('./base-generator');
const debug = require('./debug')('artifact-generator');
const utils = require('./utils');
const path = require('path');
const chalk = require('chalk');
const g = require('./globalize');
module.exports = class ArtifactGenerator extends BaseGenerator {
// Note: arguments and options should be defined in the constructor.
constructor(args, opts) {
super(args, opts);
// how classes are separated when the output contains more than one
this.classNameSeparator = ', ';
}
_setupGenerator() {
super._setupGenerator();
this.argument('name', {
type: String,
required: false,
description: g.f('Name for the %s', this.artifactInfo.type),
});
}
setOptions() {
// argument validation
const name = this.options.name;
if (name) {
const validationMsg = utils.validateClassName(name);
if (typeof validationMsg === 'string') throw new Error(validationMsg);
}
this.artifactInfo.name = name;
this.artifactInfo.relPath = path.relative(
this.destinationPath(),
this.artifactInfo.outDir,
);
return super.setOptions();
}
promptArtifactName() {
debug('Prompting for artifact name');
if (this.shouldExit()) return false;
if (this.options.name) {
Object.assign(this.artifactInfo, {name: this.options.name});
return;
}
const prompts = [
{
type: 'input',
name: 'name',
// capitalization
message: g.f(
'%s class name:',
utils.toClassName(this.artifactInfo.type),
),
when: this.artifactInfo.name === undefined,
default: this.artifactInfo.defaultName,
validate: utils.validateClassName,
},
];
return this.prompt(prompts).then(props => {
Object.assign(this.artifactInfo, props);
return props;
});
}
/**
* remind user the input might get changed if it contains _ or accented char
**/
promptWarningMsgForName() {
utils.logNamingIssues(this.artifactInfo.name, this.log.bind(this));
}
/**
* Inform user what model/file names will be created
*
* e.g: promptClassFileName('model', 'models', 'MyModel');
* >> Model MyModel will be created in src/models/my-model.model.ts
**/
promptClassFileName(type, typePlural, name) {
this.log(
g.f(
'%s %s will be created in src/%s/%s.%s.ts',
utils.toClassName(type),
chalk.yellow(name),
typePlural,
chalk.yellow(utils.toFileName(name)),
type,
),
);
this.log();
}
scaffold() {
debug('Scaffolding artifact(s)');
if (this.shouldExit()) return false;
// Capitalize class name
this.artifactInfo.name = utils.toClassName(this.artifactInfo.name);
// Copy template files from ./templates
// Renaming of the files should be done in the generator inheriting from this one
this.copyTemplatedFiles(
this.templatePath('**/*'),
this.destinationPath(),
this.artifactInfo,
);
}
async end() {
if (this.shouldExit()) {
await super.end();
return;
}
if (this._isGenerationSuccessful()) {
await this._updateIndexFiles();
const classes = this.artifactInfo.name
.split(this.classNameSeparator)
.map(utils.toClassName);
const classesOutput = classes.join(this.classNameSeparator);
if (
this.artifactInfo.repositoryConfigs &&
this.artifactInfo.repositoryConfigs.repositories.size
) {
const {repositories, datasource, repositoryBaseClass} =
this.artifactInfo.repositoryConfigs;
for (const model of repositories) {
const config = {repositoryBaseClass, datasource, model, name: model};
try {
const {execSync} = require('child_process');
const cmd =
"lb4 repository --config='" + JSON.stringify(config) + "' --yes";
execSync(cmd, {
cwd: process.cwd(),
stdio: ['ignore', 'pipe', 'pipe'],
encoding: 'utf8',
});
} catch (error) {
console.log(error);
}
}
} else {
debug(
'No repository configurations found, skipping repository generation',
);
}
if (
this.artifactInfo.relationConfigs &&
this.artifactInfo.relationConfigs.length
) {
for (const configs of this.artifactInfo.relationConfigs) {
try {
const {execSync} = require('child_process');
const cmd =
"lb4 relation --config='" + JSON.stringify(configs) + "' --yes";
execSync(cmd, {
cwd: process.cwd(),
stdio: ['ignore', 'pipe', 'pipe'],
encoding: 'utf8',
});
} catch (error) {
console.log(error);
}
}
} else {
debug('No relation configurations found, skipping relation generation');
}
// User Output
this.log();
this.log(
g.f(
'%s %s was/were created in %s',
utils.toClassName(this.artifactInfo.type),
chalk.yellow(classesOutput),
this.artifactInfo.relPath,
),
);
this.log();
}
await super.end();
}
/**
* Update the index.ts in this.artifactInfo.outDir. Creates it if it
* doesn't exist.
* this.artifactInfo.outFile is what is exported from the file.
*
* Both those properties must be present for this to happen. Optionally,
* this can be disabled even if the properties are present by setting:
* this.artifactInfo.disableIndexUpdate = true;
*
* Multiple indexes / files can be updated by providing an array of
* index update objects as follows:
* this.artifactInfo.indexesToBeUpdated = [{
* dir: 'directory in which to update index.ts',
* file: 'file to add to index.ts',
* }, {dir: '...', file: '...'}]
*/
async _updateIndexFiles() {
debug(`Indexes to be updated ${this.artifactInfo.indexesToBeUpdated}`);
// Index Update Disabled
if (this.artifactInfo.disableIndexUpdate) return;
if (!this.artifactInfo.indexesToBeUpdated) {
this.artifactInfo.indexesToBeUpdated = [];
}
// No Array given for Index Update, Create default array
if (
this.artifactInfo.outDir &&
this.artifactInfo.outFile &&
this.artifactInfo.indexesToBeUpdated.length === 0
) {
this.artifactInfo.indexesToBeUpdated = [
{dir: this.artifactInfo.outDir, file: this.artifactInfo.outFile},
];
}
for (const idx of this.artifactInfo.indexesToBeUpdated) {
await this._updateIndexFile(idx.dir, idx.file);
}
}
};