Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
dc1dc5c
check-redirects: test that a removed docs URL needs a redirect
C-Mejlak Dec 4, 2026
70da41d
check-redirects: fail a removed docs URL without a redirect
C-Mejlak Dec 4, 2026
b78736f
check-redirects: test the command line against git revisions
C-Mejlak Dec 4, 2026
8fe0731
check-redirects: run the check from the command line
C-Mejlak Dec 4, 2026
0c1d28e
check-redirects: replay docs PRs #529 and #493
C-Mejlak Dec 4, 2026
db8a672
check-redirects: test R1 on nested routes and the exit code for warnings
C-Mejlak Dec 4, 2026
68df24b
check-redirects: test file names that contain a newline
C-Mejlak Dec 4, 2026
9921217
check-redirects: read commit files by object id
C-Mejlak Dec 4, 2026
fb8599d
check-redirects: test that the change's text never acts as a command
C-Mejlak Dec 4, 2026
95a2dab
check-redirects: keep the change's text from acting as a command
C-Mejlak Dec 4, 2026
44f75a1
check-redirects: test the redirect entry rules
C-Mejlak Dec 4, 2026
5866a6b
check-redirects: validate redirect entries
C-Mejlak Dec 4, 2026
5407317
check-redirects: test manifest integrity
C-Mejlak Dec 4, 2026
d924909
check-redirects: check that manifest paths exist and map to unique URLs
C-Mejlak Dec 4, 2026
30cde9a
check-redirects: test links to removed pages and non-pages
C-Mejlak Dec 4, 2026
bbcea00
check-redirects: check links to removed pages and non-pages
C-Mejlak Dec 4, 2026
8ab0977
check-redirects: replay a step-ci push and main
C-Mejlak Dec 4, 2026
83beee0
check-redirects: run the check and its tests in CI
C-Mejlak Dec 4, 2026
caa704e
Add an empty redirects list to the manifest
C-Mejlak Dec 4, 2026
30f2c95
Document how to remove, rename, or move a page
C-Mejlak Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 207 additions & 0 deletions .github/scripts/check-redirects.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
#!/usr/bin/env node
// Fails a docs change that makes a docs URL stop working without a redirect.
// Usage: node .github/scripts/check-redirects.mjs [--base <rev>] [--head <rev>]
// --base defaults to origin/main and --head to the working tree. The check
// compares the head with the merge base of the two.

import { execFileSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { appendFileSync, existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { parseArgs } from 'node:util'

import {
annotations,
inert,
plainText,
summary
} from './check-redirects/report.mjs'
import { checkRedirects } from './check-redirects/rules.mjs'

const USAGE =
'Usage: node .github/scripts/check-redirects.mjs [--base <rev>] [--head <rev>]'

// manifest.json and every .mdx file of a revision in one read.
const MAX_BUFFER = 512 * 1024 * 1024

/**
* Runs the check and reports it. Exits 1 on any error and 2 when it can't run.
*
* @param {string[]} argv - Arguments after the script name
* @param {NodeJS.ProcessEnv} [env]
* @returns {number} The exit code
*/
export function main(argv, env = process.env) {
// Output quotes text from the change. On a runner, only the annotations may
// be read as workflow commands.
const shown = (text) =>
env.GITHUB_ACTIONS === 'true' ? inert(text, randomUUID()) : text

let options
try {
options = parseArgs({
args: argv,
options: {
base: { type: 'string', default: 'origin/main' },
head: { type: 'string' }
}
}).values
} catch (err) {
console.error(shown(`${err.message}\n${USAGE}`))
return 2
}

let violations
try {
violations = runCheck({ cwd: process.cwd(), ...options })
} catch (err) {
const detail = err.stderr?.toString().trim() || err.message
console.error(
shown(`check-redirects couldn't read the revisions: ${detail}`)
)
return 2
}

if (env.GITHUB_ACTIONS === 'true') {
for (const line of annotations(violations)) console.log(line)
if (env.GITHUB_STEP_SUMMARY) {
appendFileSync(env.GITHUB_STEP_SUMMARY, summary(violations))
}
}
console.log(shown(plainText(violations)))
return violations.some(({ severity }) => severity === 'error') ? 1 : 0
}

/**
* Reads the base and head from git and checks them.
*
* @param {{ cwd: string, base: string, head?: string }} options - Git
* revisions. Without a head, the working tree is the head.
* @returns {import('./check-redirects/rules.mjs').Violation[]}
*/
export function runCheck({ cwd, base, head }) {
const root = git(cwd, 'rev-parse', '--show-toplevel').trim()
const mergeBase = git(root, 'merge-base', base, head ?? 'HEAD').trim()
return checkRedirects({
base: readCommit(root, mergeBase),
head: head ? readCommit(root, head) : readWorkingTree(root)
})
}

/**
* Reads a commit's file list, its manifest and its .mdx files.
*
* @param {string} root - The repository's top level
* @param {string} rev - Any git revision
* @returns {import('./check-redirects/rules.mjs').Revision}
*/
export function readCommit(root, rev) {
const commit = git(root, 'rev-parse', '--verify', `${rev}^{commit}`).trim()
const entries = git(root, 'ls-tree', '-r', '-z', '--full-tree', commit)
.split('\0')
.filter(Boolean)
.map(treeEntry)
const wanted = entries.filter(
({ type, path }) => type === 'blob' && isRead(path)
)
const texts = catFile(
root,
wanted.map(({ oid }) => oid)
)
const byPath = new Map(wanted.map(({ path }, index) => [path, texts[index]]))
return revision(
entries.map(({ path }) => path),
(path) => byPath.get(path)
)
}

/**
* Reads the working tree, including untracked files that aren't ignored.
*
* @param {string} root - The repository's top level
* @returns {import('./check-redirects/rules.mjs').Revision}
*/
export function readWorkingTree(root) {
const paths = git(
root,
'ls-files',
'-z',
'--cached',
'--others',
'--exclude-standard'
)
.split('\0')
.filter((path) => path && existsSync(join(root, path)))
return revision(paths, (path) => readFileSync(join(root, path), 'utf8'))
}

function revision(paths, read) {
const files = new Set(paths)
return {
manifestText: files.has('manifest.json') ? read('manifest.json') : null,
paths: files,
mdx: new Map(
[...files]
.filter((path) => path.endsWith('.mdx'))
.map((path) => [path, read(path)])
)
}
}

const isRead = (path) => path === 'manifest.json' || path.endsWith('.mdx')

// "<mode> <type> <oid>\t<path>". The path is stored as is and may contain a
// newline, so contents are requested by object id, never by path.
function treeEntry(entry) {
const tab = entry.indexOf('\t')
const [, type, oid] = entry.slice(0, tab).split(' ')
return { type, oid, path: entry.slice(tab + 1) }
}

// One git process per revision instead of one per file. Each answer must match
// its request, so no file can be handed another file's contents.
function catFile(root, oids) {
if (oids.length === 0) return []
const output = execFileSync('git', ['cat-file', '--batch'], {
cwd: root,
input: oids.join('\n') + '\n',
maxBuffer: MAX_BUFFER,
stdio: ['pipe', 'pipe', 'pipe']
})

const texts = []
let offset = 0
for (const oid of oids) {
const headerEnd = output.indexOf(0x0a, offset)
const [answer, type, size] = output
.toString('utf8', offset, headerEnd)
.split(' ')
if (answer !== oid || type !== 'blob' || !/^\d+$/.test(size)) {
throw new Error(`git cat-file didn't return blob ${oid}`)
}
offset = headerEnd + 1
texts.push(output.toString('utf8', offset, offset + Number(size)))
offset += Number(size) + 1
}
if (offset !== output.length) {
throw new Error('git cat-file returned more than was requested')
}
return texts
}

function git(cwd, ...args) {
return execFileSync('git', args, {
cwd,
encoding: 'utf8',
maxBuffer: MAX_BUFFER,
stdio: ['ignore', 'pipe', 'pipe']
})
}

if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
process.exitCode = main(process.argv.slice(2))
}
Loading
Loading