Unverified Commit 144fa5d4 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[15.5.x] Remove generated error codes (#97783)

Co-authored-by: 's avatarJiwon Choi <devjiwonchoi@gmail.com>
parent ddd94f0a
...@@ -7,6 +7,3 @@ packages/next/compiled/** -text linguist-vendored ...@@ -7,6 +7,3 @@ packages/next/compiled/** -text linguist-vendored
# Make next/src/build folder indexable for github search # Make next/src/build folder indexable for github search
build/** linguist-generated=false build/** linguist-generated=false
# Custom merge driver for auto-generated errors.json
packages/next/errors.json merge=errors-json
...@@ -75,8 +75,6 @@ ...@@ -75,8 +75,6 @@
"swc-build-wasm": "tsx scripts/build-wasm.cjs", "swc-build-wasm": "tsx scripts/build-wasm.cjs",
"build-turbopack-cli": "cargo build -p turbopack-cli --release", "build-turbopack-cli": "cargo build -p turbopack-cli --release",
"sweep": "tsx scripts/sweep.cjs", "sweep": "tsx scripts/sweep.cjs",
"check-error-codes": "node packages/next/check-error-codes.js",
"update-error-codes": "cd packages/next && pnpm taskr compile check_error_codes",
"build-error-code-plugin": "crates/next-error-code-swc-plugin/build-and-move.sh", "build-error-code-plugin": "crates/next-error-code-swc-plugin/build-and-move.sh",
"storybook": "turbo run storybook", "storybook": "turbo run storybook",
"build-storybook": "turbo run build-storybook", "build-storybook": "turbo run build-storybook",
......
const os = require('os')
const path = require('path')
const fs = require('fs/promises')
const errorsDir = path.join(__dirname, '.errors')
// This script checks for new error codes in .errors directory and consolidates them into errors.json.
// It will fail if new error codes are found, after consolidating them, to ensure error codes are
// properly reviewed and committed.
async function main() {
// Check if .errors directory exists
try {
await fs.access(errorsDir)
} catch {
process.exit(0)
}
let existingErrors = {}
// Load existing errors.json if it exists
try {
existingErrors = JSON.parse(
await fs.readFile(path.join(__dirname, 'errors.json'), 'utf8')
)
} catch {
// Start fresh if errors.json doesn't exist
}
// Calculate next error code
const nextInitialCode =
Object.keys(existingErrors).length > 0
? Math.max(...Object.keys(existingErrors).map(Number)) + 1
: 1
// Process new error files
const errorFiles = [...(await fs.readdir(errorsDir))].map((file) =>
path.join(errorsDir, file)
)
let newErrorCount = 0
for (const file of errorFiles) {
const { errorMessage } = JSON.parse(await fs.readFile(file, 'utf8'))
// Check if message already exists
const existingCode = Object.entries(existingErrors).find(
([_, msg]) => msg === errorMessage
)?.[0]
if (!existingCode) {
// Only add if message is new
const code = nextInitialCode + newErrorCount
existingErrors[code] = errorMessage
newErrorCount++
}
}
// Write updated errors and cleanup
await fs.writeFile(
path.join(__dirname, 'errors.json'),
JSON.stringify(existingErrors, null, 2) +
// Formatters would add these anyway
os.EOL
)
await fs.rm(errorsDir, { recursive: true, force: true })
process.exit(1)
}
main().catch(console.error)
...@@ -6,7 +6,6 @@ const fs = require('fs/promises') ...@@ -6,7 +6,6 @@ const fs = require('fs/promises')
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
const resolveFrom = require('resolve-from') const resolveFrom = require('resolve-from')
const execa = require('execa') const execa = require('execa')
const process = require('process')
const recast = require('recast') const recast = require('recast')
export async function next__polyfill_nomodule(task, opts) { export async function next__polyfill_nomodule(task, opts) {
...@@ -2785,10 +2784,7 @@ export async function diagnostics(task, opts) { ...@@ -2785,10 +2784,7 @@ export async function diagnostics(task, opts) {
} }
export async function build(task, opts) { export async function build(task, opts) {
await task.serial( await task.serial(['precompile', 'compile', 'generate_types'], opts)
['precompile', 'compile', 'check_error_codes', 'generate_types'],
opts
)
} }
export async function generate_types(task, opts) { export async function generate_types(task, opts) {
...@@ -2809,25 +2805,6 @@ export async function generate_types(task, opts) { ...@@ -2809,25 +2805,6 @@ export async function generate_types(task, opts) {
} }
} }
export async function check_error_codes(task, opts) {
try {
await execa.command('pnpm -w run check-error-codes', {
stdio: 'inherit',
})
} catch (err) {
if (process.env.CI) {
await execa.command(
'echo check_error_codes FAILED: There are new errors introduced but no corresponding error codes are found in errors.json file, so make sure you run `pnpm build` or `pnpm update-error-codes` and then commit the change in errors.json.',
{
stdio: 'inherit',
}
)
process.exit(1)
}
await task.start('compile', opts)
}
}
export default async function (task) { export default async function (task) {
const opts = { dev: true } const opts = { dev: true }
await task.clear('dist') await task.clear('dist')
......
#!/bin/sh
driver_name='errors-json'
git config merge."$driver_name".name 'Automatically merge packages/next/errors.json'
git config merge."$driver_name".driver 'node scripts/merge-errors-json/merge.mjs %A %O %B'
// @ts-check
/**
* Git merge driver for packages/next/errors.json
*
* This script automatically resolves merge conflicts in the auto-generated
* errors.json file by reassigning error codes to avoid conflicts.
*
* Usage: node merge-errors-json.mjs <current> <base> <other> [<marker-size>]
*
* Arguments:
* - current: Path to the current version (our changes)
* - base: Path to the common ancestor version
* - other: Path to the other version (their changes)
* - marker-size: Size of conflict markers (optional, defaults to 7)
*
* Exit codes:
* - 0: Merge successful, result written to current file
* - 1: Merge failed, conflicts remain
*/
import { readFileSync, writeFileSync } from 'node:fs'
function main() {
const args = process.argv.slice(2)
if (args.length < 3) {
console.error(
'Usage: node merge-errors-json.mjs <current> <base> <other> [<marker-size>]'
)
process.exit(1)
}
const [currentPath, basePath, otherPath] = args
try {
const base = readJsonSync(basePath)
const current = readJsonSync(currentPath)
const other = readJsonSync(otherPath)
const merged = mergeErrors(base, current, other)
// Git expects the result to be written to the "current" file
writeJsonSync(currentPath, merged)
const addedCount = Object.keys(merged).length - Object.keys(current).length
console.error(
`merge-errors-json: added ${addedCount === 1 ? '1 new message' : `${addedCount} new messages`} to errors.json`
)
process.exit(0)
} catch (error) {
console.error('merge-errors-json: merge failed:', error.message)
process.exit(1)
}
}
/**
* @typedef {Record<string, string>} ErrorsMap
*/
/**
* Merge three versions of errors.json, resolving conflicts by assigning new sequential IDs
* @param {ErrorsMap} base - Base version (common ancestor)
* @param {ErrorsMap} current - Current version (our changes, or the state of the branch we're rebasing onto)
* @param {ErrorsMap} other - Other version (their changes, or the state the branch we're rebasing, a.k.a. "incoming")
* @returns {ErrorsMap}
*/
function mergeErrors(base, current, other) {
/** @type {ErrorsMap} */
const result = { ...current }
/** @type {Set<string>} */
const existingMessages = new Set(Object.values(result))
let nextKey = Object.keys(result).length + 1
for (const message of getNewMessages(base, other)) {
if (existingMessages.has(message)) {
continue
}
const key = nextKey++
result[key] = message
existingMessages.add(message)
}
return result
}
function getNewMessages(
/** @type {ErrorsMap} */ prev,
/** @type {ErrorsMap} */ current
) {
const existing = new Set(Object.values(prev))
return Object.values(current).filter((msg) => !existing.has(msg))
}
function readJsonSync(/** @type {string} */ filePath) {
const content = readFileSync(filePath, 'utf8')
return JSON.parse(content)
}
function writeJsonSync(
/** @type {string} */ filePath,
/** @type {any} */ value
) {
const content = JSON.stringify(value, null, 2) + '\n'
writeFileSync(filePath, content, 'utf8')
}
main()
import { mkdtempSync, rmSync } from 'fs'
import { writeJSONSync, readJSONSync } from 'fs-extra'
import { join } from 'path'
import { tmpdir } from 'os'
import execa from 'execa'
describe('merge-errors-json driver', () => {
it('should correctly merge errors.json files with conflicting new entries', async () => {
const base = {
'1': 'Original message 1',
'2': 'Original message 2',
}
const current = {
...base,
'3': 'From a conflicting branch that was merged first 1',
'4': 'From a conflicting branch that was merged first 2',
}
const rebased = await simulateRebase({
base,
current,
incoming: {
...base,
'3': 'From our branch 1',
'4': 'From our branch 2',
},
})
expect(rebased).toEqual({
...current,
'5': 'From our branch 1',
'6': 'From our branch 2',
})
})
it('should handle empty base file', async () => {
const base = {}
const current = {
'1': 'Message from a conflicting branch that was merged first',
}
const rebased = await simulateRebase({
base,
current,
incoming: { '1': 'New message from our branch' },
})
expect(rebased).toEqual({
...current,
'2': 'New message from our branch',
})
})
it('should handle stacked PRs', async () => {
const base = {
'1': 'Original message 1',
'2': 'Original message 2',
}
const current = {
...base,
'3': 'Message from a conflicting branch that was merged first',
}
const ourBranch1 = {
...base,
'3': 'New message from our-branch-1',
}
const ourBranch2 = {
...ourBranch1,
'4': 'New message from our-branch-2', // will conflict after our-branch-1 is rebased and its error is renumbered to 4
}
const branch1Rebased = await simulateRebase({
base: base,
current: current,
incoming: ourBranch1,
})
expect(branch1Rebased).toEqual({
...current,
'4': 'New message from our-branch-1',
})
const branch2Rebased = await simulateRebase({
base: ourBranch1,
current: branch1Rebased,
incoming: ourBranch2,
})
expect(branch2Rebased).toEqual({
...branch1Rebased,
'5': 'New message from our-branch-2',
})
})
})
type Contents = Record<string, string>
async function simulateRebase({
base,
current,
incoming,
}: {
base: Contents
current: Contents
incoming: Contents
}) {
const tempDir = mkdtempSync(join(tmpdir(), 'merge-driver-test-'))
const paths = {
base: join(tempDir, 'base.json'),
current: join(tempDir, 'current.json'),
other: join(tempDir, 'other.json'),
}
writeJSONSync(paths.base, base, { spaces: 2 })
// during a rebase, the branch we're rebasing onto will be "current", and our commit will be "other"
writeJSONSync(paths.current, current, { spaces: 2 })
writeJSONSync(paths.other, incoming, { spaces: 2 })
await execa('node', [
'scripts/merge-errors-json/merge.mjs',
paths.current,
paths.base,
paths.other,
])
const result = readJSONSync(paths.current)
rmSync(tempDir, { recursive: true, force: true })
return result
}
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