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
5 changes: 5 additions & 0 deletions .github/filters.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ deny:
- *workspace
- deny.toml
- '**/Cargo.toml'
pr-checks:
- .github/workflows/ci.yml
- .github/filters.yml
- justfile
- .github/pr-checks/**
35 changes: 35 additions & 0 deletions .github/pr-checks/inputs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';

const { Toml } = require('./toml.js');

/**
* The inputs a repository's caller workflow passes to pr-checks.yml, read
* once from their JSON (`toJSON(inputs)`) so every check gets them typed.
*/
class Inputs {
/** Reads the inputs; `known` are the check names a deviation may name. */
constructor(json, known) {
const inputs = JSON.parse(json || '{}');
/** The scopes a title may take. */
this.scopes = Inputs.list(inputs.scopes);
/** 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) {
const reason = Toml.string(value);
if (table || !known.includes(key) || !reason?.trim()) {
throw new Error(
`the \`deviations\` input, line ${line}: \`${key}\` must be one of ${known.join(', ')}, ` +
`given as \`${key} = "<why the repository departs from it>"\``,
);
}
this.deviations.set(key, reason);
}
}

/** The words of a list input, separated by spaces, commas or newlines. */
static list(value) {
return (value ?? '').split(/[\s,]+/).filter(Boolean);
}
}

module.exports = { Inputs };
53 changes: 53 additions & 0 deletions .github/pr-checks/pr-title.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

/** The types a title may start with. */
const TYPES = ['feat', 'fix', 'refactor', 'docs', 'test', 'chore', 'ci', 'perf', 'build', 'revert'];

/**
* G2: the title is a Conventional Commit, `type(scope)!: subject`, of one of
* `TYPES` and the scopes the repository allows, since squash-merging makes it
* the commit on `main`.
*/
const prTitle = {
name: 'pr-title',
TYPES,

async findings(pr, inputs) {
const problem = prTitle.problem(pr.title, inputs.scopes);
if (!problem) return [];
const scope = inputs.scopes.length ? `(${inputs.scopes[0]})` : '';
const scopes = inputs.scopes.length
? `one of ${inputs.scopes.join(', ')}`
: 'none, as this repository takes no scope';
return [
{
message:
`the title \`${pr.title}\` ${problem}. Write it as \`type(scope)!: subject\`: ` +
`the type one of ${TYPES.join(', ')}; the scope, if any, ${scopes}; \`!\` for a ` +
`breaking change; the subject saying what changes for the reader, such as ` +
`\`fix${scope}: a negated glob no longer matches its own pattern\`.`,
},
];
},

/** The title's parts, or `null` when it doesn't have the shape. */
parse(title) {
return (
/^(?<type>\w+)(?:\((?<scope>[^()]*)\))?(?<breaking>!)?: (?<subject>\S.*)$/.exec(title)?.groups ??
null
);
},

/** What is wrong with the title, or `null`. */
problem(title, scopes) {
const parts = prTitle.parse(title);
if (!parts) return 'is not `type(scope)!: subject`';
if (!TYPES.includes(parts.type)) return `has the type \`${parts.type}\``;
if (parts.scope !== undefined && !scopes.includes(parts.scope)) {
return `has the scope \`${parts.scope}\``;
}
return null;
},
};

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

const test = require('node:test');
const assert = require('node:assert/strict');
const prTitle = require('./pr-title.js');

const scopes = ['rules', 'check-changed'];

test('a conventional title passes, with or without scope and breaking mark', () => {
for (const title of ['feat: a', 'fix(rules): a', 'refactor(check-changed)!: a', 'docs!: a']) {
assert.equal(prTitle.problem(title, scopes), null, title);
}
});

test('a title without the shape fails', () => {
for (const title of ['Add a thing', 'feat:a', 'feat(rules) : a', 'feat: ', 'feat()x: a']) {
assert.equal(prTitle.problem(title, scopes), 'is not `type(scope)!: subject`', title);
}
});

test('a type outside the list fails', () => {
assert.equal(prTitle.problem('feature: a', scopes), 'has the type `feature`');
assert.equal(prTitle.problem('Feat: a', scopes), 'has the type `Feat`');
});

test('a scope the repository does not allow fails', () => {
assert.equal(prTitle.problem('feat(web): a', scopes), 'has the scope `web`');
assert.equal(prTitle.problem('feat(rules): a', []), 'has the scope `rules`');
});

test('the finding shows the expected form and an example in an allowed scope', async () => {
const [finding] = await prTitle.findings({ title: 'Add a thing' }, { scopes });
assert.match(finding.message, /`type\(scope\)!: subject`/);
assert.match(finding.message, /one of rules, check-changed/);
assert.match(finding.message, /`fix\(rules\): /);
});
31 changes: 31 additions & 0 deletions .github/pr-checks/pull-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict';

/**
* 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(...)`.
*/
class PullRequest {
/** `pr` holds what `pulls.get` returns that the checks read. */
constructor(pr, { github = null, repo = null } = {}) {
this.number = pr.number;
this.title = pr.title;
this.body = pr.body ?? '';
this.labels = (pr.labels ?? []).map((label) => label.name);
this.base = pr.base?.sha;
this.head = pr.head?.sha;
this.github = github;
this.repo = repo;
}

/** Fetches the pull request the event is about, as it is now: a re-run
* replays the event's payload, which may hold an old title or body. */
static async load({ github, context }) {
const { data } = await github.rest.pulls.get({
...context.repo,
pull_number: context.payload.pull_request.number,
});
return new PullRequest(data, { github, repo: context.repo });
}
}

module.exports = { PullRequest };
59 changes: 59 additions & 0 deletions .github/pr-checks/run.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use strict';

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

/**
* Runs one check from pr-checks.yml's `actions/github-script` step:
* `await Runner.run({ github, context, core })`.
*/
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')];

/** 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
* fails the job, unless the repository deviates from the check or the
* check waives it: then it is a notice, still in the summary. */
static async run({ github, context, core }, env = process.env) {
const check = Runner.CHECKS.find(({ name }) => name === env.CHECK);
if (!check) throw new Error(`no check is named \`${env.CHECK}\``);
const inputs = new Inputs(env.INPUTS, Runner.CHECKS.map(({ name }) => name));
const pr = await PullRequest.load({ github, context });
const findings = await check.findings(pr, inputs);
const deviation = inputs.deviations.get(check.name);
const waiver = deviation
? `the repository deviates from it: ${deviation}`
: await check.waiver?.(pr, inputs);

const lines = findings.map((finding) => Runner.format(check.name, finding));
findings.forEach(({ path, line }, index) => {
const properties = { title: check.name, file: path, startLine: line };
if (waiver) core.notice(lines[index], properties);
else core.error(lines[index], properties);
});
core.summary.addHeading(check.name, 3);
if (findings.length === 0) core.summary.addRaw('Passed.', true);
else core.summary.addCodeBlock(lines.join('\n\n'));
if (waiver && findings.length) core.summary.addRaw(`Allowed: ${waiver}.`, true);
await core.summary.write();
if (findings.length && !waiver) {
core.setFailed(`${check.name} found ${findings.length} problem(s); each says how to fix it.`);
}
}

/** A finding as the crate prints a violation: where, the check and what
* to fix, then how to challenge the check. */
static format(name, { message, path, line }) {
const where = path ? `${path}${line ? `:${line}` : ''}: ` : '';
return (
`${where}[${name}] ${message}\n If the check is wrong here, ask the owner, then add ` +
`\`${name} = "<why>"\` to the \`deviations\` input of this repository's pull request ` +
`workflow, or change the check in sourceorigin-standard for all.`
);
}
}

module.exports = { Runner };
48 changes: 48 additions & 0 deletions .github/pr-checks/run.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const { Runner } = require('./run.js');
const { Fake } = require('./testing.js');

const env = (inputs = {}) => ({ CHECK: 'pr-title', INPUTS: JSON.stringify(inputs) });

test('a finding fails the job with how to fix it and how to challenge the check', async () => {
const core = Fake.core();
await Runner.run({ ...Fake.github({ title: 'Add a thing' }), core }, env());
assert.equal(core.errors.length, 1);
assert.match(core.errors[0].message, /^\[pr-title\] the title `Add a thing`/);
assert.match(core.errors[0].message, /ask the owner, then add `pr-title = "<why>"`/);
assert.match(core.failed, /pr-title found 1 problem/);
assert.match(core.written, /### pr-title\n```\n\[pr-title\]/);
});

test('a passing check says so in the summary', async () => {
const core = Fake.core();
await Runner.run({ ...Fake.github(), core }, env());
assert.deepEqual([core.errors, core.failed], [[], null]);
assert.equal(core.written, '### pr-title\nPassed.\n');
});

test('a deviation turns findings into notices', async () => {
const core = Fake.core();
const deviations = 'pr-title = "titles come from an external tracker"';
await Runner.run({ ...Fake.github({ title: 'x' }), core }, env({ deviations }));
assert.deepEqual([core.errors, core.failed, core.notices.length], [[], null, 1]);
assert.match(core.written, /Allowed: the repository deviates from it: titles come/);
});

test('a deviation needs a known check and a reason', async () => {
for (const deviations of ['pr-size = "big"', 'pr-title = ""', '[x]\npr-title = "y"']) {
await assert.rejects(
Runner.run({ ...Fake.github(), core: Fake.core() }, env({ deviations })),
/the `deviations` input, line \d: `pr-\w+` must be one of pr-title/,
deviations,
);
}
});

test('a finding with a place starts with it', () => {
const text = Runner.format('lint-exceptions', { message: 'm', path: 'src/a.rs', line: 3 });
assert.match(text, /^src\/a\.rs:3: \[lint-exceptions\] m\n {2}If the check/);
});
40 changes: 40 additions & 0 deletions .github/pr-checks/testing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';

/**
* 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
* the API calls with `pr`'s values.
*/
class Fake {
/** A `core` recording annotations, the job summary and the failure. */
static core() {
const core = { errors: [], notices: [], failed: null, written: '' };
let summary = '';
core.error = (message, properties) => core.errors.push({ message, ...properties });
core.notice = (message, properties) => core.notices.push({ message, ...properties });
core.setFailed = (message) => {
core.failed = message;
};
core.summary = {
addHeading: (text) => ((summary += `### ${text}\n`), core.summary),
addRaw: (text) => ((summary += `${text}\n`), core.summary),
addCodeBlock: (text) => ((summary += `\`\`\`\n${text}\n\`\`\`\n`), core.summary),
write: async () => {
core.written = summary;
},
};
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 };
return {
github: { rest: { pulls: { get: async () => ({ data }) } } },
context: { repo: { owner: 'o', repo: 'r' }, payload: { pull_request: { number: 1 } } },
};
}
}

module.exports = { Fake };
Loading
Loading