Skip to content
Merged
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
23 changes: 18 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Add the package at a tag and install its hooks when the repository installs:
```json
{
"scripts": { "prepare": "standard install" },
"devDependencies": { "@mapringg/standard": "github:mapringg/standard#v0.5.0" }
"devDependencies": { "@mapringg/standard": "github:mapringg/standard#v0.5.3" }
}
```

Expand All @@ -22,7 +22,7 @@ Add the package at a tag and install its hooks when the repository installs:
| `standard hook commit-msg <file>` | Checks the commit message. |
| `standard hook pre-commit` | Runs the `hooks.pre-commit` lines. |
| `standard hook pre-push` | Refuses a merge commit that `origin/develop` lacks, then runs the `hooks.pre-push` lines. |
| `standard merge <number> [--admin]` | Squash-merges a pull request into `develop` once its `Check` run is green. See [Merge](#merge). |
| `standard merge <number> [--admin]` | Squash-merges a pull request into `develop` once its newest `Check` run is green. See [Merge](#merge). |
| `standard score [<path>...] [--remote] [--json]` | Reports how far each repository follows the standard. See [Score](#score). |

## Checks
Expand Down Expand Up @@ -62,7 +62,7 @@ Add the package at a tag and install its hooks when the repository installs:
| `size:XL` | 500 to 999 |
| `size:XXL` | 1000 or more |

When `GH_TOKEN` and `GITHUB_REPOSITORY` are set, `pr-size` also creates the label if the repository lacks it, removes any other `size:` label and sets its own. The token needs `issues: write`. A label it cannot set is a warning.
When `GH_TOKEN` and `GITHUB_REPOSITORY` are set, `pr-size` also creates the label if the repository lacks it, removes any other `size:` label and sets its own. The token needs both `issues: write` and `pull-requests: write`: GitHub returns 403 when a token with only `issues: write` reads a pull request's labels. A label it cannot set is a warning.

`baseline-growth` fails a pull request that adds a check to `pending`, or creates or grows a file under `.standard/baselines/`. The one exception is the pull request that removes that check from `pending`: it turns the check on and may start its baseline. It also fails when the head commit tracks a symlink under `.standard`, such as `.standard/config.json`. When the base commit has no `.standard/config.json`, it reads the base's `pending` from a root `standard.json`, so the pull request that moves the config adds nothing to `pending`.

Expand All @@ -82,15 +82,28 @@ Each finding's fix names the change, such as `Delete scripts/merge-pr.mjs, which

## Merge

`standard merge <number>` is the one way to merge a pull request. It reads the pull request and its head commit's check runs live through `gh`, and refuses unless all of these hold:
`standard merge <number>` is the one way to merge a pull request. It reads the pull request, its `ready_for_review` events, the head commit's workflow runs, its check runs, and its workflow runs again, live through `gh`, and refuses unless all of these hold:

- The pull request is open and not a draft.
- Its base is `develop`.
- Its title passes the `pr-title` rules with ` (#<number>)` added.
- A check run named `Check` from GitHub Actions on the exact head commit has concluded `success`. A missing run, a run on an older commit, or a run in any other state refuses, and the message names the runs it found.
- The newest `Check` run on the exact head commit has concluded `success`. The gate counts only check runs named `Check` from GitHub Actions whose workflow run came from a `pull_request` event, so a `push` run on the same commit does not count. Among the `pull_request` runs of the workflow that holds `Check`, the newest is the one whose latest attempt started last (`run_started_at`, then the higher run id). A re-run moves that time forward, and a run that waits in a concurrency group has it before its `Check` run exists, so an older success cannot stand in for a newer run. If the newest run's id, attempt or status differs between the two workflow run reads, the gate refuses with `retry:`, because the check runs it read between them may belong to another attempt. When both reads show the same completed attempt, that attempt ended before the check runs were read, so its `Check` run is the one GitHub lists. A `Check` that did not conclude `success` refuses and names its conclusion. Older runs on the same commit, such as one that `cancel-in-progress` cancelled or one skipped on a `closed` event, do not block. A missing run or a run on an older commit refuses, and the message names the runs it found and the event of each.
- Every `pull_request` workflow run on the head commit has completed, in both workflow run reads. Until then the gate refuses with `wait:`. This covers a run of a workflow whose `Check` run does not exist yet and a re-run that carries a green `Check` from an earlier attempt. So a merge waits for every `pull_request` workflow on the head to finish, not only the one that holds `Check`. Runs from other events, such as `push`, do not hold it.
- That `Check` run started after the pull request last left draft, as its `ready_for_review` events show. The gate reads the start of the `Check` run itself, which a re-run of failed jobs copies from the earlier attempt, so a draft-time result cannot pass through a later attempt. A draft-time run refuses until `Check` runs again.

Then it runs `gh pr merge <number> --squash --match-head-commit <sha> --subject "<title> (#<number>)" --body ""`, so a push after the check cannot be merged unseen. `--admin` passes GitHub's admin flag through for required reviews and still needs a green `Check`. Name the CI job `Check` so the gate can find it.

Because only the newest run decides, the CI workflow can cancel a run that a newer one replaces. Add `ready_for_review` so leaving draft runs `Check` again, and `edited` so a title or description fix runs it again:

```yaml
on:
pull_request:
types: [opened, synchronize, reopened, edited, ready_for_review]
concurrency:
group: ci-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
```

## Score

`standard score` reports how far a repository follows the standard. With no path it scores the repository it runs in. With several paths it prints one column per repository, named by its folder. It runs no check; it reads the files git tracks, `.standard/config.json` and the pin.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@mapringg/standard",
"version": "0.5.2",
"version": "0.5.3",
"description": "One repository standard for every project, run by one command.",
"license": "MIT",
"repository": "github:mapringg/standard",
Expand Down
147 changes: 120 additions & 27 deletions src/merge.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import { subjectNotes } from "./checks/support/subject-rules.mjs";
const BASE = "develop";
const GATE = "Check";
const GATE_APP = "github-actions";
const EVENT = "pull_request";
const PR_FIELDS = "number,title,state,isDraft,baseRefName,headRefOid";
const CHECK_FIELDS = ".check_runs[] | {name, head_sha, status, conclusion, started_at, app: {slug: .app.slug}, check_suite: {id: .check_suite.id}}";
const RUN_FIELDS = ".workflow_runs[] | {id, workflow_id, event, head_sha, check_suite_id, run_attempt, run_started_at, status, conclusion}";
const READY_FIELDS = '.[] | select(.event == "ready_for_review") | {created_at}';
const OUTPUT_LIMIT = 256 * 1024 * 1024;

export const retired = ["scripts/merge-pr.mjs", "scripts/merge-pr.test.mjs"];

Expand All @@ -23,27 +28,108 @@ export const retired = ["scripts/merge-pr.mjs", "scripts/merge-pr.test.mjs"];
* @property {string} head_sha
* @property {string} status
* @property {string | null} conclusion
* @property {string | null} started_at
* @property {{ slug: string } | null} app
* @property {{ id: number }} check_suite
*
* @typedef {object} WorkflowRun
* @property {number} id
* @property {number} workflow_id
* @property {string} event
* @property {string} head_sha
* @property {number} check_suite_id
* @property {number} run_attempt
* @property {string} run_started_at
* @property {string} status
* @property {string | null} conclusion
*
* @typedef {object} HeadRuns
* @property {readonly CheckRun[]} checkRuns
* @property {readonly [readonly WorkflowRun[], readonly WorkflowRun[]]} workflowReads
* @property {string | null} readyAt
*
* @typedef {{ merge: true, args: string[] } | { merge: false, reasons: string[] }} Decision
*/

/**
* @param {CheckRun} run
* @param {ReadonlyMap<number, WorkflowRun>} bySuite
* @returns {string}
*/
function describe(run) {
function describe(run, bySuite) {
const state = run.status === "completed" ? `concluded ${run.conclusion}` : `is ${run.status}`;
return `${run.name} from ${run.app?.slug ?? "an unknown app"} on ${run.head_sha.slice(0, 7)} ${state}`;
const event = bySuite.get(run.check_suite.id)?.event;
const source = event ? `a ${event} run` : "no workflow run";
return `${run.name} from ${run.app?.slug ?? "an unknown app"} on ${run.head_sha.slice(0, 7)} in ${source} ${state}`;
}

/**
* @param {WorkflowRun} a
* @param {WorkflowRun} b
*/
function byStart(a, b) {
return Date.parse(a.run_started_at) - Date.parse(b.run_started_at) || a.id - b.id;
}

/**
* @param {readonly WorkflowRun[]} workflowRuns
* @param {string} head
* @param {ReadonlySet<number | undefined>} workflows
*/
function newestRun(workflowRuns, head, workflows) {
return workflowRuns
.filter((run) => run.event === EVENT && run.head_sha === head && workflows.has(run.workflow_id))
.toSorted(byStart)
.at(-1);
}

/**
* @param {WorkflowRun | undefined} run
*/
function attempt(run) {
return run ? `run ${run.id} attempt ${run.run_attempt} ${run.status}` : "no run";
}

/**
* @param {string} head
* @param {HeadRuns} runs
* @returns {string | null} The reason to refuse.
*/
function gateRefusal(head, { checkRuns, workflowReads: [before, after], readyAt }) {
const unfinished = [...after, ...before].find((run) => run.event === EVENT && run.head_sha === head && run.status !== "completed");
if (unfinished) {
return `wait: ${EVENT} run ${unfinished.id} attempt ${unfinished.run_attempt} of workflow ${unfinished.workflow_id} on ${head.slice(0, 7)} is ${unfinished.status}.`;
}
const bySuite = new Map(after.map((run) => [run.check_suite_id, run]));
const gates = checkRuns.filter((run) => run.name === GATE && run.app?.slug === GATE_APP && run.head_sha === head);
const workflows = new Set(gates.map((run) => bySuite.get(run.check_suite.id)?.workflow_id));
const newest = newestRun(after, head, workflows);
if (!newest) {
const found = checkRuns.length === 0 ? "no check runs" : checkRuns.map((run) => describe(run, bySuite)).join("; ");
return `no ${GATE} run from ${GATE_APP} in a ${EVENT} run on head ${head}. Found ${found}.`;
}
const earlier = newestRun(before, head, workflows);
if (attempt(earlier) !== attempt(newest)) {
return `retry: the newest ${EVENT} run on ${head.slice(0, 7)} changed from ${attempt(earlier)} to ${attempt(newest)} while standard merge read the runs. Run standard merge again.`;
}
const where = `${EVENT} run ${newest.id} attempt ${newest.run_attempt}, the newest on ${head.slice(0, 7)},`;
const gate = gates.find((run) => run.check_suite.id === newest.check_suite_id);
if (!gate) return `${where} concluded ${newest.conclusion} without a ${GATE} run.`;
if (gate.status !== "completed") return `${GATE} in ${where} is ${gate.status}.`;
if (gate.conclusion !== "success") return `${GATE} in ${where} concluded ${gate.conclusion}.`;
if (readyAt && !(Date.parse(gate.started_at ?? "") >= Date.parse(readyAt))) {
return `${GATE} in ${where} started at ${gate.started_at}, before the pull request left draft at ${readyAt}. Rerun ${GATE}, or add ready_for_review to on.pull_request.types.`;
}
return null;
}

/**
* @param {MergeTarget} pr
* @param {readonly CheckRun[]} checkRuns
* @param {HeadRuns} runs
* @param {boolean} admin
* @returns {Decision}
*/
export function mergeDecision(pr, checkRuns, admin) {
export function mergeDecision(pr, runs, admin) {
const reasons = [];
if (pr.state !== "OPEN") reasons.push(`it is ${pr.state.toLowerCase()}, not open.`);
if (pr.isDraft) reasons.push("it is a draft.");
Expand All @@ -53,16 +139,8 @@ export function mergeDecision(pr, checkRuns, admin) {
const suffix = ` (#${pr.number})`;
for (const note of subjectNotes(title, suffix)) reasons.push(`its title breaks a subject rule. ${note}`);

const gates = checkRuns.filter(
(run) => run.name === GATE && run.app?.slug === GATE_APP && run.head_sha === pr.headRefOid,
);
if (gates.length === 0) {
const found = checkRuns.length === 0 ? "no check runs" : checkRuns.map(describe).join("; ");
reasons.push(`no ${GATE} run from ${GATE_APP} on head ${pr.headRefOid}. Found ${found}.`);
}
for (const run of gates) {
if (run.status !== "completed" || run.conclusion !== "success") reasons.push(`${describe(run)}.`);
}
const refusal = gateRefusal(pr.headRefOid, runs);
if (refusal) reasons.push(refusal);

if (reasons.length > 0) return { merge: false, reasons };
return {
Expand All @@ -86,17 +164,30 @@ export function mergeDecision(pr, checkRuns, admin) {
/**
* @param {string} cwd
* @param {string[]} args
* @returns {any}
* @returns {string}
*/
function ghJson(cwd, args) {
function gh(cwd, args) {
try {
return JSON.parse(execFileSync("gh", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }));
return execFileSync("gh", args, { cwd, encoding: "utf8", maxBuffer: OUTPUT_LIMIT, stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
const { stderr = "", message } = /** @type {Error & { stderr?: string }} */ (error);
throw new Error(`gh ${args.join(" ")} failed. ${stderr.trim() || message}`);
}
}

/**
* @param {string} cwd
* @param {string} path
* @param {string} fields
* @returns {any[]}
*/
function ghItems(cwd, path, fields) {
return gh(cwd, ["api", "--paginate", "--jq", fields, `repos/{owner}/{repo}/${path}`])
.split("\n")
.filter((line) => line !== "")
.map((line) => JSON.parse(line));
}

/**
* @param {string} arg
* @returns {string}
Expand All @@ -106,23 +197,25 @@ function quote(arg) {
}

/**
* Reads the pull request and its head's check runs live, so a push after review cannot slip in.
* Reads the pull request, its head's runs and its events live, so a push after review cannot slip in.
* @param {string} cwd
* @param {number} number
* @param {boolean} admin
* @returns {0 | 1}
*/
export function merge(cwd, number, admin) {
/** @type {MergeTarget} */
const pr = ghJson(cwd, ["pr", "view", String(number), "--json", PR_FIELDS]);
/** @type {{ check_runs: CheckRun[] }[]} */
const pages = ghJson(cwd, [
"api",
"--paginate",
"--slurp",
`repos/{owner}/{repo}/commits/${pr.headRefOid}/check-runs?per_page=100`,
]);
const decision = mergeDecision(pr, pages.flatMap((page) => page.check_runs), admin);
const pr = JSON.parse(gh(cwd, ["pr", "view", String(number), "--json", PR_FIELDS]));
/** @type {{ created_at: string }[]} */
const readyEvents = ghItems(cwd, `issues/${number}/events?per_page=100`, READY_FIELDS);
/** @type {() => WorkflowRun[]} */
const readWorkflowRuns = () => ghItems(cwd, `actions/runs?head_sha=${pr.headRefOid}&per_page=100`, RUN_FIELDS);
const before = readWorkflowRuns();
/** @type {CheckRun[]} */
const checkRuns = ghItems(cwd, `commits/${pr.headRefOid}/check-runs?filter=latest&per_page=100`, CHECK_FIELDS);
const after = readWorkflowRuns();
const readyAt = readyEvents.map((event) => event.created_at).sort().at(-1) ?? null;
const decision = mergeDecision(pr, { checkRuns, workflowReads: [before, after], readyAt }, admin);
if (!decision.merge) {
console.error(`standard merge: refusing #${number}, because`);
for (const reason of decision.reasons) console.error(` ${reason}`);
Expand Down
2 changes: 1 addition & 1 deletion test/helpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export const WIRED = {
".standard/config.json": {},
"package.json": {
scripts: { prepare: "standard install" },
devDependencies: { "@mapringg/standard": "github:mapringg/standard#v0.5.2" },
devDependencies: { "@mapringg/standard": "github:mapringg/standard#v0.5.3" },
},
".github/workflows/ci.yml": [
"on:",
Expand Down
Loading