-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathGeneratorAPI.js
305 lines (281 loc) · 9.11 KB
/
GeneratorAPI.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
const fs = require('fs')
const ejs = require('ejs')
const path = require('path')
const globby = require('globby')
const merge = require('deepmerge')
const resolve = require('resolve')
const isBinary = require('isbinaryfile')
const yaml = require('yaml-front-matter')
const mergeDeps = require('./util/mergeDeps')
const stringifyJS = require('./util/stringifyJS')
const { getPluginLink, toShortPluginId } = require('@vue/cli-shared-utils')
const isString = val => typeof val === 'string'
const isFunction = val => typeof val === 'function'
const isObject = val => val && typeof val === 'object'
class GeneratorAPI {
/**
* @param {string} id - Id of the owner plugin
* @param {Generator} generator - The invoking Generator instance
* @param {object} options - generator options passed to this plugin
* @param {object} rootOptions - root options (the entire preset)
*/
constructor (id, generator, options, rootOptions) {
this.id = id
this.generator = generator
this.options = options
this.rootOptions = rootOptions
this.pluginsData = generator.plugins
.filter(({ id }) => id !== `@vue/cli-service`)
.map(({ id }) => ({
name: toShortPluginId(id),
link: getPluginLink(id)
}))
this._entryFile = undefined
}
/**
* Resolves the data when rendering templates.
*
* @private
*/
_resolveData (additionalData) {
return Object.assign({
options: this.options,
rootOptions: this.rootOptions,
plugins: this.pluginsData
}, additionalData)
}
/**
* Inject a file processing middleware.
*
* @private
* @param {FileMiddleware} middleware - A middleware function that receives the
* virtual files tree object, and an ejs render function. Can be async.
*/
_injectFileMiddleware (middleware) {
this.generator.fileMiddlewares.push(middleware)
}
/**
* Resolve path for a project.
*
* @param {string} _path - Relative path from project root
* @return {string} The resolved absolute path.
*/
resolve (_path) {
return path.resolve(this.generator.context, _path)
}
/**
* Check if the project has a given plugin.
*
* @param {string} id - Plugin id, can omit the (@vue/|vue-|@scope/vue)-cli-plugin- prefix
* @return {boolean}
*/
hasPlugin (id) {
return this.generator.hasPlugin(id)
}
/**
* Extend the package.json of the project.
* Nested fields are deep-merged unless `{ merge: false }` is passed.
* Also resolves dependency conflicts between plugins.
* Tool configuration fields may be extracted into standalone files before
* files are written to disk.
*
* @param {object | () => object} fields - Fields to merge.
*/
extendPackage (fields) {
const pkg = this.generator.pkg
const toMerge = isFunction(fields) ? fields(pkg) : fields
for (const key in toMerge) {
const value = toMerge[key]
const existing = pkg[key]
if (isObject(value) && (key === 'dependencies' || key === 'devDependencies')) {
// use special version resolution merge
pkg[key] = mergeDeps(
this.id,
existing || {},
value,
this.generator.depSources
)
} else if (!(key in pkg)) {
pkg[key] = value
} else if (Array.isArray(value) && Array.isArray(existing)) {
pkg[key] = existing.concat(value)
} else if (isObject(value) && isObject(existing)) {
pkg[key] = merge(existing, value)
} else {
pkg[key] = value
}
}
}
/**
* Render template files into the virtual files tree object.
*
* @param {string | object | FileMiddleware} source -
* Can be one of:
* - relative path to a directory;
* - Object hash of { sourceTemplate: targetFile } mappings;
* - a custom file middleware function.
* @param {object} [additionalData] - additional data available to templates.
* @param {object} [ejsOptions] - options for ejs.
*/
render (source, additionalData = {}, ejsOptions = {}) {
const baseDir = extractCallDir()
if (isString(source)) {
source = path.resolve(baseDir, source)
this._injectFileMiddleware(async (files) => {
const data = this._resolveData(additionalData)
const _files = await globby(['**/*'], { cwd: source })
for (const rawPath of _files) {
let filename = path.basename(rawPath)
// dotfiles are ignored when published to npm, therefore in templates
// we need to use underscore instead (e.g. "_gitignore")
if (filename.charAt(0) === '_') {
filename = `.${filename.slice(1)}`
}
const targetPath = path.join(path.dirname(rawPath), filename)
const sourcePath = path.resolve(source, rawPath)
const content = renderFile(sourcePath, data, ejsOptions)
// only set file if it's not all whitespace, or is a Buffer (binary files)
if (Buffer.isBuffer(content) || /[^\s]/.test(content)) {
files[targetPath] = content
}
}
})
} else if (isObject(source)) {
this._injectFileMiddleware(files => {
const data = this._resolveData(additionalData)
for (const targetPath in source) {
const sourcePath = path.resolve(baseDir, source[targetPath])
const content = renderFile(sourcePath, data, ejsOptions)
if (Buffer.isBuffer(content) || content.trim()) {
files[targetPath] = content
}
}
})
} else if (isFunction(source)) {
this._injectFileMiddleware(source)
}
}
/**
* Push a file middleware that will be applied after all normal file
* middelwares have been applied.
*
* @param {FileMiddleware} cb
*/
postProcessFiles (cb) {
this.generator.postProcessFilesCbs.push(cb)
}
/**
* Push a callback to be called when the files have been written to disk.
*
* @param {function} cb
*/
onCreateComplete (cb) {
this.generator.completeCbs.push(cb)
}
/**
* Add a message to be printed when the generator exits (after any other standard messages).
*
* @param {} msg String or value to print after the generation is completed
* @param {('log'|'info'|'done'|'warn'|'error')} [type='log'] Type of message
*/
exitLog (msg, type = 'log') {
this.generator.exitLogs.push({ id: this.id, msg, type })
}
/**
* convenience method for generating a js config file from json
*/
genJSConfig (value) {
return `module.exports = ${stringifyJS(value, null, 2)}`
}
/**
* Add import statements to a file.
*/
injectImports (file, imports) {
const _imports = (
this.generator.imports[file] ||
(this.generator.imports[file] = new Set())
)
;(Array.isArray(imports) ? imports : [imports]).forEach(imp => {
_imports.add(imp)
})
}
/**
* Add options to the root Vue instance (detected by `new Vue`).
*/
injectRootOptions (file, options) {
const _options = (
this.generator.rootOptions[file] ||
(this.generator.rootOptions[file] = new Set())
)
;(Array.isArray(options) ? options : [options]).forEach(opt => {
_options.add(opt)
})
}
/**
* Get the entry file taking into account typescript.
*
* @readonly
*/
get entryFile () {
if (this._entryFile) return this._entryFile
return (this._entryFile = fs.existsSync(this.resolve('src/main.ts')) ? 'src/main.ts' : 'src/main.js')
}
/**
* Is the plugin being invoked?
*
* @readonly
*/
get invoking () {
return this.generator.invoking
}
}
function extractCallDir () {
// extract api.render() callsite file location using error stack
const obj = {}
Error.captureStackTrace(obj)
const callSite = obj.stack.split('\n')[3]
const fileName = callSite.match(/\s\((.*):\d+:\d+\)$/)[1]
return path.dirname(fileName)
}
const replaceBlockRE = /<%# REPLACE %>([^]*?)<%# END_REPLACE %>/g
function renderFile (name, data, ejsOptions) {
if (isBinary.sync(name)) {
return fs.readFileSync(name) // return buffer
}
const template = fs.readFileSync(name, 'utf-8')
// custom template inheritance via yaml front matter.
// ---
// extend: 'source-file'
// replace: !!js/regexp /some-regex/
// OR
// replace:
// - !!js/regexp /foo/
// - !!js/regexp /bar/
// ---
const parsed = yaml.loadFront(template)
const content = parsed.__content
let finalTemplate = content.trim() + `\n`
if (parsed.extend) {
const extendPath = path.isAbsolute(parsed.extend)
? parsed.extend
: resolve.sync(parsed.extend, { basedir: path.dirname(name) })
finalTemplate = fs.readFileSync(extendPath, 'utf-8')
if (parsed.replace) {
if (Array.isArray(parsed.replace)) {
const replaceMatch = content.match(replaceBlockRE)
if (replaceMatch) {
const replaces = replaceMatch.map(m => {
return m.replace(replaceBlockRE, '$1').trim()
})
parsed.replace.forEach((r, i) => {
finalTemplate = finalTemplate.replace(r, replaces[i])
})
}
} else {
finalTemplate = finalTemplate.replace(parsed.replace, content.trim())
}
}
}
return ejs.render(finalTemplate, data, ejsOptions)
}
module.exports = GeneratorAPI