-
Notifications
You must be signed in to change notification settings - Fork 27k
/
cli.ts
250 lines (221 loc) · 7.42 KB
/
cli.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
/**
* Copyright 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// Based on https://github.com/reactjs/react-codemod/blob/dd8671c9a470a2c342b221ec903c574cf31e9f57/bin/cli.js
// @next/codemod optional-name-of-transform optional/path/to/src [...options]
import globby from 'globby'
import inquirer from 'inquirer'
import meow from 'meow'
import path from 'path'
import execa from 'execa'
import { yellow } from 'picocolors'
import isGitClean from 'is-git-clean'
import { uninstallPackage } from '../lib/uninstall-package'
export const jscodeshiftExecutable = require.resolve('.bin/jscodeshift')
export const transformerDirectory = path.join(__dirname, '../', 'transforms')
export function checkGitStatus(force) {
let clean = false
let errorMessage = 'Unable to determine if git directory is clean'
try {
clean = isGitClean.sync(process.cwd())
errorMessage = 'Git directory is not clean'
} catch (err) {
if (err && err.stderr && err.stderr.includes('Not a git repository')) {
clean = true
}
}
if (!clean) {
if (force) {
console.log(`WARNING: ${errorMessage}. Forcibly continuing.`)
} else {
console.log('Thank you for using @next/codemod!')
console.log(
yellow(
'\nBut before we continue, please stash or commit your git changes.'
)
)
console.log(
'\nYou may use the --force flag to override this safety check.'
)
process.exit(1)
}
}
}
export function runTransform({ files, flags, transformer }) {
const transformerPath = path.join(transformerDirectory, `${transformer}.js`)
if (transformer === 'cra-to-next') {
// cra-to-next transform doesn't use jscodeshift directly
return require(transformerPath).default(files, flags)
}
let args = []
const { dry, print, runInBand } = flags
if (dry) {
args.push('--dry')
}
if (print) {
args.push('--print')
}
if (runInBand) {
args.push('--run-in-band')
}
args.push('--verbose=2')
args.push('--ignore-pattern=**/node_modules/**')
args.push('--ignore-pattern=**/.next/**')
args.push('--extensions=tsx,ts,jsx,js')
args = args.concat(['--transform', transformerPath])
if (flags.jscodeshift) {
args = args.concat(flags.jscodeshift)
}
args = args.concat(files)
console.log(`Executing command: jscodeshift ${args.join(' ')}`)
const result = execa.sync(jscodeshiftExecutable, args, {
stdio: 'inherit',
stripFinalNewline: false,
})
if (result.failed) {
throw new Error(`jscodeshift exited with code ${result.exitCode}`)
}
if (!dry && transformer === 'built-in-next-font') {
console.log('Uninstalling `@next/font`')
try {
uninstallPackage('@next/font')
} catch {
console.error(
"Couldn't uninstall `@next/font`, please uninstall it manually"
)
}
}
}
const TRANSFORMER_INQUIRER_CHOICES = [
{
name: 'name-default-component: Transforms anonymous components into named components to make sure they work with Fast Refresh',
value: 'name-default-component',
},
{
name: 'add-missing-react-import: Transforms files that do not import `React` to include the import in order for the new React JSX transform',
value: 'add-missing-react-import',
},
{
name: 'withamp-to-config: Transforms the withAmp HOC into Next.js 9 page configuration',
value: 'withamp-to-config',
},
{
name: 'url-to-withrouter: Transforms the deprecated automatically injected url property on top level pages to using withRouter',
value: 'url-to-withrouter',
},
{
name: 'cra-to-next (experimental): automatically migrates a Create React App project to Next.js',
value: 'cra-to-next',
},
{
name: 'new-link: Ensures your <Link> usage is backwards compatible.',
value: 'new-link',
},
{
name: 'next-og-import: Transforms imports from `next/server` to `next/og` for usage of Dynamic OG Image Generation.',
value: 'next-og-import',
},
{
name: 'metadata-to-viewport-export: Migrates certain viewport related metadata from the `metadata` export to a new `viewport` export.',
value: 'metadata-to-viewport-export',
},
{
name: 'next-dynamic-access-named-export: Transforms dynamic imports that return the named export itself to a module like object.',
value: 'next-dynamic-access-named-export',
},
{
name: 'next-image-to-legacy-image: safely migrate Next.js 10, 11, 12 applications importing `next/image` to the renamed `next/legacy/image` import in Next.js 13',
value: 'next-image-to-legacy-image',
},
{
name: 'next-image-experimental (experimental): dangerously migrates from `next/legacy/image` to the new `next/image` by adding inline styles and removing unused props',
value: 'next-image-experimental',
},
{
name: 'built-in-next-font: Uninstall `@next/font` and transform imports to `next/font`',
value: 'built-in-next-font',
},
]
function expandFilePathsIfNeeded(filesBeforeExpansion) {
const shouldExpandFiles = filesBeforeExpansion.some((file) =>
file.includes('*')
)
return shouldExpandFiles
? globby.sync(filesBeforeExpansion)
: filesBeforeExpansion
}
export function run() {
const cli = meow({
description: 'Codemods for updating Next.js apps.',
help: `
Usage
$ npx @next/codemod <transform> <path> <...options>
transform One of the choices from https://github.com/vercel/next.js/tree/canary/packages/next-codemod
path Files or directory to transform. Can be a glob like pages/**.js
Options
--force Bypass Git safety checks and forcibly run codemods
--dry Dry run (no changes are made to files)
--print Print transformed files to your terminal
--jscodeshift (Advanced) Pass options directly to jscodeshift
`,
flags: {
boolean: ['force', 'dry', 'print', 'help'],
string: ['_'],
alias: {
h: 'help',
},
},
} as meow.Options<meow.AnyFlags>)
if (!cli.flags.dry) {
checkGitStatus(cli.flags.force)
}
if (
cli.input[0] &&
!TRANSFORMER_INQUIRER_CHOICES.find((x) => x.value === cli.input[0])
) {
console.error('Invalid transform choice, pick one of:')
console.error(
TRANSFORMER_INQUIRER_CHOICES.map((x) => '- ' + x.value).join('\n')
)
process.exit(1)
}
inquirer
.prompt([
{
type: 'input',
name: 'files',
message: 'On which files or directory should the codemods be applied?',
when: !cli.input[1],
default: '.',
// validate: () =>
filter: (files) => files.trim(),
},
{
type: 'list',
name: 'transformer',
message: 'Which transform would you like to apply?',
when: !cli.input[0],
pageSize: TRANSFORMER_INQUIRER_CHOICES.length,
choices: TRANSFORMER_INQUIRER_CHOICES,
},
])
.then((answers) => {
const { files, transformer } = answers
const filesBeforeExpansion = cli.input[1] || files
const filesExpanded = expandFilePathsIfNeeded([filesBeforeExpansion])
const selectedTransformer = cli.input[0] || transformer
if (!filesExpanded.length) {
console.log(`No files found matching ${filesBeforeExpansion.join(' ')}`)
return null
}
return runTransform({
files: filesExpanded,
flags: cli.flags,
transformer: selectedTransformer,
})
})
}