diff --git a/.github/scripts/pr-event.cjs b/.github/scripts/pr-event.cjs new file mode 100644 index 0000000..a12fe0b --- /dev/null +++ b/.github/scripts/pr-event.cjs @@ -0,0 +1,26 @@ +// Finds the pull request into `base` a "PR event" run was started for. The run +// of a fork does not name its pull request, so match its head repository, +// branch and exact commit. Returns null unless exactly one pull request matches. +async function findPullRequest({ github, context, core, base, state = 'open' }) { + const run = context.payload.workflow_run; + if (!run.head_repository) { + core.info('The head repository of this run no longer exists; nothing to do.'); + return null; + } + const pulls = await github.paginate(github.rest.pulls.list, { + ...context.repo, + state, + base, + head: `${run.head_repository.owner.login}:${run.head_branch}`, + per_page: 100, + }); + const matches = pulls.filter(pr => + pr.head.sha === run.head_sha && pr.head.repo?.id === run.head_repository.id); + if (matches.length !== 1) { + core.info(`${matches.length} ${state} pull requests have head ${run.head_sha}; nothing to do.`); + return null; + } + return matches[0]; +} + +module.exports = { findPullRequest }; diff --git a/.github/scripts/pr-labels.cjs b/.github/scripts/pr-labels.cjs new file mode 100644 index 0000000..0c7a0e5 --- /dev/null +++ b/.github/scripts/pr-labels.cjs @@ -0,0 +1,47 @@ +// The release-notes labels a pull request can carry. The pull request +// template puts each one in backticks at the end of a "Types of changes" +// checkbox bullet, e.g. - [x] CI / workflow change: `ci` +const KNOWN = [ + 'breaking-change', 'bugfix', 'refactor', + 'new-feature', 'enhancement', 'maintenance', + 'ci', 'dependencies', 'documentation', +]; + +// Returns { label } for a ticked box, { existing } for a known label already on the PR, else { error }. +function chooseLabel(pr) { + const re = /^\s*-\s*\[x\][^`\n]*`([^`]+)`/gim; + const ticked = []; + for (const m of (pr.body || '').matchAll(re)) { + const name = m[1].trim(); + if (KNOWN.includes(name) && !ticked.includes(name)) { + ticked.push(name); + } + } + if (ticked.length > 1) { + return { + error: `Multiple "Types of changes" checkboxes are ticked ` + + `(${ticked.join(', ')}). Tick exactly one.`, + }; + } + // The description is the source of truth, so a ticked box always wins. + // That keeps the label in step when someone reconsiders the type after + // opening. Only with nothing ticked does a label already on the pull + // request count, covering pull requests opened without the template. + if (ticked.length === 1) { + return { label: ticked[0] }; + } + // Two or more known labels are ambiguous, so those fail rather than guess. + const existing = (pr.labels || []) + .map(l => l.name) + .filter(n => KNOWN.includes(n)); + if (existing.length === 1) { + return { existing: existing[0] }; + } + return { + error: 'No "Types of changes" checkbox is ticked in the PR ' + + 'description. Edit the description and tick exactly ' + + 'one box so this PR can be release-noted.', + }; +} + +module.exports = { KNOWN, chooseLabel }; diff --git a/.github/workflows/pr-event.yml b/.github/workflows/pr-event.yml new file mode 100644 index 0000000..b05a06f --- /dev/null +++ b/.github/workflows/pr-event.yml @@ -0,0 +1,31 @@ +name: PR event + +# Carries no data and has no permissions. Workflows that need to act on pull +# requests from forks listen for this one through workflow_run, then read the +# pull request from the API with their own token. The run name holds the event +# action and, for a label change, the label, so a listener can pick the events +# it handles. A pull request controls its own copy of this file, so a listener +# never trusts the run name for anything else. +run-name: ${{ github.event.action }} ${{ github.event.label.name }} + +on: + pull_request: + types: + - opened + - reopened + - synchronize + - edited + - ready_for_review + - labeled + - unlabeled + +permissions: {} + +jobs: + notify: + name: Notify + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Nothing to do + run: "true" diff --git a/.github/workflows/pr-labels.yaml b/.github/workflows/pr-labels.yaml index fe31b79..4cb6865 100644 --- a/.github/workflows/pr-labels.yaml +++ b/.github/workflows/pr-labels.yaml @@ -4,10 +4,15 @@ name: PR Labels # Each PR must carry exactly one of the labels the release notes sort by. # The label comes from the ticked "Types of changes" checkbox in the PR # template, since external contributors can't label their own PRs. +# +# Verify runs on the pull request itself, without write access. The +# Apply job runs from `main` after the "PR event" workflow and reads the +# pull request through the API, so pull requests from forks get their +# label as well. # yamllint disable-line rule:truthy on: - pull_request_target: + pull_request: types: - opened - edited @@ -18,78 +23,96 @@ on: - ready_for_review branches: - main + workflow_run: + workflows: [PR event] + types: [completed] -permissions: - pull-requests: write +permissions: {} jobs: pr_labels: name: Verify runs-on: ubuntu-latest # Bots like Dependabot don't use the template and label their own PRs. - if: github.event.pull_request.user.type != 'Bot' + if: >- + github.event_name == 'pull_request' + && github.event.pull_request.user.type != 'Bot' + permissions: + contents: read + concurrency: + group: pr-labels-verify-${{ github.event.pull_request.number }} steps: - - name: 🏷 Apply label from PR description checkbox + - name: ⤵️ Check out the label rules + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/scripts + persist-credentials: false + + - name: 🏷 Check the "Types of changes" checkbox uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | - const known = [ - 'breaking-change', 'bugfix', 'new-feature', 'enhancement', - 'refactor', 'documentation', 'maintenance', 'ci', 'dependencies', - ]; + const { chooseLabel } = require( + `${process.env.GITHUB_WORKSPACE}/.github/scripts/pr-labels.cjs`); + const result = chooseLabel(context.payload.pull_request); + if (result.error) { + core.setFailed(result.error); + } - const { owner, repo } = context.repo; - const issue_number = context.payload.pull_request.number; - const current = (context.payload.pull_request.labels || []) - .map(l => l.name); + apply: + name: Apply + runs-on: ubuntu-latest + if: github.event_name == 'workflow_run' + permissions: + contents: read + pull-requests: write + # Overlapping runs for the same PR can each read a label set the + # other is about to change and leave a stale label behind, so they + # run one at a time. + concurrency: + group: >- + ${{ github.workflow }}-${{ github.event.workflow_run.head_repository.full_name }}-${{ + github.event.workflow_run.head_branch }} + cancel-in-progress: false + steps: + - name: ⤵️ Check out the label rules + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/scripts + persist-credentials: false - // Match a ticked bullet whose first backticked word is a label, - // e.g. - [x] CI / workflow change: `ci` - const body = context.payload.pull_request.body || ''; - const re = /^\s*-\s*\[x\][^`\n]*`([^`]+)`/gim; - const ticked = []; - for (const m of body.matchAll(re)) { - const name = m[1].trim(); - if (known.includes(name) && !ticked.includes(name)) { - ticked.push(name); - } - } + - name: 🏷 Apply label from PR description checkbox + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const dir = `${process.env.GITHUB_WORKSPACE}/.github/scripts`; + const { findPullRequest } = require(`${dir}/pr-event.cjs`); + const { KNOWN, chooseLabel } = require(`${dir}/pr-labels.cjs`); - if (ticked.length > 1) { - core.setFailed( - `Multiple "Types of changes" checkboxes are ticked ` + - `(${ticked.join(', ')}). Tick exactly one.` - ); + // A PR merged right after opening still gets its label. + const pr = await findPullRequest({ github, context, core, base: 'main' }) + ?? await findPullRequest({ github, context, core, base: 'main', state: 'closed' }); + if (!pr || pr.user.type === 'Bot') { return; } - // A ticked box wins. Without one, accept a single known label - // already on the PR, for PRs opened without the template. - if (ticked.length === 0) { - const existing = current.filter(n => known.includes(n)); - if (existing.length === 1) { - core.info(`Skipping: PR already labelled '${existing[0]}'.`); - return; - } - core.setFailed( - 'No "Types of changes" checkbox is ticked in the PR ' + - 'description. Edit the description and tick exactly ' + - 'one box so this PR can be release-noted.' - ); + const { owner, repo } = context.repo; + const issue_number = pr.number; + const current = pr.labels.map(l => l.name); + const { label } = chooseLabel(pr); + if (!label) { return; } - const desired = ticked[0]; - for (const name of current) { - if (known.includes(name) && name !== desired) { + if (KNOWN.includes(name) && name !== label) { await github.rest.issues.removeLabel({ owner, repo, issue_number, name, }).catch(() => {}); } } - if (!current.includes(desired)) { + if (!current.includes(label)) { await github.rest.issues.addLabels({ - owner, repo, issue_number, labels: [desired], + owner, repo, issue_number, labels: [label], }); }