diff --git a/.github/filters.yml b/.github/filters.yml index d6e2db3..a87f67d 100644 --- a/.github/filters.yml +++ b/.github/filters.yml @@ -20,3 +20,8 @@ deny: - *workspace - deny.toml - '**/Cargo.toml' +pr-checks: + - .github/workflows/ci.yml + - .github/filters.yml + - justfile + - .github/pr-checks/** diff --git a/.github/pr-checks/inputs.js b/.github/pr-checks/inputs.js new file mode 100644 index 0000000..d0b78c7 --- /dev/null +++ b/.github/pr-checks/inputs.js @@ -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} = ""\``, + ); + } + 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 }; diff --git a/.github/pr-checks/pr-title.js b/.github/pr-checks/pr-title.js new file mode 100644 index 0000000..b229870 --- /dev/null +++ b/.github/pr-checks/pr-title.js @@ -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 ( + /^(?\w+)(?:\((?[^()]*)\))?(?!)?: (?\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; diff --git a/.github/pr-checks/pr-title.test.js b/.github/pr-checks/pr-title.test.js new file mode 100644 index 0000000..fb73702 --- /dev/null +++ b/.github/pr-checks/pr-title.test.js @@ -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\): /); +}); diff --git a/.github/pr-checks/pull-request.js b/.github/pr-checks/pull-request.js new file mode 100644 index 0000000..0b3a61a --- /dev/null +++ b/.github/pr-checks/pull-request.js @@ -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 }; diff --git a/.github/pr-checks/run.js b/.github/pr-checks/run.js new file mode 100644 index 0000000..6a9a4a9 --- /dev/null +++ b/.github/pr-checks/run.js @@ -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} = ""\` to the \`deviations\` input of this repository's pull request ` + + `workflow, or change the check in sourceorigin-standard for all.` + ); + } +} + +module.exports = { Runner }; diff --git a/.github/pr-checks/run.test.js b/.github/pr-checks/run.test.js new file mode 100644 index 0000000..f55c40f --- /dev/null +++ b/.github/pr-checks/run.test.js @@ -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 = ""`/); + 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/); +}); diff --git a/.github/pr-checks/testing.js b/.github/pr-checks/testing.js new file mode 100644 index 0000000..c72bd40 --- /dev/null +++ b/.github/pr-checks/testing.js @@ -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 }; diff --git a/.github/pr-checks/toml.js b/.github/pr-checks/toml.js new file mode 100644 index 0000000..e5864ed --- /dev/null +++ b/.github/pr-checks/toml.js @@ -0,0 +1,157 @@ +'use strict'; + +/** + * Just enough TOML for the pull request checks, without a dependency: each + * key with its table and raw value, so a check can compare a manifest before + * and after a pull request. Values stay raw text; `string` and `items` read + * the ones a check needs. + */ +class Toml { + /** Reads `text`, which needn't be valid TOML: what can't be read is skipped. */ + constructor(text) { + /** Each `key = value`: `{ table, key, value, line, section }`, where + * `section` counts the table headers before it, so the entries of one + * `[[array.table]]` element share it. Dotted keys stay joined: `a.b`. */ + this.entries = []; + let table = ''; + let section = 0; + for (const { text: statement, line } of Toml.statements(text)) { + if (statement.startsWith('[')) { + table = Toml.key(statement.replace(/^\[\[?|\]?\]$/g, '')); + section += 1; + continue; + } + const equals = Toml.find(statement, '='); + if (equals < 0) continue; + this.entries.push({ + table, + key: Toml.key(statement.slice(0, equals)), + value: statement.slice(equals + 1).trim(), + line, + section, + }); + } + } + + /** The entries of `table`, such as `workspace.dependencies`. */ + table(name) { + return this.entries.filter((entry) => entry.table === name); + } + + /** The value of a string, or `null` for any other value. */ + static string(value) { + for (const quote of ['"""', "'''", '"', "'"]) { + if (value.length >= 2 * quote.length && value.startsWith(quote) && value.endsWith(quote)) { + const inner = value.slice(quote.length, -quote.length); + if (quote !== '"') return inner; + try { + return JSON.parse(value); + } catch { + return inner; + } + } + } + return null; + } + + /** The elements of an array, 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, ''))) { + if (!quoted && (c === '[' || c === '{')) depth += 1; + if (!quoted && (c === ']' || c === '}')) depth -= 1; + if (!quoted && depth === 0 && c === ',') { + items.push(current); + current = ''; + } else { + current += c; + } + } + items.push(current); + return items.map((item) => item.replace(/\s+/g, ' ').trim()).filter(Boolean); + } + + /** A key or table name, its dotted parts trimmed and unquoted. */ + static key(text) { + const parts = []; + let current = ''; + for (const { c, quoted } of Toml.characters(text)) { + if (!quoted && c === '.') { + parts.push(current); + current = ''; + } else { + current += c; + } + } + parts.push(current); + return parts.map((part) => Toml.string(part.trim()) ?? part.trim()).join('.'); + } + + /** Where `char` first appears outside strings in `text`, or -1. */ + static find(text, char) { + let index = 0; + for (const { c, quoted } of Toml.characters(text)) { + if (!quoted && c === char) return index; + index += c.length; + } + return -1; + } + + /** Each statement (a header or a key and its value, which may span lines + * inside brackets), with comments dropped, and the line it starts on. */ + static *statements(text) { + let current = ''; + let start = 1; + let line = 1; + let depth = 0; + for (const { c, quoted } of Toml.characters(text)) { + if (c === '\n') line += 1; + if (!quoted && c === '\n' && depth <= 0) { + if (current.trim()) yield { text: current.trim(), line: start }; + current = ''; + depth = 0; + continue; + } + if (!quoted && (c === '[' || c === '{')) depth += 1; + if (!quoted && (c === ']' || c === '}')) depth -= 1; + if (!current.trim() && c.trim()) start = line; + current += c === '\n' && !quoted ? ' ' : c; + } + if (current.trim()) yield { text: current.trim(), line: start }; + } + + /** Each character of `text` outside comments, and whether it sits in a + * string. A newline ends a single-line string, so bad input can't swallow + * the rest of the file. */ + static *characters(text) { + let quote = null; + for (let i = 0; i < text.length; i += 1) { + const c = text[i]; + if (quote) { + if (c === '\\' && quote[0] === '"' && i + 1 < text.length) { + yield { c: c + text[i + 1], quoted: true }; + i += 1; + } else if (text.startsWith(quote, i)) { + yield { c: quote, quoted: true }; + i += quote.length - 1; + quote = null; + } else { + if (c === '\n' && quote.length === 1) quote = null; + yield { c, quoted: quote !== null }; + } + } else if (c === '"' || c === "'") { + quote = text.startsWith(c.repeat(3), i) ? c.repeat(3) : c; + yield { c: quote, quoted: true }; + i += quote.length - 1; + } else if (c === '#') { + while (i + 1 < text.length && text[i + 1] !== '\n') i += 1; + } else { + yield { c, quoted: false }; + } + } + } +} + +module.exports = { Toml }; diff --git a/.github/pr-checks/toml.test.js b/.github/pr-checks/toml.test.js new file mode 100644 index 0000000..f714c96 --- /dev/null +++ b/.github/pr-checks/toml.test.js @@ -0,0 +1,45 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { Toml } = require('./toml.js'); + +test('entries carry their table, line and section, comments dropped', () => { + const toml = new Toml( + ['top = 1 # a comment', '', '[workspace.dependencies]', 'serde = "1" # why', 'a.b = 2'].join('\n'), + ); + assert.deepEqual(toml.entries, [ + { table: '', key: 'top', value: '1', line: 1, section: 0 }, + { table: 'workspace.dependencies', key: 'serde', value: '"1"', line: 4, section: 1 }, + { table: 'workspace.dependencies', key: 'a.b', value: '2', line: 5, section: 1 }, + ]); +}); + +test('a value spanning lines inside brackets is one entry', () => { + const toml = new Toml('ignore = [\n "A", # first\n { id = "B", reason = "x]" },\n]\nnext = 1'); + assert.equal(toml.entries.length, 2); + assert.deepEqual(Toml.items(toml.entries[0].value), ['"A"', '{ id = "B", reason = "x]" }']); + assert.equal(toml.entries[1].line, 5); +}); + +test('a comment sign inside a string is text', () => { + assert.equal(new Toml('a = "x # y"').entries[0].value, '"x # y"'); +}); + +test('quoted keys and array table headers read as their names', () => { + const toml = new Toml('[[licenses.exceptions]]\n"my.crate" = 1\n[[licenses.exceptions]]\nb = 2'); + assert.deepEqual( + toml.entries.map(({ table, key, section }) => [table, key, section]), + [ + ['licenses.exceptions', 'my.crate', 1], + ['licenses.exceptions', 'b', 2], + ], + ); +}); + +test('strings read whatever their quotes', () => { + assert.equal(Toml.string('"a\\"b"'), 'a"b'); + assert.equal(Toml.string("'a\\b'"), 'a\\b'); + assert.equal(Toml.string('"""a\nb"""'), 'a\nb'); + assert.equal(Toml.string('12'), null); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12a784a..da1d23d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,7 @@ jobs: outputs: rust: ${{ github.event_name != 'pull_request' || steps.filter.outputs.rust == 'true' }} deny: ${{ github.event_name != 'pull_request' || steps.filter.outputs.deny == 'true' }} + pr-checks: ${{ github.event_name != 'pull_request' || steps.filter.outputs.pr-checks == 'true' }} steps: # The filters file only: the action lists the changed paths through # the GitHub API. @@ -111,6 +112,22 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - run: just standard + # The scripts of pr-checks.yml, the workflow other repositories call. + pr-check-scripts: + name: pr-check-scripts + needs: changes + if: needs.changes.outputs.pr-checks == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: taiki-e/install-action@3f74d7c16a4242f1c95561e98edc25d36adb4375 # v2 + with: + tool: just + - run: just test-pr-checks + ci: name: ci if: always() @@ -119,10 +136,11 @@ jobs: - checks - rust - standard + - pr-check-scripts runs-on: ubuntu-latest timeout-minutes: 5 steps: - uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # v1.3.0 with: - allowed-skips: checks, rust + allowed-skips: checks, rust, pr-check-scripts jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml new file mode 100644 index 0000000..d016c97 --- /dev/null +++ b/.github/workflows/pr-checks.yml @@ -0,0 +1,65 @@ +# The standard's checks of a pull request itself, which each repository calls +# from a small workflow (see the crate's README). The checks read the pull +# request through the API and run .github/pr-checks at this workflow's own +# commit, so a caller pins one SHA. A merge group passes: its pull requests +# passed these checks before joining the queue. + +name: PR checks + +on: + workflow_call: + inputs: + scopes: + description: The scopes a title may take, separated by spaces. + type: string + default: "" + deviations: + description: Lines of `check = "why"`, for checks the repository departs from. + type: string + default: "" + +permissions: + contents: read + +jobs: + check: + name: ${{ matrix.check }} + if: github.event_name != 'merge_group' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + strategy: + fail-fast: false + matrix: + check: [pr-title] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .standard + persist-credentials: false + sparse-checkout: .github/pr-checks + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + CHECK: ${{ matrix.check }} + INPUTS: ${{ toJSON(inputs) }} + with: + script: | + const { Runner } = require('./.standard/.github/pr-checks/run.js'); + await Runner.run({ github, context, core }); + + # The one check a ruleset requires of this workflow. + pr-checks: + name: pr-checks + if: always() + needs: check + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # v1.3.0 + with: + allowed-skips: check + jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 0000000..b4ca168 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,28 @@ +# Runs the standard's pull request checks on this repository's own pull +# requests, as every repository does. Reviews and labels re-run them, since +# some checks accept an approval or a label. + +name: PR + +on: + pull_request: + types: [opened, edited, synchronize, reopened, labeled, unlabeled] + pull_request_review: + types: [submitted, dismissed] + merge_group: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + standard: + uses: ./.github/workflows/pr-checks.yml + permissions: + contents: read + pull-requests: read + with: + scopes: check-changed rules lints pr-checks xtask diff --git a/AGENTS.md b/AGENTS.md index aa9de18..863ebb1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,11 @@ in this crate, a CI check on the pull request, a cleanup-pass skill. documentation and shows how a repository's xtask uses it. - `tools/xtask`: this repository's own `cargo xtask`, which uses the crate as the other repositories do. +- `.github/workflows/pr-checks.yml`: the reusable workflow that checks a + pull request itself (its title, description, commits and the exceptions + it adds), which each repository calls and this one dogfoods from + `pr.yml`. Its logic is in `.github/pr-checks`, Node scripts without + dependencies, tested by `just test-pr-checks`. Terms that are easy to mix up: @@ -83,7 +88,9 @@ this list and say which entries applied: - the crate's README, whose example is how a repository's xtask wires it in; - the pull request's note of what each repository's xtask must change when the API breaks; -- this repository's own `tools/xtask`, which uses the crate as the others do. +- this repository's own `tools/xtask`, which uses the crate as the others do; +- for `pr-checks.yml`, the README's caller workflow and inputs, and this + repository's own `pr.yml`. ## Issues, commits & pull requests diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index c52d92e..464fd54 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -11,7 +11,7 @@ a rule gets in the way, stop and ask the user why, and with their approval add a deviation, with its reason, to the repository's `standard.toml`, or change the rule here, in the same pull request. -A repository adopts the standard in four steps: +A repository adopts the standard in five steps: 1. Its `tools/xtask` depends on this crate from crates.io and runs [`rules::check`] as `cargo xtask standard`, as @@ -25,6 +25,10 @@ A repository adopts the standard in four steps: 4. It commits `standard.toml` when it needs settings or deviations, and `budget.toml`, under `CODEOWNERS`, when it has `#[expect]` attributes or `// INVARIANT:` comments. +5. A workflow of its own calls this repository's pull request checks, as + [below](#pull-request-checks) shows, and its ruleset requires two + checks: `ci`, for the code, and `standard / pr-checks`, for the pull + request. ## The rules @@ -117,6 +121,72 @@ piqueld = 2 [`rules::report`]: https://docs.rs/sourceorigin-standard/latest/sourceorigin_standard/rules/fn.report.html [`rules::describe`]: https://docs.rs/sourceorigin-standard/latest/sourceorigin_standard/rules/fn.describe.html +## Pull request checks + +Some rules are about a pull request itself rather than the code, so +`.github/workflows/pr-checks.yml` in this repository checks them, reading +the pull request through the GitHub API, without a checkout or a toolchain. +Each check is a job, and a finding says what to fix and how to challenge the +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. + +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 +accept an approval or a label: + +```yaml +name: PR + +on: + pull_request: + types: [opened, edited, synchronize, reopened, labeled, unlabeled] + pull_request_review: + types: [submitted, dismissed] + merge_group: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + standard: + uses: sourceorigin-dev/sourceorigin-standard/.github/workflows/pr-checks.yml@ # main + permissions: + contents: read + pull-requests: read + with: + scopes: daemon cli web +``` + +Its inputs: + +- `scopes`: the scopes a title may take, separated by spaces. Without it, a + title takes no scope. +- `deviations`: lines of `check = "why"`, for the checks the repository + departs from, whose findings then pass as notices. + +The repository's ruleset requires two checks: `ci`, the summary of +`ci.yml`, for the code, and `standard / pr-checks`, the summary of these +checks, for the pull request. They can't share one: editing a description, +labelling or reviewing re-runs these checks, and `ci.yml` re-running on +each would either rebuild everything or replace a failed `ci` with one that +skipped the code. A merge group passes them, its pull +requests having passed. `CODEOWNERS` gives the owner the files that loosen a +rule: + +```text +/standard.toml @PiquelChips +/budget.toml @PiquelChips +/clippy.toml @PiquelChips +/deny.toml @PiquelChips +``` + ## `check-changed` Runs CI's quick checks for only what changed since the merge base with diff --git a/justfile b/justfile index f945c27..4934409 100644 --- a/justfile +++ b/justfile @@ -5,7 +5,7 @@ default: validate # Formats the sources, then runs every check CI runs. -validate: fmt lint standard test doc doc-test audit unused package +validate: fmt lint standard test test-pr-checks doc doc-test audit unused package build: @cargo build --locked --workspace --all-targets @@ -40,6 +40,10 @@ standard: test *ARGS='--workspace': @cargo nextest run --locked "$@" +# The scripts of .github/workflows/pr-checks.yml, under Node's test runner. +test-pr-checks: + @node --test .github/pr-checks/*.test.js + # Rustdoc warnings, such as broken intra-doc links, fail the build. doc: @RUSTDOCFLAGS='-D warnings' cargo doc --locked --workspace --no-deps diff --git a/tools/xtask/src/ci.rs b/tools/xtask/src/ci.rs index dca9971..911b18c 100644 --- a/tools/xtask/src/ci.rs +++ b/tools/xtask/src/ci.rs @@ -10,16 +10,18 @@ pub enum Filter { Workspace, Rust, Deny, + PrChecks, } impl check_changed::Filter for Filter { - const ALL: &'static [Self] = &[Self::Workspace, Self::Rust, Self::Deny]; + const ALL: &'static [Self] = &[Self::Workspace, Self::Rust, Self::Deny, Self::PrChecks]; fn name(self) -> &'static str { match self { Self::Workspace => "workspace", Self::Rust => "rust", Self::Deny => "deny", + Self::PrChecks => "pr-checks", } } } @@ -61,6 +63,11 @@ pub const CI: Ci = Ci { just(&["just", "package"]), ], }, + Job { + id: "pr-check-scripts", + trigger: Trigger::AnyOf(&[Filter::PrChecks]), + recipes: &[just(&["just", "test-pr-checks"])], + }, ], ignored: &["ci"], };