Unverified Commit 26a2bab6 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

next-upgrade: prompt (un)install only when there's a change (#71308)

### Why?

When running next-upgrade, `next-request-geo-ip` requires to install
`@vercel/functions` and `built-in-next-font` makes `@next/font` no
longer needed. We added a prompt to ask user whether to (un)install it
at https://github.com/vercel/next.js/pull/71038 but it prompts even if
there were no transform occurred.

This is unnecessary layer so we only prompt when there's a change caused
from the codemod.

### No Modification


https://github.com/user-attachments/assets/3acfdb24-c8e7-4189-9c81-4765ce748822

### With Modification


https://github.com/user-attachments/assets/f44a8b1c-c75a-4446-afc8-f74111de939d

---------
parent 19e2edcf
......@@ -23,6 +23,7 @@ packages/react-dev-overlay/lib/**
.github/actions/next-stats-action/.work
packages/next-codemod/transforms/__testfixtures__/**/*
packages/next-codemod/transforms/__tests__/**/*
packages/next-codemod/bin/__testfixtures__/**/*
packages/next-codemod/**/*.js
packages/next-codemod/**/*.d.ts
packages/next-env/**/*.d.ts
......
// @ts-nocheck
import { type NextRequest, NextResponse } from 'next/server'
export function GET(request: NextRequest) {
const geo = request.geo
const ip = request.ip
return NextResponse.json({ geo, ip })
}
{
"name": "geo-ip-usage",
"scripts": {
"dev": "next dev --turbo"
},
"dependencies": {
"next": "15.0.0-canary.152",
"react": "19.0.0-rc-94e652d5-20240912",
"react-dom": "19.0.0-rc-94e652d5-20240912"
}
}
{
"name": "no-geo-ip-usage",
"scripts": {
"dev": "next dev --turbo"
},
"dependencies": {
"next": "15.0.0-canary.152",
"react": "19.0.0-rc-94e652d5-20240912",
"react-dom": "19.0.0-rc-94e652d5-20240912"
}
}
import execa from 'execa'
import globby from 'globby'
import prompts from 'prompts'
import stripAnsi from 'strip-ansi'
import { join } from 'node:path'
import { installPackages, uninstallPackage } from '../lib/handle-package'
import {
......@@ -79,6 +80,25 @@ export async function runTransform(
transformer = res.transformer
}
if (transformer === 'next-request-geo-ip') {
const { isAppDeployedToVercel } = await prompts(
{
type: 'confirm',
name: 'isAppDeployedToVercel',
message:
'Is your app deployed to Vercel? (Required to apply the selected codemod)',
initial: true,
},
{ onCancel }
)
if (!isAppDeployedToVercel) {
console.log(
'Skipping codemod "next-request-geo-ip" as your app is not deployed to Vercel.'
)
return
}
}
const filesExpanded = expandFilePathsIfNeeded([directory])
if (!filesExpanded.length) {
......@@ -126,22 +146,77 @@ export async function runTransform(
console.log(`Executing command: jscodeshift ${args.join(' ')}`)
const result = execa.sync(jscodeshiftExecutable, args, {
stdio: 'inherit',
stripFinalNewline: false,
const execaChildProcess = execa(jscodeshiftExecutable, args, {
// include ANSI color codes
// Note: execa merges env with existing env by default.
env: process.stdout.isTTY ? { FORCE_COLOR: 'true' } : {},
})
if (result.failed) {
throw new Error(`jscodeshift exited with code ${result.exitCode}`)
}
// "\n" + "a\n" + "b\n"
let lastThreeLineBreaks = ''
if (!dry && transformer === 'built-in-next-font') {
const { uninstallNextFont } = await prompts({
type: 'confirm',
name: 'uninstallNextFont',
message: 'Do you want to uninstall `@next/font`?',
initial: true,
if (execaChildProcess.stdout) {
execaChildProcess.stdout.pipe(process.stdout)
execaChildProcess.stderr.pipe(process.stderr)
// The last two lines contain the successful transformation count as "N ok".
// To save memory, we "slide the window" to keep only the last three line breaks.
// We save three line breaks because the EOL is always "\n".
execaChildProcess.stdout.on('data', (chunk) => {
lastThreeLineBreaks += chunk.toString('utf-8')
let cutoff = lastThreeLineBreaks.length
// Note: the stdout ends with "\n".
// "foo\n" + "bar\n" + "baz\n" -> "\nbar\nbaz\n"
// "\n" + "foo\n" + "bar\n" -> "\nfoo\nbar\n"
for (let i = 0; i < 3; i++) {
cutoff = lastThreeLineBreaks.lastIndexOf('\n', cutoff) - 1
}
if (cutoff > 0 && cutoff < lastThreeLineBreaks.length) {
lastThreeLineBreaks = lastThreeLineBreaks.slice(cutoff + 1)
}
})
}
try {
const result = await execaChildProcess
if (result.failed) {
throw new Error(`jscodeshift exited with code ${result.exitCode}`)
}
} catch (error) {
throw error
}
// With ANSI color codes, it will be "\x1B[39m\x1B[32m0 ok".
// Without, it will be "0 ok".
const targetOkLine = lastThreeLineBreaks.split('\n').at(-3)
if (!targetOkLine.endsWith('ok')) {
throw new Error(
`Failed to parse the successful transformation count "${targetOkLine}". This is a bug in the codemod tool.`
)
}
const stripped = stripAnsi(targetOkLine)
// "N ok" -> "N"
const parsedNum = parseInt(stripped.split(' ')[0], 10)
const hasChanges = parsedNum > 0
if (!dry && transformer === 'built-in-next-font' && hasChanges) {
const { uninstallNextFont } = await prompts(
{
type: 'confirm',
name: 'uninstallNextFont',
message:
'`built-in-next-font` should have removed all usages of `@next/font`. Do you want to uninstall `@next/font`?',
initial: true,
},
{ onCancel }
)
if (uninstallNextFont) {
console.log('Uninstalling `@next/font`')
......@@ -149,17 +224,11 @@ export async function runTransform(
}
}
if (!dry && transformer === 'next-request-geo-ip') {
const { installVercelFunctions } = await prompts({
type: 'confirm',
name: 'installVercelFunctions',
message: 'Do you want to install `@vercel/functions`?',
initial: true,
})
if (installVercelFunctions) {
console.log('Installing `@vercel/functions`...')
installPackages(['@vercel/functions'])
}
// When has changes, it requires `@vercel/functions`, so skip prompt.
if (!dry && transformer === 'next-request-geo-ip' && hasChanges) {
console.log(
'Installing `@vercel/functions` because the `next-request-geo-ip` made changes.'
)
installPackages(['@vercel/functions'])
}
}
......@@ -17,7 +17,8 @@
"jscodeshift": "17.0.0",
"picocolors": "1.0.0",
"prompts": "2.4.2",
"semver": "7.6.3"
"semver": "7.6.3",
"strip-ansi": "6.0.0"
},
"files": [
"transforms/*.js",
......
......@@ -1538,6 +1538,9 @@ importers:
semver:
specifier: 7.6.3
version: 7.6.3
strip-ansi:
specifier: 6.0.0
version: 6.0.0
devDependencies:
'@types/find-up':
specifier: 4.0.0
......@@ -12676,7 +12679,6 @@ packages:
engines: {node: '>=0.6.0', teleport: '>=0.2.0'}
deprecated: |-
You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.
(For a CapTP with native promises, see @endo/eventual-send and @endo/captp)
qs@6.11.0:
......@@ -18029,7 +18031,7 @@ snapshots:
micromatch: 4.0.5
pretty-format: 29.7.0
slash: 3.0.0
strip-ansi: 6.0.1
strip-ansi: 6.0.0
transitivePeerDependencies:
- babel-plugin-macros
- supports-color
......@@ -21659,7 +21661,7 @@ snapshots:
cliui@7.0.4:
dependencies:
string-width: 4.2.3
strip-ansi: 6.0.1
strip-ansi: 6.0.0
wrap-ansi: 7.0.0
cliui@8.0.1:
......@@ -27993,7 +27995,7 @@ snapshots:
is-interactive: 1.0.0
log-symbols: 3.0.0
mute-stream: 0.0.8
strip-ansi: 6.0.1
strip-ansi: 6.0.0
wcwidth: 1.0.1
ora@5.4.1:
......@@ -32128,7 +32130,7 @@ snapshots:
dependencies:
ansi-styles: 4.3.0
string-width: 4.2.3
strip-ansi: 6.0.1
strip-ansi: 6.0.0
wrap-ansi@8.1.0:
dependencies:
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment