-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
Copy pathapp-generator.ts
327 lines (294 loc) · 10.1 KB
/
app-generator.ts
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
import chalk from "chalk"
import spawn from "cross-spawn"
import {readJSONSync, writeJson} from "fs-extra"
import {baseLogger, log} from "next/dist/server/lib/logging"
import {join} from "path"
import username from "username"
import {Generator, GeneratorOptions, SourceRootType} from "../generator"
import {fetchLatestVersionsFor} from "../utils/fetch-latest-version-for"
import {getBlitzDependencyVersion} from "../utils/get-blitz-dependency-version"
function assert(condition: any, message: string): asserts condition {
if (!condition) throw new Error(message)
}
type TemplateConfig = {
path: string
skipForms?: boolean
skipDatabase?: boolean
}
export interface AppGeneratorOptions extends GeneratorOptions {
template: TemplateConfig
appName: string
useTs: boolean
yarn: boolean
pnpm?: boolean
version: string
skipInstall: boolean
skipGit: boolean
form?: "React Final Form" | "React Hook Form" | "Formik"
onPostInstall?: () => Promise<void>
}
type PkgManager = "npm" | "yarn" | "pnpm"
export class AppGenerator extends Generator<AppGeneratorOptions> {
sourceRoot: SourceRootType = {type: "template", path: this.options.template.path}
// Disable file-level prettier because we manually run prettier at the end
prettierDisabled = true
packageInstallSuccess: boolean = false
filesToIgnore() {
if (!this.options.useTs) {
return [
"tsconfig.json",
"blitz-env.d.ts",
"jest.config.ts",
"package.ts.json",
"pre-push-ts",
"types.ts",
]
}
return ["jsconfig.json", "jest.config.js", "package.js.json", "pre-push-js"]
}
async getTemplateValues() {
return {
name: this.options.appName,
safeNameSlug: this.options.appName.replace(/[^a-zA-Z0-9-_]/g, "-"),
username: await username(),
}
}
getTargetDirectory() {
return ""
}
// eslint-disable-next-line require-await
async preCommit() {
this.fs.move(this.destinationPath("gitignore"), this.destinationPath(".gitignore"))
this.fs.move(this.destinationPath("npmrc"), this.destinationPath(".npmrc"))
this.fs.move(
this.destinationPath(this.options.useTs ? ".husky/pre-push-ts" : ".husky/pre-push-js"),
this.destinationPath(".husky/pre-push"),
)
this.fs.move(
this.destinationPath(this.options.useTs ? "package.ts.json" : "package.js.json"),
this.destinationPath("package.json"),
)
if (!this.options.template.skipForms) {
this.updateForms()
}
}
async postWrite() {
const {pkgManager} = this
let gitInitSuccessful
if (!this.options.skipGit) {
const initResult = spawn.sync("git", ["init"], {
stdio: "ignore",
})
gitInitSuccessful = initResult.status === 0
if (!gitInitSuccessful) {
baseLogger({displayDateTime: false}).warn("Failed to run git init.")
baseLogger({displayDateTime: false}).warn(
"Find out more about how to install git here: https://git-scm.com/downloads.",
)
}
}
const pkgJsonLocation = join(this.destinationPath(), "package.json")
const pkg = readJSONSync(pkgJsonLocation)
console.log("") // New line needed
const spinner = log.spinner(log.withBrand("Retrieving the freshest of dependencies")).start()
const [
{value: newDependencies, isFallback: dependenciesUsedFallback},
{value: newDevDependencies, isFallback: devDependenciesUsedFallback},
{value: blitzDependencyVersion, isFallback: blitzUsedFallback},
] = await Promise.all([
fetchLatestVersionsFor(pkg.dependencies),
fetchLatestVersionsFor(pkg.devDependencies),
getBlitzDependencyVersion(this.options.version),
])
pkg.dependencies = newDependencies
pkg.devDependencies = newDevDependencies
pkg.dependencies.blitz = blitzDependencyVersion
const fallbackUsed =
dependenciesUsedFallback || devDependenciesUsedFallback || blitzUsedFallback
await writeJson(pkgJsonLocation, pkg, {spaces: 2})
if (!fallbackUsed && !this.options.skipInstall) {
spinner.succeed()
await new Promise<void>((resolve) => {
const logFlag = pkgManager === "yarn" ? "--json" : "--loglevel=error"
const cp = spawn(pkgManager, ["install", logFlag], {
stdio: ["inherit", "pipe", "pipe"],
})
const getJSON = (data: string) => {
try {
return JSON.parse(data)
} catch {
return null
}
}
const spinners: any[] = []
if (pkgManager !== "yarn") {
const spinner = log
.spinner(log.withBrand("Installing those dependencies (this will take a few minutes)"))
.start()
spinners.push(spinner)
}
cp.stdout?.setEncoding("utf8")
cp.stderr?.setEncoding("utf8")
cp.stdout?.on("data", (data) => {
if (pkgManager === "yarn") {
let json = getJSON(data)
if (json && json.type === "step") {
spinners[spinners.length - 1]?.succeed()
const spinner = log.spinner(log.withBrand(json.data.message)).start()
spinners.push(spinner)
}
if (json && json.type === "success") {
spinners[spinners.length - 1]?.succeed()
}
}
})
cp.stderr?.on("data", (data) => {
if (pkgManager === "yarn") {
let json = getJSON(data)
if (json && json.type === "error") {
spinners[spinners.length - 1]?.fail()
console.error(json.data)
}
} else {
// Hide the annoying Prisma warning about not finding the schema file
// because we generate the client ourselves
if (!data.includes("schema.prisma")) {
console.error(`\n${data}`)
}
}
})
cp.on("exit", (code) => {
if (pkgManager !== "yarn" && spinners[spinners.length - 1].isSpinning) {
if (code !== 0) spinners[spinners.length - 1].fail()
else {
spinners[spinners.length - 1].succeed()
this.packageInstallSuccess = true
}
}
resolve()
})
})
await this.options.onPostInstall?.()
const runLocalNodeCLI = (command: string) => {
const {pkgManager} = this
if (pkgManager === "yarn") {
return spawn.sync("yarn", ["run", ...command.split(" ")])
} else if (pkgManager === "pnpm") {
return spawn.sync("pnpx", command.split(" "))
} else {
return spawn.sync("npx", command.split(" "))
}
}
// Ensure the generated files are formatted with the installed prettier version
if (this.packageInstallSuccess) {
const formattingSpinner = log.spinner(log.withBrand("Formatting your code")).start()
const prettierResult = runLocalNodeCLI("prettier --loglevel silent --write .")
if (prettierResult.status !== 0) {
formattingSpinner.fail(
chalk.yellow.bold(
"We had an error running Prettier, but don't worry your app will still run fine :)",
),
)
} else {
formattingSpinner.succeed()
}
}
} else {
console.log("") // New line needed
if (this.options.skipInstall) {
spinner.succeed()
} else {
spinner.fail(
chalk.red.bold(
`We had some trouble connecting to the network, so we'll skip installing your dependencies right now. Make sure to run ${`${this.pkgManager} install`} once you're connected again.`,
),
)
}
}
if (!this.options.skipGit && gitInitSuccessful) {
this.commitChanges()
}
}
preventFileFromLogging(path: string): boolean {
if (path.includes(".env")) return false
if (path.includes("eslint")) return false
const filename = path.split("/").pop() as string
return path[0] === "." || filename[0] === "."
}
commitChanges() {
const commitSpinner = log.spinner(log.withBrand("Committing your app")).start()
const commands: Array<[string, string[], object]> = [
["git", ["add", "."], {stdio: "ignore"}],
[
"git",
[
"-c",
"user.name='Blitz.js CLI'",
"-c",
"user.email='[email protected]'",
"commit",
"--no-gpg-sign",
"--no-verify",
"-m",
"Brand new Blitz app!",
],
{stdio: "ignore", timeout: 10000},
],
]
for (let command of commands) {
const result = spawn.sync(...command)
if (result.status !== 0) {
commitSpinner.fail(
chalk.red.bold(
`Failed to run command ${command[0]} with ${command[1].join(" ")} options.`,
),
)
return
}
}
commitSpinner.succeed()
}
private updateForms() {
const pkg = this.fs.readJSON(this.destinationPath("package.json")) as
| Record<string, any>
| undefined
assert(pkg, "couldn't find package.json")
const ext = this.options.useTs ? "tsx" : "js"
let type: string = ""
switch (this.options.form) {
case "React Final Form":
type = "finalform"
pkg.dependencies["final-form"] = "4.x"
pkg.dependencies["react-final-form"] = "6.x"
break
case "React Hook Form":
type = "hookform"
pkg.dependencies["react-hook-form"] = "7.x"
pkg.dependencies["@hookform/resolvers"] = "2.x"
break
case "Formik":
type = "formik"
pkg.dependencies["formik"] = "2.x"
break
}
this.fs.move(
this.destinationPath(`_forms/${type}/Form.${ext}`),
this.destinationPath(`app/core/components/Form.${ext}`),
)
this.fs.move(
this.destinationPath(`_forms/${type}/LabeledTextField.${ext}`),
this.destinationPath(`app/core/components/LabeledTextField.${ext}`),
)
this.fs.writeJSON(this.destinationPath("package.json"), pkg)
this.fs.delete(this.destinationPath("_forms"))
}
private get pkgManager(): PkgManager {
if (this.options.pnpm) {
return "pnpm"
} else if (this.options.yarn) {
return "yarn"
} else {
return "npm"
}
}
}