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
3 changes: 3 additions & 0 deletions .github/pr-checks/inputs.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ class Inputs {
const inputs = JSON.parse(json || '{}');
/** The scopes a title may take. */
this.scopes = Inputs.list(inputs.scopes);
/** 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'] || '#';
/** 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
95 changes: 95 additions & 0 deletions .github/pr-checks/pr-body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
'use strict';

/** Where the repository's pull request template lives. */
const TEMPLATE = '.github/pull_request_template.md';

/** The words that make GitHub or Linear close an issue a description names. */
const CLOSING = ['close', 'closes', 'closed', 'fix', 'fixes', 'fixed', 'resolve', 'resolves', 'resolved'];

/**
* G3 and G7: the description has every heading of the repository's pull
* request template, each with something under it besides the template's
* comments. An issue link is optional; one that closes an issue is
* `Fixes <prefix><number>`, in the form the repository's issues take.
*/
const prBody = {
name: 'pr-body',

async findings(pr, inputs) {
const template = await pr.fileAt(pr.base, TEMPLATE);
if (template === null) {
return [
{
path: TEMPLATE,
message: `the repository has no pull request template, whose headings a description follows: add one with \`## What and why\` and \`## Testing\``,
},
];
}
const missing = prBody.missing(template, pr.body).map((heading) => ({
message:
`the description has nothing under \`${heading}\`: fill in every heading of ${TEMPLATE}, ` +
`saying what was wrong, what changes and how it was tested, including what wasn't.`,
}));
const links = prBody.wrongLinks(pr.body, inputs.issuePrefix).map((link) => ({
message:
`\`${link}\` closes an issue in another form than this repository's: write ` +
`\`Fixes ${inputs.issuePrefix}<number>\` to close it, or \`Part of ${inputs.issuePrefix}<number>\` ` +
`to only link it.`,
}));
return [...missing, ...links];
},

/** The template's headings that `body` lacks or leaves empty. */
missing(template, body) {
const sections = prBody.sections(body);
return prBody
.sections(template)
.map(({ heading }) => heading)
.filter(
(heading) =>
!sections.some(
(section) => section.heading.toLowerCase() === heading.toLowerCase() && section.text,
),
);
},

/** Each heading of `markdown` and the text under it, its subsections'
* included, without HTML comments or lines in code fences. */
sections(markdown) {
const sections = [];
let fenced = false;
for (const line of prBody.prose(markdown).split(/\r?\n/)) {
if (/^\s*(```|~~~)/.test(line)) fenced = !fenced;
const heading = !fenced && /^(#{1,6})\s+(.+?)[\s#]*$/.exec(line);
if (heading) sections.push({ level: heading[1].length, heading: heading[2], text: '' });
else if (sections.length) sections.at(-1).text += line.trim();
}
return sections.map((section, index) => {
let { text } = section;
for (const next of sections.slice(index + 1)) {
if (next.level <= section.level) break;
text += next.heading + next.text;
}
return { heading: section.heading, text };
});
},

/** `markdown` without its HTML comments, which hold a template's prompts. */
prose(markdown) {
return markdown.replace(/<!--[\s\S]*?(-->|$)/g, '');
},

/** The closing references in `body` that aren't `Fixes <prefix><n>`.
* Those in code, which closes nothing, don't count. */
wrongLinks(body, prefix) {
const reference = /\b([A-Za-z]+):?\s+(#\d+|[\w.-]+\/[\w.-]+#\d+|[A-Z][A-Z0-9]*-\d+|https?:\/\/\S+)/g;
const form = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\d+$`);
const text = prBody.prose(body).replace(/^\s*(```|~~~)[\s\S]*?^\s*\1/gm, '').replace(/`[^`\n]*`/g, '');
return [...text.matchAll(reference)]
.filter(([, keyword]) => CLOSING.includes(keyword.toLowerCase()))
.filter(([, keyword, issue]) => keyword.toLowerCase() !== 'fixes' || !form.test(issue))
.map(([link]) => link.replace(/\s+/g, ' '));
},
};

module.exports = prBody;
75 changes: 75 additions & 0 deletions .github/pr-checks/pr-body.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const prBody = require('./pr-body.js');
const { Inputs } = require('./inputs.js');
const { Fake } = require('./testing.js');

const template = [
'<!-- Title: a conventional commit. -->',
'',
'## What and why',
'',
'<!-- What was wrong, and the issue it closes ("Fixes #123"). -->',
'',
'## Testing',
'',
'<!-- How you tested it. -->',
].join('\n');

const findings = async (body, inputs = {}, files = { base: { '.github/pull_request_template.md': template } }) =>
prBody.findings(await Fake.pr({ body }, { files }), new Inputs(JSON.stringify(inputs), []));

test('a description filling every heading passes', async () => {
assert.deepEqual(await findings('## What and why\nIt broke.\n\n## Testing\n\nRan it.'), []);
});

test('a heading left empty or with only the prompt fails', async () => {
const messages = (await findings(`## What and why\nIt broke.\n${template.split('## Testing')[1]}`)).map(
(finding) => finding.message,
);
assert.equal(messages.length, 1);
assert.match(messages[0], /nothing under `Testing`/);
assert.equal((await findings(template)).length, 2);
});

test('a missing heading fails, whatever the case of those present', async () => {
const [finding] = await findings('## what AND why\nIt broke.');
assert.match(finding.message, /nothing under `Testing`: fill in every heading/);
});

test("a subsection counts as its heading's text, and a fenced heading as none", () => {
assert.deepEqual(prBody.missing(template, '## What and why\n### Detail\n## Testing\nRan it.'), []);
assert.deepEqual(prBody.missing(template, '## What and why\n```\n## Testing\nx\n```'), ['Testing']);
});

test('a repository without a template is told to add one', async () => {
const [finding] = await findings('anything', {}, {});
assert.equal(finding.path, '.github/pull_request_template.md');
});

test("an issue link is optional, and one in the repository's form passes", () => {
assert.deepEqual(prBody.wrongLinks('No issue.', '#'), []);
assert.deepEqual(prBody.wrongLinks('Fixes #12. Part of #13. fixes #14', '#'), []);
assert.deepEqual(prBody.wrongLinks('Fixes PQD-123', 'PQD-'), []);
});

test('a closing link in another form fails', () => {
assert.deepEqual(prBody.wrongLinks('Closes #12, resolves: #13', '#'), ['Closes #12', 'resolves: #13']);
assert.deepEqual(prBody.wrongLinks('Fixes #12', 'PQD-'), ['Fixes #12']);
assert.deepEqual(prBody.wrongLinks('Fixes PQD-12', '#'), ['Fixes PQD-12']);
assert.deepEqual(prBody.wrongLinks('Fixes owner/repo#12', '#'), ['Fixes owner/repo#12']);
assert.deepEqual(prBody.wrongLinks('<!-- Closes #12 -->', '#'), []);
});

test('a link in code closes nothing, so it passes', () => {
assert.deepEqual(prBody.wrongLinks('Reads `Closes #12` as wrong.', '#'), []);
assert.deepEqual(prBody.wrongLinks('```\nCloses #12\n```\nThen Closes #13', '#'), ['Closes #13']);
});

test('the finding for a link gives the form to use', async () => {
const body = '## What and why\nCloses #4\n## Testing\nRan it.';
const [finding] = await findings(body, { 'issue-prefix': 'PQD-' });
assert.match(finding.message, /^`Closes #4` closes an issue .* write `Fixes PQD-<number>`/);
});
17 changes: 17 additions & 0 deletions .github/pr-checks/pull-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ class PullRequest {
});
return new PullRequest(data, { github, repo: context.repo });
}

/** The text of the file at `path` in commit `sha`, or `null` if it has
* none. */
async fileAt(sha, path) {
try {
const { data } = await this.github.rest.repos.getContent({
...this.repo,
path,
ref: sha,
mediaType: { format: 'raw' },
});
return data;
} catch (error) {
if (error.status === 404) return null;
throw error;
}
}
}

module.exports = { PullRequest };
2 changes: 1 addition & 1 deletion .github/pr-checks/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Runner {
/** Every check, each a job of pr-checks.yml's matrix: an object with a
* `name`, `findings(pr, inputs)` and, optionally, `waiver(pr, inputs)`,
* the reason findings shouldn't fail the job, or nothing. */
static CHECKS = [require('./pr-title.js')];
static CHECKS = [require('./pr-title.js'), require('./pr-body.js')];

/** Runs the check named in `CHECK` with the inputs in `INPUTS`. Each
* finding becomes an error annotation and a line of the job summary, and
Expand Down
31 changes: 26 additions & 5 deletions .github/pr-checks/testing.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const { PullRequest } = require('./pull-request.js');

/**
* Stand-ins for what `actions/github-script` hands a script, for the tests:
* `Fake.core()` records what a check reports, and `Fake.github(pr)` answers
Expand All @@ -26,15 +28,34 @@ class Fake {
return core;
}

/** A `github` and `context` for pull request number 1, with the fields
* of `pr` over a passing default. */
static github(pr = {}) {
const data = { number: 1, title: 'feat: a change', body: '', labels: [], ...pr };
/** 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, and `files[sha][path]` the text of each file. */
static github(pr = {}, { files = {} } = {}) {
const data = {
number: 1,
title: 'feat: a change',
body: '',
labels: [],
base: { sha: 'base' },
head: { sha: 'head' },
...pr,
};
const getContent = async ({ ref, path }) => {
const text = files[ref]?.[path];
if (text === undefined) throw Object.assign(new Error('Not Found'), { status: 404 });
return { data: text };
};
return {
github: { rest: { pulls: { get: async () => ({ data }) } } },
github: { rest: { pulls: { get: async () => ({ data }) }, repos: { getContent } } },
context: { repo: { owner: 'o', repo: 'r' }, payload: { pull_request: { number: 1 } } },
};
}

/** The pull request `Fake.github` describes, as a check receives it. */
static async pr(pr = {}, options = {}) {
return PullRequest.load(Fake.github(pr, options));
}
}

module.exports = { Fake };
6 changes: 5 additions & 1 deletion .github/workflows/pr-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ on:
description: The scopes a title may take, separated by spaces.
type: string
default: ""
issue-prefix:
description: What precedes an issue's number where issues live, such as `PQD-`.
type: string
default: "#"
deviations:
description: Lines of `check = "why"`, for checks the repository departs from.
type: string
Expand All @@ -33,7 +37,7 @@ jobs:
strategy:
fail-fast: false
matrix:
check: [pr-title]
check: [pr-title, pr-body]
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 @@ -132,6 +132,10 @@ check:
- `pr-title`: the title is a Conventional Commit, `type(scope)!: subject`,
of type `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `ci`, `perf`,
`build` or `revert`, and of a scope the repository allows, if any.
- `pr-body`: the description has every heading of the repository's
`.github/pull_request_template.md`, each with more than the template's
comments under it. An issue link is optional; one that closes an issue
reads `Fixes #123`, or `Fixes PQD-123` where issues live in Linear.

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 @@ -162,12 +166,16 @@ jobs:
pull-requests: read
with:
scopes: daemon cli web
issue-prefix: PQD-
```

Its inputs:

- `scopes`: the scopes a title may take, separated by spaces. Without it, a
title takes no scope.
- `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-`.
- `deviations`: lines of `check = "why"`, for the checks the repository
departs from, whose findings then pass as notices.

Expand Down