Skip to content

Commit

Permalink
Merge branch 'main' into fix/generator-loads-hardcoded-prisma-schema-…
Browse files Browse the repository at this point in the history
…path
  • Loading branch information
Dillon Raphael authored Oct 3, 2022
2 parents ef3efc9 + eb970f7 commit e121070
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 44 deletions.
5 changes: 5 additions & 0 deletions .changeset/spotty-lies-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---

Fix detecting `blitz.config.(ts|js)` config file when running the codemod.
121 changes: 77 additions & 44 deletions packages/codemod/src/upgrade-legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
replaceIdentifiers,
replaceBlitzPkgsVersions,
} from "./utils"
import { log } from "blitz"
import {log} from "blitz"

const CURRENT_BLITZ_TAG = "latest"

Expand All @@ -35,21 +35,27 @@ class ExpectedError extends Error {
const isInternalBlitzMonorepoDevelopment = fs.existsSync(
path.join(__dirname, "../../../blitz-next"),
)
type Step = { name: string; action: (stepIndex: number) => Promise<void> }
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))
let existingBlitzConfigFiles = ["ts", "js"]
.map((e) => `blitz.config.${e}`)
.map((e) => path.resolve(e))
.filter(fs.existsSync)
let blitzConfigFile = existingBlitzConfigFiles.reduce((_prev, current) => current, "")
if (blitzConfigFile === "") {
throw new ExpectedError("Could not identify Legacy Blitz Config file")
}
const appDir = path.resolve("app")
let failedAt =
fs.existsSync(path.resolve(".migration.json")) && fs.readJSONSync("./.migration.json").failedAt
let collectedErrors: { message: string; step: number }[] = []
let collectedErrors: {message: string; step: number}[] = []
let steps: Step[] = []

// Add steps in order

