-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathindex.js
387 lines (342 loc) · 9.94 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
import fs from 'fs'
import path from 'path'
import lodash from 'lodash/string'
import camelcase from 'camelcase'
import pascalcase from 'pascalcase'
import pluralize from 'pluralize'
import decamelize from 'decamelize'
import { paramCase } from 'param-case'
import { getDMMF } from '@prisma/sdk'
import { getPaths as getRedwoodPaths } from '@redwoodjs/internal'
import execa from 'execa'
import Listr from 'listr'
import VerboseRenderer from 'listr-verbose-renderer'
import { format } from 'prettier'
import * as babel from '@babel/core'
import c from './colors'
export const asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
/**
* Returns the database schema for the given `name` database table parsed from
* the schema.prisma of the target application. If no `name` is given then the
* entire schema is returned.
*/
export const getSchema = async (name) => {
const schema = await getSchemaDefinitions()
if (name) {
const model = schema.datamodel.models.find((model) => {
return model.name === name
})
if (model) {
return model
} else {
throw new Error(
`No schema definition found for \`${name}\` in schema.prisma file`
)
}
}
return schema.metadata.datamodel
}
/**
* Returns the enum defined with the given `name` parsed from
* the schema.prisma of the target applicaiton. If no `name` is given then the
* all enum definitions are returned
*/
export const getEnum = async (name) => {
const schema = await getSchemaDefinitions()
if (name) {
const model = schema.datamodel.enums.find((model) => {
return model.name === name
})
if (model) {
return model
} else {
throw new Error(
`No enum schema definition found for \`${name}\` in schema.prisma file`
)
}
}
return schema.metadata.datamodel.enums
}
/*
* Returns the DMMF defined by `prisma` resolving the relevant `shema.prisma` path.
*/
export const getSchemaDefinitions = async () => {
const schemaPath = path.join(getPaths().api.db, 'schema.prisma')
const metadata = await getDMMF({
datamodel: readFile(schemaPath.toString()),
})
return metadata
}
/**
* Returns variants of the passed `name` for usage in templates. If the given
* name was "fooBar" then these would be:
* pascalName: FooBar
* singularPascalName: FooBar
* pluralPascalName: FooBars
* singularCamelName: fooBar
* pluralCamelName: fooBars
* singularParamName: foo-bar
* pluralParamName: foo-bars
* singularConstantName: FOO_BAR
* pluralConstantName: FOO_BARS
*/
export const nameVariants = (name) => {
const normalizedName = pascalcase(paramCase(pluralize.singular(name)))
return {
pascalName: pascalcase(name),
camelName: camelcase(name),
singularPascalName: normalizedName,
pluralPascalName: pluralize(normalizedName),
singularCamelName: camelcase(normalizedName),
pluralCamelName: camelcase(pluralize(normalizedName)),
singularParamName: paramCase(normalizedName),
pluralParamName: paramCase(pluralize(normalizedName)),
singularConstantName: decamelize(normalizedName).toUpperCase(),
pluralConstantName: decamelize(pluralize(normalizedName)).toUpperCase(),
}
}
export const templateRoot = path.resolve(__dirname, '../commands/generate')
export const generateTemplate = (templateFilename, { name, root, ...rest }) => {
const templatePath = path.join(root || templateRoot, templateFilename)
const template = lodash.template(readFile(templatePath).toString())
const renderedTemplate = template({
name,
...nameVariants(name),
...rest,
})
return prettify(templateFilename, renderedTemplate)
}
export const prettify = (templateFilename, renderedTemplate) => {
// We format .js and .css templates, we need to tell prettier which parser
// we're using.
// https://prettier.io/docs/en/options.html#parser
const parser = {
'.css': 'css',
'.js': 'babel',
'.ts': 'babel-ts',
}[path.extname(templateFilename.replace('.template', ''))]
if (typeof parser === 'undefined') {
return renderedTemplate
}
return format(renderedTemplate, {
...prettierOptions(),
parser,
})
}
export const readFile = (target) => fs.readFileSync(target)
export const deleteFile = (file) => {
const extension = path.extname(file)
if (['.js', '.ts'].includes(extension)) {
const baseFile = getBaseFile(file)
const files = [baseFile + '.js', baseFile + '.ts']
files.forEach((f) => {
if (fs.existsSync(f)) {
fs.unlinkSync(f)
}
})
} else {
fs.unlinkSync(file)
}
}
const getBaseFile = (file) => file.replace(/\.\w*$/, '')
const existsAnyExtensionSync = (file) => {
const extension = path.extname(file)
if (['.js', '.ts'].includes(extension)) {
const baseFile = getBaseFile(file)
return fs.existsSync(`${baseFile}.js`) || fs.existsSync(`${baseFile}.ts`)
}
return fs.existsSync(file)
}
export const writeFile = (
target,
contents,
{ overwriteExisting = false } = {}
) => {
if (!overwriteExisting && fs.existsSync(target)) {
throw new Error(`${target} already exists.`)
}
const filename = path.basename(target)
const targetDir = target.replace(filename, '')
fs.mkdirSync(targetDir, { recursive: true })
fs.writeFileSync(target, contents)
}
export const bytes = (contents) => Buffer.byteLength(contents, 'utf8')
/**
* This wraps the core version of getPaths into something that catches the exception
* and displays a helpful error message.
*/
export const getPaths = () => {
try {
return getRedwoodPaths()
} catch (e) {
console.error(c.error(e.message))
process.exit(0)
}
}
/**
* This returns the config present in `prettier.config.js` of a Redwood project.
*/
export const prettierOptions = () => {
try {
return require(path.join(getPaths().base, 'prettier.config.js'))
} catch (e) {
return undefined
}
}
// TODO: Move this into `generateTemplate` when all templates have TS support
/*
* Convert a generated TS template file into JS.
*/
export const transformTSToJS = (filename, content) => {
const result = babel.transform(content, {
filename,
configFile: false,
plugins: [
[
'@babel/plugin-transform-typescript',
{
isTSX: true,
allExtensions: true,
},
],
],
retainLines: true,
}).code
return prettify(filename.replace(/\.ts$/, '.js'), result)
}
/**
* Creates a list of tasks that write files to the disk.
*
* @param files - {[filepath]: contents}
*/
export const writeFilesTask = (files, options) => {
const { base } = getPaths()
return new Listr(
Object.keys(files).map((file) => {
const contents = files[file]
return {
title: `Writing \`./${path.relative(base, file)}\`...`,
task: () => writeFile(file, contents, options),
}
})
)
}
/**
* Creates a list of tasks that delete files from the disk.
*
* @param files - {[filepath]: contents}
*/
export const deleteFilesTask = (files) => {
const { base } = getPaths()
return new Listr([
...Object.keys(files).map((file) => {
return {
title: `Destroying \`./${path.relative(base, getBaseFile(file))}\`...`,
skip: () => !existsAnyExtensionSync(file) && `File doesn't exist`,
task: () => deleteFile(file),
}
}),
{
title: 'Cleaning up empty directories...',
task: () => cleanupEmptyDirsTask(files),
},
])
}
/**
* @param files - {[filepath]: contents}
*/
export const cleanupEmptyDirsTask = (files) => {
const { base } = getPaths()
const allDirs = Object.keys(files).map((file) => path.dirname(file))
const uniqueDirs = [...new Set(allDirs)]
return new Listr(
uniqueDirs.map((dir) => {
return {
title: `Removing empty \`./${path.relative(base, dir)}\`...`,
task: () => fs.rmdirSync(dir),
skip: () => {
if (!fs.existsSync(dir)) {
return `Doesn't exist`
}
if (fs.readdirSync(dir).length > 0) {
return 'Not empty'
}
return false
},
}
})
)
}
/**
* Update the project's routes file.
*/
export const addRoutesToRouterTask = (routes) => {
const redwoodPaths = getPaths()
const routesContent = readFile(redwoodPaths.web.routes).toString()
const newRoutesContent = routes.reverse().reduce((content, route) => {
if (content.includes(route)) {
return content
}
return content.replace(/(\s*)\<Router\>/, `$1<Router>$1 ${route}`)
}, routesContent)
writeFile(redwoodPaths.web.routes, newRoutesContent, {
overwriteExisting: true,
})
}
/**
* Remove named routes from the project's routes file.
*
* @param {string[]} routes - Route names
*/
export const removeRoutesFromRouterTask = (routes) => {
const redwoodPaths = getPaths()
const routesContent = readFile(redwoodPaths.web.routes).toString()
const newRoutesContent = routes.reduce((content, route) => {
const matchRouteByName = new RegExp(`\\s*<Route[^>]*name="${route}"[^>]*/>`)
return content.replace(matchRouteByName, '')
}, routesContent)
writeFile(redwoodPaths.web.routes, newRoutesContent, {
overwriteExisting: true,
})
}
export const runCommandTask = async (commands, { verbose }) => {
const tasks = new Listr(
commands.map(({ title, cmd, args, opts = {} }) => ({
title,
task: async () => {
return execa(cmd, args, {
shell: true,
cwd: `${getPaths().base}/api`,
stdio: verbose ? 'inherit' : 'pipe',
extendEnv: true,
cleanup: true,
...opts,
})
},
})),
{
renderer: verbose && VerboseRenderer,
dateFormat: false,
}
)
try {
await tasks.run()
return true
} catch (e) {
console.log(c.error(e.message))
return false
}
}
/*
* Extract default CLI args from an exported builder
*/
export const getDefaultArgs = (builder) => {
return Object.entries(builder).reduce((agg, [k, v]) => {
agg[k] = v.default
return agg
}, {})
}