Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
77 changes: 77 additions & 0 deletions .github/pr-checks/frozen-files.js
Original file line number Diff line number Diff line change
@@ -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;
70 changes: 70 additions & 0 deletions .github/pr-checks/frozen-files.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
3 changes: 3 additions & 0 deletions .github/pr-checks/inputs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
14 changes: 2 additions & 12 deletions .github/pr-checks/lint-exceptions.js
Original file line number Diff line number Diff line change
@@ -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:`
Expand All @@ -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*\()/;
Expand Down Expand Up @@ -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. */
Expand Down
32 changes: 28 additions & 4 deletions .github/pr-checks/pull-request.js
Original file line number Diff line number Diff line change
@@ -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(...)`.
Expand Down Expand Up @@ -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`
Expand All @@ -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) {
Expand All @@ -77,4 +101,4 @@ class PullRequest {
}
}

module.exports = { PullRequest };
module.exports = { PullRequest, APPROVED };
1 change: 1 addition & 0 deletions .github/pr-checks/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/pr-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -52,6 +56,7 @@ jobs:
- fix-has-test
- new-dependency
- lint-exceptions
- frozen-files
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
Expand Down
8 changes: 8 additions & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -185,6 +190,7 @@ jobs:
scopes: daemon cli web
issue-prefix: PQD-
approvers: PiquelChips
frozen-files: crates/*/migrations/*.sql
```

Its inputs:
Expand All @@ -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.

Expand Down