Commit 0c092d11 authored by Ben Gubler's avatar Ben Gubler

feat [Next 16]: remove 'next lint' command

parent 0a90014c
......@@ -26,15 +26,14 @@ The following options are available:
The following commands are available:
| Command | Description |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more. |
| [`build`](#next-build-options) | Creates an optimized production build of your application. Displaying information about each route. |
| [`start`](#next-start-options) | Starts Next.js in production mode. The application should be compiled with `next build` first. |
| [`info`](#next-info-options) | Prints relevant details about the current system which can be used to report Next.js bugs. |
| [`lint`](#next-lint-options) | Runs ESLint for all files in the `/src`, `/app`, `/pages`, `/components`, and `/lib` directories. It also provides a guided setup to install any required dependencies if ESLint it is not already configured in your application. |
| [`telemetry`](#next-telemetry-options) | Allows you to enable or disable Next.js' completely anonymous telemetry collection. |
| [`typegen`](#next-typegen-options) | Generates TypeScript definitions for routes, pages, layouts, and route handlers without running a full build. |
| Command | Description |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more. |
| [`build`](#next-build-options) | Creates an optimized production build of your application. Displaying information about each route. |
| [`start`](#next-start-options) | Starts Next.js in production mode. The application should be compiled with `next build` first. |
| [`info`](#next-info-options) | Prints relevant details about the current system which can be used to report Next.js bugs. |
| [`telemetry`](#next-telemetry-options) | Allows you to enable or disable Next.js' completely anonymous telemetry collection. |
| [`typegen`](#next-typegen-options) | Generates TypeScript definitions for routes, pages, layouts, and route handlers without running a full build. |
> **Good to know**: Running `next` without a command is an alias for `next dev`.
......
......@@ -16,7 +16,6 @@ import {
} from '../cli/next-test.js'
import type { NextTelemetryOptions } from '../cli/next-telemetry.js'
import type { NextStartOptions } from '../cli/next-start.js'
import type { NextLintOptions } from '../cli/next-lint.js'
import type { NextInfoOptions } from '../cli/next-info.js'
import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextBuildOptions } from '../cli/next-build.js'
......@@ -237,94 +236,6 @@ program
import('../cli/next-info.js').then((mod) => mod.nextInfo(options))
)
program
.command('lint')
.description(
'Runs ESLint for all files in the `/src`, `/app`, `/pages`, `/components`, and `/lib` directories. It also provides a guided setup to install any required dependencies if ESLint is not already configured in your application.'
)
.argument(
'[directory]',
`A base directory on which to lint the application. ${italic(
'If no directory is provided, the current directory will be used.'
)}`
)
.option(
'-d, --dir, <dirs...>',
'Include directory, or directories, to run ESLint.'
)
.option('--file, <files...>', 'Include file, or files, to run ESLint.')
.addOption(
new Option(
'--ext, [exts...]',
'Specify JavaScript file extensions.'
).default(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'])
)
.option(
'-c, --config, <config>',
'Uses this configuration file, overriding all other configuration options.'
)
.option(
'--resolve-plugins-relative-to, <rprt>',
'Specify a directory where plugins should be resolved from.'
)
.option(
'--strict',
'Creates a `.eslintrc.json` file using the Next.js strict configuration.'
)
.option(
'--rulesdir, <rulesdir...>',
'Uses additional rules from this directory(s).'
)
.option('--fix', 'Automatically fix linting issues.')
.option(
'--fix-type <fixType>',
'Specify the types of fixes to apply (e.g., problem, suggestion, layout).'
)
.option('--ignore-path <path>', 'Specify a file to ignore.')
.option('--no-ignore', 'Disables the `--ignore-path` option.')
.option('--quiet', 'Reports errors only.')
.addOption(
new Option(
'--max-warnings [maxWarnings]',
'Specify the number of warnings before triggering a non-zero exit code.'
)
.argParser(parseValidPositiveInteger)
.default(-1)
)
.option(
'-o, --output-file, <outputFile>',
'Specify a file to write report to.'
)
.option('-f, --format, <format>', 'Uses a specific output format.')
.option(
'--no-inline-config',
'Prevents comments from changing config or rules.'
)
.addOption(
new Option(
'--report-unused-disable-directives-severity <level>',
'Specify severity level for unused eslint-disable directives.'
).choices(['error', 'off', 'warn'])
)
.option('--no-cache', 'Disables caching.')
.option('--cache-location, <cacheLocation>', 'Specify a location for cache.')
.addOption(
new Option(
'--cache-strategy, [cacheStrategy]',
'Specify a strategy to use for detecting changed files in the cache.'
).default('metadata')
)
.option(
'--error-on-unmatched-pattern',
'Reports errors when any file patterns are unmatched.'
)
.action((directory: string, options: NextLintOptions) =>
import('../cli/next-lint.js').then((mod) =>
mod.nextLint(options, directory)
)
)
.usage('[directory] [options]')
program
.command('start')
.description(
......
#!/usr/bin/env node
import { existsSync } from 'fs'
import { isAbsolute, join } from 'path'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import { Telemetry } from '../telemetry/storage'
import { green, yellow, bold } from '../lib/picocolors'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import { CompileError } from '../lib/compile-error'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { eventLintCheckCompleted } from '../telemetry/events'
import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup'
export type NextLintOptions = {
cache: boolean
cacheLocation?: string
cacheStrategy: string
config?: string
dir?: string[]
errorOnUnmatchedPattern?: boolean
file?: string[]
fix?: boolean
fixType?: string
format?: string
ignore: boolean
outputFile?: string
quiet?: boolean
strict?: boolean
// TODO(jiwon): ESLint v9 unsupported options
// we currently delete them at `runLintCheck` when used in v9
ext: string[]
ignorePath?: string
reportUnusedDisableDirectivesSeverity: 'error' | 'off' | 'warn'
resolvePluginsRelativeTo?: string
rulesdir?: string
inlineConfig: boolean
maxWarnings: number
}
const eslintOptions = (
options: NextLintOptions,
defaultCacheLocation: string
) => ({
overrideConfigFile: options.config || null,
extensions: options.ext ?? [],
resolvePluginsRelativeTo: options.resolvePluginsRelativeTo || null,
rulePaths: options.rulesdir ?? [],
fix: options.fix ?? false,
fixTypes: options.fixType ?? null,
ignorePath: options.ignorePath || null,
ignore: options.ignore,
allowInlineConfig: options.inlineConfig,
reportUnusedDisableDirectives:
options.reportUnusedDisableDirectivesSeverity || null,
cache: options.cache,
cacheLocation: options.cacheLocation || defaultCacheLocation,
cacheStrategy: options.cacheStrategy,
errorOnUnmatchedPattern: options.errorOnUnmatchedPattern ?? false,
})
const nextLint = async (options: NextLintOptions, directory?: string) => {
// Show deprecation warning
console.warn(
yellow('`next lint` is deprecated and will be removed in Next.js 16.\n') +
'For new projects, use ' +
bold('create-next-app') +
' to choose your preferred linter.\n' +
'For existing projects, migrate to the ESLint CLI:\n' +
bold('npx @next/codemod@canary next-lint-to-eslint-cli .') +
'\n'
)
const baseDir = getProjectDir(directory)
// Check if the provided directory exists
if (!existsSync(baseDir)) {
printAndExit(`> No such directory exists as the project root: ${baseDir}`)
}
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
const files = options.file ?? []
const dirs = options.dir ?? nextConfig.eslint?.dirs
const filesToLint = [...(dirs ?? []), ...files]
const pathsToLint = (
filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS
).reduce((res: string[], d: string) => {
const currDir = isAbsolute(d) ? d : join(baseDir, d)
if (!existsSync(currDir)) {
return res
}
res.push(currDir)
return res
}, [])
const reportErrorsOnly = Boolean(options.quiet)
const maxWarnings = options.maxWarnings
const formatter = options.format || null
const strict = Boolean(options.strict)
const outputFile = options.outputFile || null
const distDir = join(baseDir, nextConfig.distDir)
const defaultCacheLocation = join(distDir, 'cache', 'eslint/')
const { pagesDir, appDir } = findPagesDir(baseDir)
await verifyTypeScriptSetup({
dir: baseDir,
distDir: nextConfig.distDir,
intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
})
runLintCheck(baseDir, pathsToLint, {
lintDuringBuild: false,
eslintOptions: eslintOptions(options, defaultCacheLocation),
reportErrorsOnly,
maxWarnings,
formatter,
outputFile,
strict,
})
.then(async (lintResults) => {
const lintOutput =
typeof lintResults === 'string' ? lintResults : lintResults?.output
if (typeof lintResults !== 'string' && lintResults?.eventInfo) {
const telemetry = new Telemetry({
distDir,
})
telemetry.record(
eventLintCheckCompleted({
...lintResults.eventInfo,
buildLint: false,
})
)
await telemetry.flush()
}
if (
typeof lintResults !== 'string' &&
lintResults?.isError &&
lintOutput
) {
throw new CompileError(lintOutput)
}
if (lintOutput) {
printAndExit(lintOutput, 0)
} else if (lintResults && !lintOutput) {
printAndExit(green('✔ No ESLint warnings or errors'), 0)
} else {
// this makes sure we exit 1 after the error from line 116
// in packages/next/src/lib/eslint/runLintCheck
process.exit(1)
}
})
.catch((err) => {
printAndExit(err.message)
})
}
export { nextLint }
import { bold, cyan, gray, red, yellow } from '../picocolors'
import path from 'path'
// eslint-disable-next-line no-shadow
export enum MessageSeverity {
Warning = 1,
Error = 2,
}
interface LintMessage {
ruleId: string | null
severity: 1 | 2
message: string
line: number
column: number
}
export interface LintResult {
filePath: string
messages: LintMessage[]
errorCount: number
warningCount: number
output?: string
source?: string
}
function pluginCount(messages: LintMessage[]): {
nextPluginErrorCount: number
nextPluginWarningCount: number
} {
let nextPluginWarningCount = 0
let nextPluginErrorCount = 0
for (let i = 0; i < messages.length; i++) {
const { severity, ruleId } = messages[i]
if (ruleId?.includes('@next/next')) {
if (severity === MessageSeverity.Warning) {
nextPluginWarningCount += 1
} else {
nextPluginErrorCount += 1
}
}
}
return {
nextPluginErrorCount,
nextPluginWarningCount,
}
}
function formatMessage(
dir: string,
messages: LintMessage[],
filePath: string
): string {
let fileName = path.posix.normalize(
path.relative(dir, filePath).replace(/\\/g, '/')
)
if (!fileName.startsWith('.')) {
fileName = './' + fileName
}
let output = '\n' + cyan(fileName)
for (let i = 0; i < messages.length; i++) {
const { message, severity, line, column, ruleId } = messages[i]
output = output + '\n'
if (line && column) {
output =
output +
yellow(line.toString()) +
':' +
yellow(column.toString()) +
' '
}
if (severity === MessageSeverity.Warning) {
output += yellow(bold('Warning')) + ': '
} else {
output += red(bold('Error')) + ': '
}
output += message
if (ruleId) {
output += ' ' + gray(bold(ruleId))
}
}
return output
}
export async function formatResults(
baseDir: string,
results: LintResult[],
format: (r: LintResult[]) => string | Promise<string>
): Promise<{
output: string
outputWithMessages: string
totalNextPluginErrorCount: number
totalNextPluginWarningCount: number
}> {
let totalNextPluginErrorCount = 0
let totalNextPluginWarningCount = 0
let resultsWithMessages = results.filter(({ messages }) => messages?.length)
// Track number of Next.js plugin errors and warnings
resultsWithMessages.forEach(({ messages }) => {
const res = pluginCount(messages)
totalNextPluginErrorCount += res.nextPluginErrorCount
totalNextPluginWarningCount += res.nextPluginWarningCount
})
// Use user defined formatter or Next.js's built-in custom formatter
const output = format
? await format(resultsWithMessages)
: resultsWithMessages
.map(({ messages, filePath }) =>
formatMessage(baseDir, messages, filePath)
)
.join('\n')
return {
output: output,
outputWithMessages:
resultsWithMessages.length > 0
? output +
`\n\n${cyan(
'info'
)} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/app/api-reference/config/eslint#disabling-rules`
: '',
totalNextPluginErrorCount,
totalNextPluginWarningCount,
}
}
import findUp from 'next/dist/compiled/find-up'
export const getESLintStrictValue = async (cwd: string) => {
const tsConfigLocation = await findUp('tsconfig.json', { cwd })
const hasTSConfig = tsConfigLocation !== undefined
return {
title: 'Strict',
recommended: true,
config: {
extends: hasTSConfig
? ['next/core-web-vitals', 'next/typescript']
: 'next/core-web-vitals',
},
}
}
export const getESLintPromptValues = async (cwd: string) => {
return [
await getESLintStrictValue(cwd),
{
title: 'Base',
config: {
extends: 'next',
},
},
{
title: 'Cancel',
config: null,
},
]
}
import { promises as fs } from 'fs'
export type ConfigAvailable = {
exists: boolean
emptyEslintrc?: boolean
emptyPkgJsonConfig?: boolean
firstTimeSetup?: true
}
export async function hasEslintConfiguration(
eslintrcFile: string | null,
packageJsonConfig: { eslintConfig: any } | null
): Promise<ConfigAvailable> {
const configObject = {
exists: false,
emptyEslintrc: false,
emptyPkgJsonConfig: false,
}
if (eslintrcFile) {
const content = await fs.readFile(eslintrcFile, { encoding: 'utf8' }).then(
(txt) => txt.trim().replace(/\n/g, ''),
() => null
)
if (
content === '' ||
content === '{}' ||
content === '---' ||
content === 'module.exports = {}'
) {
configObject.emptyEslintrc = true
} else {
configObject.exists = true
}
} else if (packageJsonConfig?.eslintConfig) {
if (Object.keys(packageJsonConfig.eslintConfig).length) {
configObject.exists = true
} else {
configObject.emptyPkgJsonConfig = true
}
}
return configObject
}
This diff is collapsed.
import { promises as fs } from 'fs'
import { bold, green } from '../picocolors'
import os from 'os'
import path from 'path'
import * as CommentJson from 'next/dist/compiled/comment-json'
import type { ConfigAvailable } from './hasEslintConfiguration'
import * as Log from '../../build/output/log'
export async function writeDefaultConfig(
baseDir: string,
{ exists, emptyEslintrc, emptyPkgJsonConfig }: ConfigAvailable,
selectedConfig: any,
eslintrcFile: string | null,
pkgJsonPath: string | null,
packageJsonConfig: { eslintConfig: any } | null
) {
if (!exists && emptyEslintrc && eslintrcFile) {
const ext = path.extname(eslintrcFile)
let newFileContent
if (ext === '.yaml' || ext === '.yml') {
newFileContent = "extends: 'next'"
} else {
newFileContent = CommentJson.stringify(selectedConfig, null, 2)
if (ext === '.js') {
newFileContent = 'module.exports = ' + newFileContent
}
}
await fs.writeFile(eslintrcFile, newFileContent + os.EOL)
Log.info(
`We detected an empty ESLint configuration file (${bold(
path.basename(eslintrcFile)
)}) and updated it for you!`
)
} else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {
packageJsonConfig.eslintConfig = selectedConfig
if (pkgJsonPath)
await fs.writeFile(
pkgJsonPath,
CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL
)
Log.info(
`We detected an empty ${bold(
'eslintConfig'
)} field in package.json and updated it for you!`
)
} else if (!exists) {
await fs.writeFile(
path.join(baseDir, '.eslintrc.json'),
CommentJson.stringify(selectedConfig, null, 2) + os.EOL
)
console.log(
green(
`We created the ${bold(
'.eslintrc.json'
)} file for you and included your selected configuration.`
)
)
}
}
import { promises as fs } from 'fs'
import path from 'path'
import * as Log from '../../build/output/log'
import isError from '../../lib/is-error'
/**
* Check if a given file path is a directory or not.
* Returns `true` if the path is a directory.
*/
function isDirectory(
/** The path to a file to check. */
filePath: string
): Promise<boolean> {
return fs
.stat(filePath)
.then((stat) => stat.isDirectory())
.catch((error) => {
if (
isError(error) &&
(error.code === 'ENOENT' || error.code === 'ENOTDIR')
) {
return false
}
throw error
})
}
/**
* Create a file with eslint output data
*/
export async function writeOutputFile(
/** The name file that needs to be created */
outputFile: string,
/** The data that needs to be inserted into the file */
outputData: string
): Promise<void> {
const filePath = path.resolve(process.cwd(), outputFile)
if (await isDirectory(filePath)) {
Log.error(
`Cannot write to output file path, it is a directory: ${filePath}`
)
} else {
try {
await fs.mkdir(path.dirname(filePath), { recursive: true })
await fs.writeFile(filePath, outputData)
Log.info(`The output file has been created: ${filePath}`)
} catch (err) {
Log.error(`There was a problem writing the output file: ${filePath}`)
console.error(err)
}
}
}
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