Skip to content

Commit

Permalink
Store error for cookiePrefix if undefined & show error at the end of …
Browse files Browse the repository at this point in the history
…codemod (#3704)

* store error for cookiePrefix if undefined & show error at the end

* rename to collectedErrors

* fix type & update error message
  • Loading branch information
Dillon Raphael authored Aug 10, 2022
1 parent 85b15a9 commit 2d1482f
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 126 deletions.
5 changes: 5 additions & 0 deletions .changeset/sour-mails-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---

Allow codemod to finish if `cookiePrefix` is undefined. Then show error at the end of running the codemod.
102 changes: 37 additions & 65 deletions packages/codemod/src/upgrade-legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,16 @@ class ExpectedError extends Error {
const isInternalBlitzMonorepoDevelopment = fs.existsSync(
path.join(__dirname, "../../../blitz-next"),
)

type Step = {name: string; action: (stepIndex: number) => Promise<void>}
const upgradeLegacy = async () => {
let isTypescript = fs.existsSync(path.resolve("tsconfig.json"))
let blitzConfigFile = `blitz.config.${isTypescript ? "ts" : "js"}`
let isLegacyBlitz = fs.existsSync(path.resolve(blitzConfigFile))
const appDir = path.resolve("app")
let failedAt =
fs.existsSync(path.resolve(".migration.json")) && fs.readJSONSync("./.migration.json").failedAt

let steps: {
name: string
action: () => Promise<void>
}[] = []
let collectedErrors: {message: string; step: number}[] = []
let steps: Step[] = []

// Add steps in order

Expand All @@ -61,8 +58,8 @@ const upgradeLegacy = async () => {
withBlitz.shorthand = true

/* Declare the variable using the object above that equals to a require expression, eg.
const {withBlitz} = require("@blitzjs/next")
*/
const {withBlitz} = require("@blitzjs/next")
*/
let blitzDeclare = j.variableDeclaration("const", [
j.variableDeclarator(
j.objectPattern([withBlitz]),
Expand Down Expand Up @@ -411,7 +408,7 @@ const upgradeLegacy = async () => {

steps.push({
name: "Add cookiePrefix to blitz server",
action: async () => {
action: async (stepIndex) => {
const blitzConfigProgram = getCollectionFromSource(blitzConfigFile)
const cookieIdentifier = blitzConfigProgram.find(
j.Identifier,
Expand All @@ -434,9 +431,12 @@ const upgradeLegacy = async () => {
blitzClientProgram.toSource(),
)
} else {
throw new ExpectedError(
"Cookie Prefix is undefined & not a string. Please set your cookie prefix manually in app/blitz-client",
)
// Show error at end of codemod
collectedErrors.push({
message:
"Detected cookiePrefix is undefined. Please set your cookie prefix manually in app/blitz-client",
step: stepIndex,
})
}
} else {
log.error("Cookie Prefix not found in blitz config file")
Expand Down Expand Up @@ -1110,7 +1110,7 @@ const upgradeLegacy = async () => {

steps.push({
name: "check for usages of invokeWithMiddleware",
action: async () => {
action: async (stepIndex) => {
let errors = 0

getAllFiles(appDir, [], [], [".ts", ".tsx", ".js", ".jsx"]).forEach((file) => {
Expand All @@ -1132,58 +1132,21 @@ const upgradeLegacy = async () => {
})

if (errors > 0) {
throw new ExpectedError(
"\n invokeWithMiddleware is not supported. \n Use invokeWithCtx instead: https://canary.blitzjs.com/docs/resolver-server-utilities#invoke-with-ctx \n Fix the files above, then run the codemod again.",
)
collectedErrors.push({
message:
"\n invokeWithMiddleware is not supported. \n Use invokeWithCtx instead: https://canary.blitzjs.com/docs/resolver-server-utilities#invoke-with-ctx \n Fix the files above, then run the codemod again.",
step: stepIndex,
})

// Write to the migration file so the user can run the migration again from this point
failedAt = stepIndex + 1
fs.writeJsonSync(".migration.json", {
failedAt,
})
}
},
})

// steps.push({
// name: "Update invokeMiddleware to invoke",
// action: async () => {
// getAllFiles(appDir, [], [], [".css"]).forEach((file) => {
// const program = getCollectionFromSource(file)
// const importSpecifier = findImportSpecifier(program, "invokeWithMiddleware")
// importSpecifier?.paths().forEach((path) => {
// path.get().value.imported.name = "invoke"
// })

// const invokeWithMiddlewarePath = findCallExpression(program, "invokeWithMiddleware")
// if (invokeWithMiddlewarePath?.length) {
// invokeWithMiddlewarePath?.paths().forEach((path) => {
// path.get().value.callee.name = "invoke"
// if (path.get().value.arguments.length === 3) {
// delete path.get().value.arguments[2]
// }
// })
// }

// fs.writeFileSync(path.resolve(file), program.toSource())
// })

// getAllFiles(path.resolve("pages"), [], [], [".css"]).forEach((file) => {
// const program = getCollectionFromSource(file)
// const importSpecifier = findImportSpecifier(program, "invokeWithMiddleware")
// importSpecifier?.paths().forEach((path) => {
// path.get().value.imported.name = "invoke"
// })

// const invokeWithMiddlewarePath = findCallExpression(program, "invokeWithMiddleware")
// if (invokeWithMiddlewarePath?.length) {
// invokeWithMiddlewarePath?.paths().forEach((path) => {
// path.get().value.callee.name = "invoke"
// if (path.get().value.arguments.length === 3) {
// delete path.get().value.arguments[2]
// }
// })
// }

// fs.writeFileSync(path.resolve(file), program.toSource())
// })
// },
// })

// Loop through steps and run the action
if ((failedAt && failedAt < steps.length) || failedAt !== "SUCCESS" || isLegacyBlitz) {
for (let [index, step] of steps.entries()) {
Expand All @@ -1193,8 +1156,15 @@ const upgradeLegacy = async () => {
}
const spinner = log.spinner(log.withBrand(`Running ${step.name}...`)).start()
try {
await step.action()
await step.action(index)
if (collectedErrors.filter((e) => e.step === index).length) {
// Soft stored error
spinner.fail(`${step.name}`)
} else {
spinner.succeed(`Successfully ran ${step.name}`)
}
} catch (err) {
// Hard exit error
const error = err as {code: string} | string
spinner.fail(`${step.name}`)
log.error(error as string)
Expand All @@ -1218,10 +1188,12 @@ const upgradeLegacy = async () => {
})
process.exit(1)
}

spinner.succeed(`Successfully ran ${step.name}`)
}

if (collectedErrors.length) {
for (const error of collectedErrors) {
log.error(`⚠️ ${error.message}`)
}
}
fs.writeJsonSync(".migration.json", {
failedAt: "SUCCESS",
})
Expand Down
Loading

0 comments on commit 2d1482f

Please sign in to comment.