-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathGenerator.js
381 lines (346 loc) · 10.3 KB
/
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
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
const ejs = require('ejs')
const debug = require('debug')
const GeneratorAPI = require('./GeneratorAPI')
const PackageManager = require('./util/ProjectPackageManager')
const sortObject = require('./util/sortObject')
const writeFileTree = require('./util/writeFileTree')
const inferRootOptions = require('./util/inferRootOptions')
const normalizeFilePaths = require('./util/normalizeFilePaths')
const { runTransformation } = require('vue-codemod')
const {
semver,
isPlugin,
toShortPluginId,
matchesPluginId,
loadModule,
sortPlugins
} = require('@vue/cli-shared-utils')
const ConfigTransform = require('./ConfigTransform')
const logger = require('@vue/cli-shared-utils/lib/logger')
const logTypes = {
log: logger.log,
info: logger.info,
done: logger.done,
warn: logger.warn,
error: logger.error
}
const defaultConfigTransforms = {
babel: new ConfigTransform({
file: {
js: ['babel.config.js']
}
}),
postcss: new ConfigTransform({
file: {
js: ['postcss.config.js'],
json: ['.postcssrc.json', '.postcssrc'],
yaml: ['.postcssrc.yaml', '.postcssrc.yml']
}
}),
eslintConfig: new ConfigTransform({
file: {
js: ['.eslintrc.js'],
json: ['.eslintrc', '.eslintrc.json'],
yaml: ['.eslintrc.yaml', '.eslintrc.yml']
}
}),
jest: new ConfigTransform({
file: {
js: ['jest.config.js']
}
}),
browserslist: new ConfigTransform({
file: {
lines: ['.browserslistrc']
}
}),
'lint-staged': new ConfigTransform({
file: {
js: ['lint-staged.config.js'],
json: ['.lintstagedrc', '.lintstagedrc.json'],
yaml: ['.lintstagedrc.yaml', '.lintstagedrc.yml']
}
})
}
const reservedConfigTransforms = {
vue: new ConfigTransform({
file: {
js: ['vue.config.js']
}
})
}
const ensureEOL = str => {
if (str.charAt(str.length - 1) !== '\n') {
return str + '\n'
}
return str
}
/**
* Collect created/modified files into set
* @param {Record<string,string|Buffer>} files
* @param {Set<string>} set
*/
const watchFiles = (files, set) => {
return new Proxy(files, {
set (target, key, value, receiver) {
set.add(key)
return Reflect.set(target, key, value, receiver)
},
deleteProperty (target, key) {
set.delete(key)
return Reflect.deleteProperty(target, key)
}
})
}
module.exports = class Generator {
constructor (context, {
pkg = {},
plugins = [],
afterInvokeCbs = [],
afterAnyInvokeCbs = [],
files = {},
invoking = false
} = {}) {
this.context = context
this.plugins = sortPlugins(plugins)
this.originalPkg = pkg
this.pkg = Object.assign({}, pkg)
this.pm = new PackageManager({ context })
this.imports = {}
this.rootOptions = {}
this.afterInvokeCbs = afterInvokeCbs
this.afterAnyInvokeCbs = afterAnyInvokeCbs
this.configTransforms = {}
this.defaultConfigTransforms = defaultConfigTransforms
this.reservedConfigTransforms = reservedConfigTransforms
this.invoking = invoking
// for conflict resolution
this.depSources = {}
// virtual file tree
this.files = Object.keys(files).length
// when execute `vue add/invoke`, only created/modified files are written to disk
? watchFiles(files, this.filesModifyRecord = new Set())
// all files need to be written to disk
: files
this.fileMiddlewares = []
this.postProcessFilesCbs = []
// exit messages
this.exitLogs = []
// load all the other plugins
this.allPlugins = this.resolveAllPlugins()
const cliService = plugins.find(p => p.id === '@vue/cli-service')
const rootOptions = cliService
? cliService.options
: inferRootOptions(pkg)
this.rootOptions = rootOptions
}
async initPlugins () {
const { rootOptions, invoking } = this
const pluginIds = this.plugins.map(p => p.id)
// avoid modifying the passed afterInvokes, because we want to ignore them from other plugins
const passedAfterInvokeCbs = this.afterInvokeCbs
this.afterInvokeCbs = []
// apply hooks from all plugins to collect 'afterAnyHooks'
for (const plugin of this.allPlugins) {
const { id, apply } = plugin
const api = new GeneratorAPI(id, this, {}, rootOptions)
if (apply.hooks) {
await apply.hooks(api, {}, rootOptions, pluginIds)
}
}
// We are doing save/load to make the hook order deterministic
// save "any" hooks
const afterAnyInvokeCbsFromPlugins = this.afterAnyInvokeCbs
// reset hooks
this.afterInvokeCbs = passedAfterInvokeCbs
this.afterAnyInvokeCbs = []
this.postProcessFilesCbs = []
// apply generators from plugins
for (const plugin of this.plugins) {
const { id, apply, options } = plugin
const api = new GeneratorAPI(id, this, options, rootOptions)
await apply(api, options, rootOptions, invoking)
if (apply.hooks) {
// while we execute the entire `hooks` function,
// only the `afterInvoke` hook is respected
// because `afterAnyHooks` is already determined by the `allPlugins` loop above
await apply.hooks(api, options, rootOptions, pluginIds)
}
}
// restore "any" hooks
this.afterAnyInvokeCbs = afterAnyInvokeCbsFromPlugins
}
async generate ({
extractConfigFiles = false,
checkExisting = false,
sortPackageJson = true
} = {}) {
await this.initPlugins()
// save the file system before applying plugin for comparison
const initialFiles = Object.assign({}, this.files)
// extract configs from package.json into dedicated files.
this.extractConfigFiles(extractConfigFiles, checkExisting)
// wait for file resolve
await this.resolveFiles()
// set package.json
if (sortPackageJson) {
this.sortPkg()
}
this.files['package.json'] = JSON.stringify(this.pkg, null, 2) + '\n'
// write/update file tree to disk
await writeFileTree(this.context, this.files, initialFiles, this.filesModifyRecord)
}
extractConfigFiles (extractAll, checkExisting) {
const configTransforms = Object.assign({},
defaultConfigTransforms,
this.configTransforms,
reservedConfigTransforms
)
const extract = key => {
if (
configTransforms[key] &&
this.pkg[key] &&
// do not extract if the field exists in original package.json
!this.originalPkg[key]
) {
const value = this.pkg[key]
const configTransform = configTransforms[key]
const res = configTransform.transform(
value,
checkExisting,
this.files,
this.context
)
const { content, filename } = res
this.files[filename] = ensureEOL(content)
delete this.pkg[key]
}
}
if (extractAll) {
for (const key in this.pkg) {
extract(key)
}
} else {
if (!process.env.VUE_CLI_TEST) {
// by default, always extract vue.config.js
extract('vue')
}
// always extract babel.config.js as this is the only way to apply
// project-wide configuration even to dependencies.
// TODO: this can be removed when Babel supports root: true in package.json
extract('babel')
}
}
sortPkg () {
// ensure package.json keys has readable order
this.pkg.dependencies = sortObject(this.pkg.dependencies)
this.pkg.devDependencies = sortObject(this.pkg.devDependencies)
this.pkg.scripts = sortObject(this.pkg.scripts, [
'serve',
'build',
'test:unit',
'test:e2e',
'lint',
'deploy'
])
this.pkg = sortObject(this.pkg, [
'name',
'version',
'private',
'description',
'author',
'scripts',
'main',
'module',
'browser',
'jsDelivr',
'unpkg',
'files',
'dependencies',
'devDependencies',
'peerDependencies',
'vue',
'babel',
'eslintConfig',
'prettier',
'postcss',
'browserslist',
'jest'
])
debug('vue:cli-pkg')(this.pkg)
}
resolveAllPlugins () {
const allPlugins = []
Object.keys(this.pkg.dependencies || {})
.concat(Object.keys(this.pkg.devDependencies || {}))
.forEach(id => {
if (!isPlugin(id)) return
const pluginGenerator = loadModule(`${id}/generator`, this.context)
if (!pluginGenerator) return
allPlugins.push({ id, apply: pluginGenerator })
})
return sortPlugins(allPlugins)
}
async resolveFiles () {
const files = this.files
for (const middleware of this.fileMiddlewares) {
await middleware(files, ejs.render)
}
// normalize file paths on windows
// all paths are converted to use / instead of \
normalizeFilePaths(files)
// handle imports and root option injections
Object.keys(files).forEach(file => {
let imports = this.imports[file]
imports = imports instanceof Set ? Array.from(imports) : imports
if (imports && imports.length > 0) {
files[file] = runTransformation(
{ path: file, source: files[file] },
require('./util/codemods/injectImports'),
{ imports }
)
}
let injections = this.rootOptions[file]
injections = injections instanceof Set ? Array.from(injections) : injections
if (injections && injections.length > 0) {
files[file] = runTransformation(
{ path: file, source: files[file] },
require('./util/codemods/injectOptions'),
{ injections }
)
}
})
await Promise.all(this.postProcessFilesCbs.map((postProcess) => postProcess(files)))
debug('vue:cli-files')(this.files)
}
hasPlugin (id, versionRange) {
const pluginExists = [
...this.plugins.map(p => p.id),
...this.allPlugins.map(p => p.id)
].some(pid => matchesPluginId(id, pid))
if (!pluginExists) {
return false
}
if (!versionRange) {
return pluginExists
}
return semver.satisfies(
this.pm.getInstalledVersion(id),
versionRange
)
}
printExitLogs () {
if (this.exitLogs.length) {
this.exitLogs.forEach(({ id, msg, type }) => {
const shortId = toShortPluginId(id)
const logFn = logTypes[type]
if (!logFn) {
logger.error(`Invalid api.exitLog type '${type}'.`, shortId)
} else {
logFn(msg, msg && shortId)
}
})
logger.log()
}
}
}