diff --git a/.github/pr-checks/inputs.js b/.github/pr-checks/inputs.js index ed66578..ebf195d 100644 --- a/.github/pr-checks/inputs.js +++ b/.github/pr-checks/inputs.js @@ -15,6 +15,11 @@ class Inputs { /** What precedes an issue's number where it lives: `#`, or a Linear * team's key and a dash, such as `PQD-`. */ this.issuePrefix = inputs['issue-prefix'] || '#'; + /** Who may approve a lint exception with a review: the owner. */ + this.approvers = Inputs.list(inputs.approvers); + /** 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; /** 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 new file mode 100644 index 0000000..6f510ba --- /dev/null +++ b/.github/pr-checks/lint-exceptions.js @@ -0,0 +1,157 @@ +'use strict'; + +const { Toml } = require('./toml.js'); + +/** The repository's ceilings of `#[expect]` attributes and `// INVARIANT:` + * comments, by crate. */ +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*\()/; + +/** + * C11: every exception a pull request adds is seen. It lists each added + * `#[expect]`, each ceiling of budget.toml it raises and each deviation of + * standard.toml it adds, rewords or widens; they are allowed once the owner + * approves the pull request's latest commit, or it carries the + * `approved-exception` label, and always allowed in report-only mode. + */ +const lintExceptions = { + name: 'lint-exceptions', + + async findings(pr) { + const files = await pr.files(); + const findings = []; + for (const { path, status, patch } of files) { + if (!path.endsWith('.rs') || status === 'removed') continue; + if (patch === undefined) { + findings.push({ path, message: 'GitHub shows no diff of this file, too large to read for added `#[expect]` attributes: review it for them.' }); + continue; + } + for (const { line, text } of lintExceptions.added(patch)) { + if (EXPECT.test(text)) { + findings.push({ path, line, message: `this adds the lint exception \`${text.trim()}\`.` }); + } + } + } + const changed = new Set(files.map(({ path }) => path)); + for (const [path, read] of [ + [BUDGET, lintExceptions.ceilings], + [STANDARD, lintExceptions.deviations], + ]) { + if (!changed.has(path)) continue; + const before = read(new Toml((await pr.fileAt(pr.base, path)) ?? '')); + for (const [key, after] of read(new Toml((await pr.fileAt(pr.head, path)) ?? ''))) { + const verb = before.has(key) ? after.loosens(before.get(key)) : 'adds'; + if (verb) findings.push({ path, line: after.line, message: `this ${verb} \`${key}\`: ${after.text}.` }); + } + } + return findings.map((finding) => ({ + ...finding, + message: + `${finding.message} An exception loosens a rule, so it needs the owner's approving ` + + `review of the latest commit, or the \`${APPROVED}\` label: ask for one, and say in the ` + + `exception's reason why the rule is wrong here.`, + })); + }, + + /** Why the exceptions may stand, or `undefined` while they wait for an + * 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`; + }, + + /** The lines a unified diff adds, each with its line in the new file. */ + added(patch) { + const lines = []; + let line = 0; + for (const text of patch.split('\n')) { + const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(text); + if (hunk) line = Number(hunk[1]); + else if (text.startsWith('+')) lines.push({ line: line++, text: text.slice(1) }); + else if (text.startsWith(' ')) line += 1; + } + return lines; + }, + + /** Each ceiling of a budget.toml, by table and crate: its line, its text + * and what loosens one it replaces, if it does. */ + ceilings(toml) { + return new Map( + toml.entries + .filter(({ table }) => table) + .map(({ table, key, value, line }) => [ + `${table}.${key}`, + { + line, + ceiling: Number(value), + text: `the ceiling is now ${value}`, + loosens: (before) => (Number(value) > before.ceiling ? 'raises' : null), + }, + ]), + ); + }, + + /** Each deviation of a standard.toml, by rule: its line, its text and + * what loosens one it replaces, if it does: a new reason, or a scope that + * grows or goes. A narrower scope doesn't. */ + deviations(toml) { + const rules = new Map(); + for (const { table, key, value, line } of toml.entries) { + const [section, rule, field] = [...table.split('.'), ...key.split('.')]; + if (section !== 'deviations' || !rule) continue; + if (!rules.has(rule)) rules.set(rule, { line, reason: '', paths: [], crates: [] }); + const deviation = rules.get(rule); + const fields = field + ? [[field, value]] + : Toml.string(value) === null + ? new Toml(Toml.items(value).join('\n')).entries.map((entry) => [entry.key, entry.value]) + : [['reason', value]]; + for (const [name, text] of fields) { + if (name === 'reason') deviation.reason = Toml.string(text) ?? text; + if (name === 'paths' || name === 'crates') { + deviation[name] = Toml.items(text).map((item) => Toml.string(item) ?? item); + } + } + } + return new Map( + [...rules].map(([rule, { line, reason, paths, crates }]) => { + const scope = [...paths.map((path) => `\`${path}\``), ...crates.map((name) => `crate \`${name}\``)]; + return [ + `deviations.${rule}`, + { + line, + reason, + scope: new Set(scope), + text: `"${reason}", ${scope.length ? `in ${scope.join(', ')}` : 'everywhere'}`, + loosens: (before) => { + if (before.reason !== reason) return 'rewords'; + const widens = before.scope.size + ? scope.length === 0 || scope.some((entry) => !before.scope.has(entry)) + : false; + return widens ? 'widens' : null; + }, + }, + ]; + }), + ); + }, +}; + +module.exports = lintExceptions; diff --git a/.github/pr-checks/lint-exceptions.test.js b/.github/pr-checks/lint-exceptions.test.js new file mode 100644 index 0000000..a08a41c --- /dev/null +++ b/.github/pr-checks/lint-exceptions.test.js @@ -0,0 +1,125 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const lintExceptions = require('./lint-exceptions.js'); +const { Inputs } = require('./inputs.js'); +const { Fake } = require('./testing.js'); + +const patch = [ + '@@ -10,3 +10,6 @@ impl Rule {', + ' fn a() {}', + '+#[expect(clippy::too_many_lines, reason = "one match")]', + '-#[allow(dead_code)]', + ' fn b() {}', + '+ #![expect(unsafe_code, reason = "ffi")]', + '+#[cfg_attr(test, expect(clippy::unwrap_used, reason = "tests"))]', + '+// #[expect] in prose is a comment, which another rule forbids', +].join('\n'); + +const lines = (findings) => findings.map(({ path, line, message }) => `${path}:${line ?? ''} ${message.split(' An exception')[0]}`); + +test('each added #[expect] is found at its line, removed ones not', async () => { + const changed = [ + { filename: 'src/lib.rs', status: 'modified', patch }, + { filename: 'src/old.rs', status: 'removed', patch: '+#[expect(x)]' }, + { filename: 'notes.md', status: 'modified', patch: '+#[expect(x)]' }, + ]; + assert.deepEqual(lines(await lintExceptions.findings(await Fake.pr({}, { changed }))), [ + 'src/lib.rs:11 this adds the lint exception `#[expect(clippy::too_many_lines, reason = "one match")]`.', + 'src/lib.rs:13 this adds the lint exception `#![expect(unsafe_code, reason = "ffi")]`.', + 'src/lib.rs:14 this adds the lint exception `#[cfg_attr(test, expect(clippy::unwrap_used, reason = "tests"))]`.', + ]); +}); + +test('a Rust file too large for a diff is flagged for review', async () => { + const changed = [{ filename: 'src/big.rs', status: 'modified' }]; + const [finding] = await lintExceptions.findings(await Fake.pr({}, { changed })); + assert.match(finding.message, /^GitHub shows no diff of this file/); +}); + +test('raised or new budget ceilings are found, lowered ones not', async () => { + const base = { 'budget.toml': '[expect]\na = 3\nb = 2\n' }; + const head = { 'budget.toml': '[expect]\na = 4\nb = 1\n\n[invariant]\na = 1\n' }; + const changed = [{ filename: 'budget.toml', status: 'modified' }]; + assert.deepEqual(lines(await lintExceptions.findings(await Fake.pr({}, { files: { base, head }, changed }))), [ + 'budget.toml:2 this raises `expect.a`: the ceiling is now 4.', + 'budget.toml:6 this adds `invariant.a`: the ceiling is now 1.', + ]); +}); + +test('new or reworded deviations are found, unchanged ones not', async () => { + const base = { 'standard.toml': '[deviations]\nbudget = "old"\ndoc-length = "kept"\n' }; + const head = { 'standard.toml': '[deviations]\nbudget = "new"\ndoc-length = "kept"\nrust-comments = "why"\n' }; + const changed = [{ filename: 'standard.toml', status: 'modified' }]; + assert.deepEqual(lines(await lintExceptions.findings(await Fake.pr({}, { files: { base, head }, changed }))), [ + 'standard.toml:2 this rewords `deviations.budget`: "new", everywhere.', + 'standard.toml:4 this adds `deviations.rust-comments`: "why", everywhere.', + ]); +}); + +test('a scoped deviation that widens is found, one that narrows not', async () => { + const base = { + 'standard.toml': [ + '[deviations]', + 'a = { reason = "r", paths = ["gen/**"] }', + 'b = { reason = "r", crates = ["x", "y"] }', + 'c = "r"', + '[deviations.d]', + 'reason = "r"', + 'paths = ["d/**"]', + ].join('\n'), + }; + const head = { + 'standard.toml': [ + '[deviations]', + 'a = { reason = "r", paths = ["gen/**", "src/**"] }', + 'b = { reason = "r", crates = ["x"] }', + 'c = { reason = "r", paths = ["c/**"] }', + '[deviations.d]', + 'reason = "r"', + ].join('\n'), + }; + const changed = [{ filename: 'standard.toml', status: 'modified' }]; + assert.deepEqual(lines(await lintExceptions.findings(await Fake.pr({}, { files: { base, head }, changed }))), [ + 'standard.toml:2 this widens `deviations.a`: "r", in `gen/**`, `src/**`.', + 'standard.toml:6 this widens `deviations.d`: "r", everywhere.', + ]); +}); + +test("each finding says how to get approval", async () => { + const changed = [{ filename: 'src/lib.rs', status: 'modified', patch }]; + const [finding] = await lintExceptions.findings(await Fake.pr({}, { changed })); + assert.match(finding.message, /needs the owner's approving review of the latest commit, or the `approved-exception` label/); +}); + +const waiver = async (pr, { reviews = [], ...inputs } = {}) => + lintExceptions.waiver( + await Fake.pr(pr, { reviews }), + new Inputs(JSON.stringify({ approvers: 'owner', ...inputs }), []), + ); +const review = (login, state, commit_id = 'head') => ({ user: { login }, state, commit_id }); + +test("the owner's approval of the latest commit allows the exceptions", async () => { + assert.equal(await waiver({}, { reviews: [review('owner', 'APPROVED')] }), 'owner approved the latest commit'); + assert.equal( + await waiver({}, { reviews: [review('owner', 'APPROVED'), review('owner', 'COMMENTED')] }), + 'owner approved the latest commit', + ); +}); + +test('another approval, a stale one, or one withdrawn does not', async () => { + for (const reviews of [ + [review('someone', 'APPROVED')], + [review('owner', 'APPROVED', 'older')], + [review('owner', 'APPROVED'), review('owner', 'CHANGES_REQUESTED')], + [review('owner', 'APPROVED'), review('owner', 'DISMISSED')], + ]) { + assert.equal(await waiver({}, { reviews }), undefined, JSON.stringify(reviews)); + } +}); + +test('the label or report-only mode allows the exceptions', async () => { + assert.match(await waiver({ labels: [{ name: 'approved-exception' }] }), /`approved-exception` label/); + assert.match(await waiver({}, { 'enforce-lint-exceptions': false }), /report-only mode/); +}); diff --git a/.github/pr-checks/pull-request.js b/.github/pr-checks/pull-request.js index 8907e06..94250e7 100644 --- a/.github/pr-checks/pull-request.js +++ b/.github/pr-checks/pull-request.js @@ -48,6 +48,17 @@ class PullRequest { return files.map(({ filename, status, patch }) => ({ path: filename, status, patch })); } + /** Each review, oldest first: `{ login, state, commit }`, where `commit` + * is the SHA it reviewed. */ + async reviews() { + const reviews = await this.github.paginate(this.github.rest.pulls.listReviews, { + ...this.repo, + pull_number: this.number, + per_page: 100, + }); + return reviews.map(({ user, state, commit_id }) => ({ login: user?.login, state, commit: commit_id })); + } + /** The text of the file at `path` in commit `sha`, or `null` if it has * none. */ async fileAt(sha, path) { diff --git a/.github/pr-checks/run.js b/.github/pr-checks/run.js index bebc0ff..11e0c2a 100644 --- a/.github/pr-checks/run.js +++ b/.github/pr-checks/run.js @@ -17,6 +17,7 @@ class Runner { require('./no-co-authors.js'), require('./fix-has-test.js'), require('./new-dependency.js'), + require('./lint-exceptions.js'), ]; /** Runs the check named in `CHECK` with the inputs in `INPUTS`. Each diff --git a/.github/pr-checks/testing.js b/.github/pr-checks/testing.js index 2d83808..b6e1446 100644 --- a/.github/pr-checks/testing.js +++ b/.github/pr-checks/testing.js @@ -31,9 +31,10 @@ class Fake { /** A `github` and `context` for pull request number 1, from base commit * `base` to head commit `head`, with the fields of `pr` over a passing * default, `files[sha][path]` the text of each file, `commits` its - * commits, as `{ sha, commit: { message } }`, and `changed` the files it - * changes, as `{ filename, status, patch }`. */ - static github(pr = {}, { files = {}, commits = [], changed = [] } = {}) { + * commits, as `{ sha, commit: { message } }`, `changed` the files it + * changes, as `{ filename, status, patch }`, and `reviews` its reviews, as + * `{ user: { login }, state, commit_id }`. */ + static github(pr = {}, { files = {}, commits = [], changed = [], reviews = [] } = {}) { const data = { number: 1, title: 'feat: a change', @@ -55,6 +56,7 @@ class Fake { get: async () => ({ data }), listCommits: async () => ({ data: commits }), listFiles: async () => ({ data: changed }), + listReviews: async () => ({ data: reviews }), }, repos: { getContent }, }, diff --git a/.github/pr-checks/toml.js b/.github/pr-checks/toml.js index e5864ed..b5b30c1 100644 --- a/.github/pr-checks/toml.js +++ b/.github/pr-checks/toml.js @@ -54,12 +54,13 @@ class Toml { return null; } - /** The elements of an array, each as raw text with its spacing squeezed. */ + /** The elements of an array, or the `key = value` pairs of an inline + * table, each as raw text with its spacing squeezed. */ static items(value) { const items = []; let current = ''; let depth = 0; - for (const { c, quoted } of Toml.characters(value.trim().replace(/^\[|\]$/g, ''))) { + for (const { c, quoted } of Toml.characters(value.trim().replace(/^[[{]|[\]}]$/g, ''))) { if (!quoted && (c === '[' || c === '{')) depth += 1; if (!quoted && (c === ']' || c === '}')) depth -= 1; if (!quoted && depth === 0 && c === ',') { diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index e475a85..f554b36 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -17,6 +17,14 @@ on: description: What precedes an issue's number where issues live, such as `PQD-`. type: string default: "#" + approvers: + description: Who may approve a lint exception with a review, separated by spaces. + type: string + default: "" + enforce-lint-exceptions: + description: Whether an unapproved lint exception fails, rather than only being reported. + type: boolean + default: true deviations: description: Lines of `check = "why"`, for checks the repository departs from. type: string @@ -37,7 +45,13 @@ jobs: strategy: fail-fast: false matrix: - check: [pr-title, pr-body, no-co-authors, fix-has-test, new-dependency] + check: + - pr-title + - pr-body + - no-co-authors + - fix-has-test + - new-dependency + - lint-exceptions steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index b4ca168..c767d8a 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -26,3 +26,4 @@ jobs: pull-requests: read with: scopes: check-changed rules lints pr-checks xtask + approvers: PiquelChips diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index 3ac3d79..6feac1d 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -146,6 +146,13 @@ check: `[workspace.dependencies]`, or an exception to `deny.toml` (an ignored advisory, an allowed license, a skipped duplicate, an allowed source), has a `## Dependencies` section in its description saying why. +- `lint-exceptions`: lists, in the job's summary, each `#[expect]` a pull + request adds, each ceiling of `budget.toml` it raises and each deviation + of `standard.toml` it adds, rewords or widens (a scope gaining a path or + crate, or dropped for everywhere). They fail the job until an approver + approves the latest commit, or the pull request carries the + `approved-exception` label: exceptions are fine, but a loosened rule is + always seen. 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 @@ -177,6 +184,7 @@ jobs: with: scopes: daemon cli web issue-prefix: PQD- + approvers: PiquelChips ``` Its inputs: @@ -186,6 +194,10 @@ Its inputs: - `issue-prefix`: what precedes an issue's number where the repository's issues live: `#` by default, or a Linear team's key and a dash, such as `PQD-`. +- `approvers`: who may approve a lint exception with a review, separated + by spaces: the owner. +- `enforce-lint-exceptions`: `false` only reports lint exceptions, without + failing, as a repository adopting the check starts. - `deviations`: lines of `check = "why"`, for the checks the repository departs from, whose findings then pass as notices.