steps.push({
name: "move the config from blitz.config.ts to next.config.js",
name: `move the config from ${blitzConfigFile} to next.config.js`,
action: async () => {
const program = getCollectionFromSource(blitzConfigFile)
const parsedProgram = program.get()
Expand Down Expand Up @@ -115,7 +121,9 @@ const upgradeLegacy = async () => {
j.assignmentExpression(
"=",
j.identifier("const " + defaultImport.local.name),
j.callExpression(j.identifier("require"), [j.stringLiteral(`${i.value.source.value}`)]),
j.callExpression(j.identifier("require"), [
j.stringLiteral(`${i.value.source.value}`),
]),
),
)
parsedProgram.value.program.body.unshift(importStatement)
Expand All @@ -128,7 +136,9 @@ const upgradeLegacy = async () => {
j.assignmentExpression(
"=",
j.identifier("const {" + namedImportNamesString + "}"),
j.callExpression(j.identifier("require"), [j.stringLiteral(`${i.value.source.value}`)]),
j.callExpression(j.identifier("require"), [
j.stringLiteral(`${i.value.source.value}`),
]),
),
)
parsedProgram.value.program.body.unshift(importStatement)
Expand Down Expand Up @@ -317,8 +327,10 @@ const upgradeLegacy = async () => {
})
fs.writeFileSync(path.resolve(appDir, filename), program.toSource())
} catch (e) {
log.error(`Error updating imports in the ${file}`)
throw new Error(e)
log.error(`Error updating imports in the ${filename}`)
if (typeof e === "string") {
throw new Error(e)
}
}
})
},
Expand Down Expand Up @@ -400,7 +412,9 @@ const upgradeLegacy = async () => {
fs.writeFileSync(path.join(path.resolve(file)), program.toSource())
} catch (e) {
log.error(`Error in updating next.js default imports in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
})
},
Expand Down Expand Up @@ -432,7 +446,9 @@ const upgradeLegacy = async () => {
fs.writeFileSync(path.resolve(appDir, file), program.toSource())
} catch (e) {
log.error(`Error in changing queryClient to getQueryClient in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
})
},
Expand All @@ -452,7 +468,9 @@ const upgradeLegacy = async () => {
fs.writeFileSync(path.join(path.resolve(file)), program.toSource())
} catch (e) {
log.error(`Error in changing BlitzApiRequest to NextApiRequest in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
},
)
Expand All @@ -473,7 +491,9 @@ const upgradeLegacy = async () => {
fs.writeFileSync(path.join(path.resolve(file)), program.toSource())
} catch (e) {
log.error(`Error in changing BlitzApiResponse to NextApiResponse in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
},
)
Expand All @@ -494,7 +514,9 @@ const upgradeLegacy = async () => {
fs.writeFileSync(path.join(path.resolve(file)), program.toSource())
} catch (e) {
log.error(`Error in changing BlitzApiHandler to NextApiHandler in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
},
)
Expand Down Expand Up @@ -666,7 +688,7 @@ const upgradeLegacy = async () => {
.toString()

if (!fs.existsSync(pagesDir)) {
fs.mkdirSync(pagesDir, { recursive: true })
fs.mkdirSync(pagesDir, {recursive: true})
}

fs.writeFileSync(
Expand Down Expand Up @@ -714,7 +736,7 @@ const upgradeLegacy = async () => {
let files = fs.readdirSync(dirPath)

const pageDir = files.reduce(
(arr: { model: string; path: string; subModel?: string }[], file: string) => {
(arr: {model: string; path: string; subModel?: string}[], file: string) => {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
let subs = fs.readdirSync(dirPath + "/" + file)

Expand Down Expand Up @@ -838,7 +860,8 @@ const upgradeLegacy = async () => {

if (findBlitzCustomServerLiteral.length === 0) {
log.error(
`Failed to find "blitz/custom-server" import in ${customServerDir}/index.${isTypescript ? "ts" : "js"
`Failed to find "blitz/custom-server" import in ${customServerDir}/index.${
isTypescript ? "ts" : "js"
}. You will need to update your custom server manually.`,
)
} else {
Expand Down Expand Up @@ -957,7 +980,9 @@ const upgradeLegacy = async () => {
}
} catch (e) {
log.error(`Error in changing useRouterQuery to useRouter in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
})

Expand Down Expand Up @@ -1021,7 +1046,9 @@ const upgradeLegacy = async () => {
}
} catch (e) {
log.error(`Error in changing useRouterQuery to useRouter in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
})
},
Expand All @@ -1045,7 +1072,7 @@ const upgradeLegacy = async () => {

if (appFunction.length) {
// Store the App function
const storeFunction = { ...appFunction.get().value }
const storeFunction = {...appFunction.get().value}
// Create a new withBlitz call expresion with an empty argument
const withBlitzFunction = (appFunction.get().parentPath.value.declaration =
j.expressionStatement(j.callExpression(j.identifier("withBlitz"), []))) as any
Expand All @@ -1055,7 +1082,7 @@ const upgradeLegacy = async () => {
appIdentifier.forEach((a) => {
switch (a.name) {
case "declaration":
const storeFunction = { ...a.get().value }
const storeFunction = {...a.get().value}
// Create a new withBlitz call expresion with an empty argument
const withBlitzFunction = (a.get().parentPath.value.declaration =
j.expressionStatement(j.callExpression(j.identifier("withBlitz"), []))) as any
Expand Down Expand Up @@ -1181,7 +1208,9 @@ const upgradeLegacy = async () => {
fs.writeFileSync(path.join(path.resolve(file)), program.toSource())
} catch (e) {
log.error(`Error in wrapping getServerSideProps, getStaticProps in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
})

Expand All @@ -1197,7 +1226,7 @@ const upgradeLegacy = async () => {
const program = getCollectionFromSource(file)
const defaultExportPath = findDefaultExportPath(program)
if (defaultExportPath) {
const { node } = defaultExportPath
const {node} = defaultExportPath

if (node.declaration.type === "Identifier") {
node.declaration = j.callExpression(j.identifier("api"), [node.declaration as any])
Expand All @@ -1211,7 +1240,9 @@ const upgradeLegacy = async () => {
}
} catch (e) {
log.error(`Error in wrapping api in the ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
})
}
Expand Down Expand Up @@ -1285,30 +1316,33 @@ const upgradeLegacy = async () => {
const invokeWithMiddlewarePath = findCallExpression(program, "invokeWithMiddleware")
if (invokeWithMiddlewarePath?.length) {
invokeWithMiddlewarePath.forEach((path) => {
const resolverName = path.value.arguments.at(0)
if(resolverName?.type === "Identifier") {
const resolverExpression = j.callExpression(
j.identifier(resolverName.name),
path.value.arguments.slice(1),
)
const resolverStatement = j.expressionStatement(resolverExpression)
j(path).replaceWith(resolverStatement)
}
else{
throw new Error(`invokeWithMiddleware can only be used with a resolver as the first argument \nError at Line ${path?.value?.loc?.start.line}`)
}
})
const resolverName = path.value.arguments.at(0)
if (resolverName?.type === "Identifier") {
const resolverExpression = j.callExpression(
j.identifier(resolverName.name),
path.value.arguments.slice(1),
)
const resolverStatement = j.expressionStatement(resolverExpression)
j(path).replaceWith(resolverStatement)
} else {
throw new Error(
`invokeWithMiddleware can only be used with a resolver as the first argument \nError at Line ${path?.value?.loc?.start.line}`,
)
}
})
}
} catch (e:any) {
} catch (e) {
log.error(`\nError in checking invokeWithMiddleware in ${file}`)
throw new Error(e)
if (typeof e === "string") {
throw new Error(e)
}
}
fs.writeFileSync(path.join(path.resolve(file)), program.toSource())
})
},
})
// Loop through steps and run the action
if ((failedAt && failedAt < steps.length) || failedAt !== "SUCCESS" || isLegacyBlitz) {
if ((failedAt && failedAt < steps.length) || failedAt !== "SUCCESS") {
for (let [index, step] of steps.entries()) {
// Ignore previous steps and continue at step that was failed
if (failedAt && index + 1 < failedAt) {
Expand All @@ -1325,7 +1359,7 @@ const upgradeLegacy = async () => {
}
} catch (err) {
// Hard exit error
const error = err as { code: string } | string
const error = err as {code: string} | string
spinner.fail(`${step.name}`)
log.error(error as string)

Expand Down Expand Up @@ -1362,8 +1396,7 @@ const upgradeLegacy = async () => {
log.withBrand("Migration already successful")
process.exit(0)
}
log.error("Legacy blitz config file not found")
}
}

export { upgradeLegacy }
export {upgradeLegacy}

0 comments on commit e121070

Please sign in to comment.