From dd024c4db5b3cbdf950f8ab7b35bc4fc77a62774 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 23:13:29 +0100 Subject: [PATCH] feat(pr-checks): frozen-files fails a pull request that changes a file frozen on the base branch frozen-files (PQ2) matches the changed files against the globs of the new frozen-files input, such as applied migrations: modifying, renaming or deleting one needs the owner's approval or the approved-exception label, as a lint exception does. The approval moves to PullRequest, which both checks share. --- .github/pr-checks/frozen-files.js | 77 ++++++++++++++++++++++++++ .github/pr-checks/frozen-files.test.js | 70 +++++++++++++++++++++++ .github/pr-checks/inputs.js | 3 + .github/pr-checks/lint-exceptions.js | 14 +---- .github/pr-checks/pull-request.js | 32 +++++++++-- .github/pr-checks/run.js | 1 + .github/workflows/pr-checks.yml | 5 ++ crates/sourceorigin-standard/README.md | 8 +++ 8 files changed, 194 insertions(+), 16 deletions(-) create mode 100644 .github/pr-checks/frozen-files.js create mode 100644 .github/pr-checks/frozen-files.test.js diff --git a/.github/pr-checks/frozen-files.js b/.github/pr-checks/frozen-files.js new file mode 100644 index 0000000..0e44575 --- /dev/null +++ b/.github/pr-checks/frozen-files.js @@ -0,0 +1,77 @@ +'use strict'; + +const { APPROVED } = require('./pull-request.js'); + +/** What a pull request does to a file, by the status `pulls.listFiles` + * gives it; an added or copied file is new, so it isn't frozen yet. */ +const CHANGES = { modified: 'modifies', changed: 'changes the mode of', removed: 'deletes', renamed: 'renames' }; + +/** + * PQ2: a file matching a glob of the `frozen-files` input that exists on + * the base branch, such as an applied migration, is not modified, renamed + * or deleted. A deliberate change needs the same approval as a lint + * exception. Only a pull request can check it: on `main` there is nothing + * to compare with. + */ +const frozenFiles = { + name: 'frozen-files', + + async findings(pr, inputs) { + if (inputs.frozenFiles.length === 0) return []; + const globs = inputs.frozenFiles.map((glob) => [glob, frozenFiles.pattern(glob)]); + const findings = []; + for (const { path, previous, status } of await pr.files()) { + const verb = CHANGES[status]; + const before = previous ?? path; + const [glob] = globs.find(([, pattern]) => pattern.test(before)) ?? []; + if (!verb || !glob) continue; + findings.push({ + path: before, + message: + `this ${verb} a frozen file (\`${glob}\` in the \`frozen-files\` input), which never ` + + `changes once on the base branch: put the change in a new file instead, such as a new ` + + `migration. A deliberate change needs the owner's approving review of the latest commit, ` + + `or the \`${APPROVED}\` label.`, + }); + } + return findings; + }, + + async waiver(pr, inputs) { + return pr.approval(inputs.approvers); + }, + + /** A glob as a regular expression, as picomatch reads it with dotfiles: + * `**` spans directories, `*` and `?` stay within one, `{a,b}` is either + * and `[…]` a class. */ + pattern(glob) { + let source = ''; + let braces = 0; + for (let i = 0; i < glob.length; i += 1) { + const c = glob[i]; + if (glob.startsWith('**/', i)) { + source += '(?:.*/)?'; + i += 2; + } else if (glob.startsWith('**', i)) { + source += '.*'; + i += 1; + } else if (c === '*') source += '[^/]*'; + else if (c === '?') source += '[^/]'; + else if (c === '{') { + source += '(?:'; + braces += 1; + } else if (c === '}' && braces > 0) { + source += ')'; + braces -= 1; + } else if (c === ',' && braces > 0) source += '|'; + else if (c === '[') { + const end = glob.indexOf(']', i + 1); + source += end < 0 ? '\\[' : glob.slice(i, end + 1).replace(/^\[!/, '[^'); + if (end >= 0) i = end; + } else source += c.replace(/[.+^$()|\\]/g, '\\$&'); + } + return new RegExp(`^${source}$`); + }, +}; + +module.exports = frozenFiles; diff --git a/.github/pr-checks/frozen-files.test.js b/.github/pr-checks/frozen-files.test.js new file mode 100644 index 0000000..1347fba --- /dev/null +++ b/.github/pr-checks/frozen-files.test.js @@ -0,0 +1,70 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const frozenFiles = require('./frozen-files.js'); +const { Inputs } = require('./inputs.js'); +const { Fake } = require('./testing.js'); + +const frozen = 'crates/*/migrations/*.sql'; +const findings = async (changed, globs = frozen) => + frozenFiles.findings(await Fake.pr({}, { changed }), new Inputs(JSON.stringify({ 'frozen-files': globs }), [])); +const file = (filename, status, previous_filename) => ({ filename, status, previous_filename }); + +test('modifying, deleting or renaming a frozen file fails at its old path', async () => { + const result = await findings([ + file('crates/db/migrations/0001_init.sql', 'modified'), + file('crates/db/migrations/0002_users.sql', 'removed'), + file('crates/db/migrations/0004_users.sql', 'renamed', 'crates/db/migrations/0003_users.sql'), + ]); + assert.deepEqual( + result.map(({ path, message }) => `${path} ${message.split(' (')[0]}`), + [ + 'crates/db/migrations/0001_init.sql this modifies a frozen file', + 'crates/db/migrations/0002_users.sql this deletes a frozen file', + 'crates/db/migrations/0003_users.sql this renames a frozen file', + ], + ); + assert.match(result[0].message, /put the change in a new file instead.*`approved-exception` label/); +}); + +test('adding a frozen file, or changing another, passes', async () => { + const changed = [ + file('crates/db/migrations/0005_new.sql', 'added'), + file('crates/db/src/lib.rs', 'modified'), + file('crates/db/migrations/README.md', 'modified'), + file('crates/db/migrations/0006.sql', 'renamed', 'crates/db/schema.sql'), + ]; + assert.deepEqual(await findings(changed), []); +}); + +test('a repository without frozen files passes', async () => { + assert.deepEqual(await findings([file('crates/db/migrations/0001_init.sql', 'removed')], ''), []); +}); + +test('globs read as picomatch reads them', () => { + const cases = [ + ['crates/*/migrations/*.sql', 'crates/db/migrations/1.sql', true], + ['crates/*/migrations/*.sql', 'crates/db/x/migrations/1.sql', false], + ['**/migrations/**', 'migrations/a/b.sql', true], + ['**/migrations/**', 'crates/db/migrations/a.sql', true], + ['snapshots/*.{json,ron}', 'snapshots/a.ron', true], + ['snapshots/*.{json,ron}', 'snapshots/a.toml', false], + ['data/[!x]?.bin', 'data/ab.bin', true], + ['data/[!x]?.bin', 'data/xb.bin', false], + ['.config/*.toml', '.config/a.toml', true], + ['a.b', 'axb', false], + ['{a,b}/c,d', 'a/c,d', true], + ]; + for (const [glob, path, matches] of cases) { + assert.equal(frozenFiles.pattern(glob).test(path), matches, `${glob} ${path}`); + } +}); + +test("a deliberate change stands with the owner's approval or the label", async () => { + const inputs = new Inputs(JSON.stringify({ approvers: 'owner' }), []); + const reviews = [{ user: { login: 'owner' }, state: 'APPROVED', commit_id: 'head' }]; + assert.equal(await frozenFiles.waiver(await Fake.pr({}, { reviews }), inputs), 'owner approved the latest commit'); + assert.match(await frozenFiles.waiver(await Fake.pr({ labels: [{ name: 'approved-exception' }] }), inputs), /label/); + assert.equal(await frozenFiles.waiver(await Fake.pr(), inputs), undefined); +}); diff --git a/.github/pr-checks/inputs.js b/.github/pr-checks/inputs.js index ebf195d..52c5d53 100644 --- a/.github/pr-checks/inputs.js +++ b/.github/pr-checks/inputs.js @@ -20,6 +20,9 @@ class Inputs { /** Whether an unapproved lint exception fails the job, or is only * reported, as a repository adopting the check starts. */ this.enforceLintExceptions = inputs['enforce-lint-exceptions'] ?? true; + /** Globs of the files that never change once on the base branch, such + * as applied migrations. */ + this.frozenFiles = Inputs.list(inputs['frozen-files']); /** Each check the repository departs from, with its reason. */ this.deviations = new Map(); for (const { table, key, value, line } of new Toml(inputs.deviations ?? '').entries) { diff --git a/.github/pr-checks/lint-exceptions.js b/.github/pr-checks/lint-exceptions.js index 6f510ba..86c297f 100644 --- a/.github/pr-checks/lint-exceptions.js +++ b/.github/pr-checks/lint-exceptions.js @@ -1,5 +1,6 @@ 'use strict'; +const { APPROVED } = require('./pull-request.js'); const { Toml } = require('./toml.js'); /** The repository's ceilings of `#[expect]` attributes and `// INVARIANT:` @@ -9,9 +10,6 @@ const BUDGET = 'budget.toml'; /** How the repository applies the standard, deviations included. */ const STANDARD = 'standard.toml'; -/** The label that approves a pull request's exceptions. */ -const APPROVED = 'approved-exception'; - /** An added lint expectation: `#[expect(…)]`, `#![expect(…)]`, or one * through `cfg_attr`. */ const EXPECT = /#!?\[\s*(expect\s*\(|cfg_attr\s*\(.*\bexpect\s*\()/; @@ -66,15 +64,7 @@ const lintExceptions = { * approval. */ async waiver(pr, inputs) { if (!inputs.enforceLintExceptions) return 'the repository runs this check in report-only mode'; - if (pr.labels.includes(APPROVED)) return `the pull request carries the \`${APPROVED}\` label`; - const latest = new Map(); - for (const review of await pr.reviews()) { - if (review.state !== 'COMMENTED') latest.set(review.login, review); - } - const approval = [...latest.values()].find( - ({ login, state, commit }) => state === 'APPROVED' && commit === pr.head && inputs.approvers.includes(login), - ); - return approval && `${approval.login} approved the latest commit`; + return pr.approval(inputs.approvers); }, /** The lines a unified diff adds, each with its line in the new file. */ diff --git a/.github/pr-checks/pull-request.js b/.github/pr-checks/pull-request.js index 94250e7..61137b5 100644 --- a/.github/pr-checks/pull-request.js +++ b/.github/pr-checks/pull-request.js @@ -1,5 +1,8 @@ 'use strict'; +/** The label that approves the exceptions a pull request makes. */ +const APPROVED = 'approved-exception'; + /** * The pull request a check runs on, read through the GitHub API rather than * a checkout. Tests build one from plain values with `new PullRequest(...)`. @@ -37,15 +40,21 @@ class PullRequest { return commits.map(({ sha, commit }) => ({ sha, message: commit.message })); } - /** Each file it changes: `{ path, status, patch }`, where `patch` is the - * unified diff, or `undefined` when GitHub leaves out a large one. */ + /** Each file it changes: `{ path, status, patch, previous }`, where + * `patch` is the unified diff, or `undefined` when GitHub leaves out a + * large one, and `previous` a renamed file's former path. */ async files() { const files = await this.github.paginate(this.github.rest.pulls.listFiles, { ...this.repo, pull_number: this.number, per_page: 100, }); - return files.map(({ filename, status, patch }) => ({ path: filename, status, patch })); + return files.map(({ filename, status, patch, previous_filename }) => ({ + path: filename, + status, + patch, + previous: previous_filename, + })); } /** Each review, oldest first: `{ login, state, commit }`, where `commit` @@ -59,6 +68,21 @@ class PullRequest { return reviews.map(({ user, state, commit_id }) => ({ login: user?.login, state, commit: commit_id })); } + /** Why the exceptions it makes may stand: an approval of its latest + * commit by one of `approvers`, which no later review of theirs has + * withdrawn, or the `approved-exception` label. `undefined` without one. */ + async approval(approvers) { + if (this.labels.includes(APPROVED)) return `the pull request carries the \`${APPROVED}\` label`; + const latest = new Map(); + for (const review of await this.reviews()) { + if (review.state !== 'COMMENTED') latest.set(review.login, review); + } + const approval = [...latest.values()].find( + ({ login, state, commit }) => state === 'APPROVED' && commit === this.head && approvers.includes(login), + ); + return approval && `${approval.login} approved the latest commit`; + } + /** The text of the file at `path` in commit `sha`, or `null` if it has * none. */ async fileAt(sha, path) { @@ -77,4 +101,4 @@ class PullRequest { } } -module.exports = { PullRequest }; +module.exports = { PullRequest, APPROVED }; diff --git a/.github/pr-checks/run.js b/.github/pr-checks/run.js index 11e0c2a..e784c15 100644 --- a/.github/pr-checks/run.js +++ b/.github/pr-checks/run.js @@ -18,6 +18,7 @@ class Runner { require('./fix-has-test.js'), require('./new-dependency.js'), require('./lint-exceptions.js'), + require('./frozen-files.js'), ]; /** Runs the check named in `CHECK` with the inputs in `INPUTS`. Each diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index f554b36..15a2ab1 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -25,6 +25,10 @@ on: description: Whether an unapproved lint exception fails, rather than only being reported. type: boolean default: true + frozen-files: + description: Globs of the files that never change once on the base branch, separated by spaces. + type: string + default: "" deviations: description: Lines of `check = "why"`, for checks the repository departs from. type: string @@ -52,6 +56,7 @@ jobs: - fix-has-test - new-dependency - lint-exceptions + - frozen-files steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index 6feac1d..def3620 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -153,6 +153,11 @@ check: approves the latest commit, or the pull request carries the `approved-exception` label: exceptions are fine, but a loosened rule is always seen. +- `frozen-files`: a file matching a glob of the `frozen-files` input that + exists on the base branch, such as an applied migration, is not modified, + renamed or deleted; a deliberate change needs the same approval as a lint + exception. Only a pull request can check this: on `main` there is + nothing to compare with. A repository calls it from `.github/workflows/pr.yml`, pinned to a commit of this repository's `main`. Reviews and labels re-run it, as some checks @@ -185,6 +190,7 @@ jobs: scopes: daemon cli web issue-prefix: PQD- approvers: PiquelChips + frozen-files: crates/*/migrations/*.sql ``` Its inputs: @@ -198,6 +204,8 @@ Its inputs: by spaces: the owner. - `enforce-lint-exceptions`: `false` only reports lint exceptions, without failing, as a repository adopting the check starts. +- `frozen-files`: globs, separated by spaces, of the files that never + change once on the base branch, such as `crates/*/migrations/*.sql`. - `deviations`: lines of `check = "why"`, for the checks the repository departs from, whose findings then pass as notices.