mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
ci: a PR author's own comment can carry the Studio and player captures (#8800)
* ci: a PR author's own comment can carry the Studio and player captures The captures check reads the PR description, then each comment by the PR's author, each on its own with the same parser. Anyone else's comment never counts. An author comment created, edited or deleted re-runs the PR's newest check for its head, so the required check at the head updates. * ci: the captures re-check re-runs only a finished check, and no other comment cancels it A comment run now has a concurrency group of its own, and only the recheck job, which runs for the author's comments alone, shares one per PR. The re-run takes only a completed run whose conclusion is success, failure or cancelled, so a fork PR's run waiting for approval is never re-run.
This commit is contained in:
@@ -12,16 +12,20 @@ on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
branches: [main]
|
||||
# Runs this file from main, never the PR's code: it only re-runs the PR's own check, which reads the comments.
|
||||
issue_comment:
|
||||
types: [created, edited, deleted]
|
||||
|
||||
# A comment run gets a group of its own: anyone's comment starts one, and only the recheck job's group may cancel.
|
||||
concurrency:
|
||||
group: pr-captures-${{ github.event.pull_request.number || github.ref }}
|
||||
group: pr-captures-${{ github.event.pull_request.number || (github.event_name == 'issue_comment' && github.run_id) || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
captures:
|
||||
name: Studio and player captures
|
||||
# A merge group has no PR body to read; the queued PR passed this check already.
|
||||
if: github.event_name != 'merge_group'
|
||||
if: github.event_name != 'merge_group' && github.event_name != 'issue_comment'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
@@ -40,4 +44,48 @@ jobs:
|
||||
HEAD_REPO: ${{ fromJSON(steps.pr.outputs.pr).head.repo.full_name }}
|
||||
BASE_REPO: ${{ github.repository }}
|
||||
HEAD_SHA: ${{ fromJSON(steps.pr.outputs.pr).head.sha }}
|
||||
run: node scripts/check-pr-captures.mjs --base "origin/$BASE_REF" --head "$HEAD_SHA"
|
||||
PR_AUTHOR: ${{ fromJSON(steps.pr.outputs.pr).user.login }}
|
||||
PR_COMMENTS_FILE: ${{ runner.temp }}/pr-comments.json
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh api --paginate --slurp "repos/$BASE_REPO/issues/$PR_NUMBER/comments" > "$PR_COMMENTS_FILE"
|
||||
node scripts/check-pr-captures.mjs --base "origin/$BASE_REF" --head "$HEAD_SHA"
|
||||
|
||||
recheck:
|
||||
name: Re-check captures after an author comment
|
||||
# The required check reports on the PR head only from a pull_request run, so the newest one for the head is re-run.
|
||||
if: >-
|
||||
github.event_name == 'issue_comment' && github.event.issue.pull_request &&
|
||||
github.event.comment.user.login == github.event.issue.user.login
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
concurrency:
|
||||
group: pr-captures-recheck-${{ github.event.issue.number }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
actions: write
|
||||
pull-requests: read
|
||||
steps:
|
||||
- env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.issue.number }}
|
||||
# Only a run that ran: a fork PR's run waiting for approval is completed with conclusion action_required.
|
||||
RERUNNABLE: >-
|
||||
select(.status == "completed" and
|
||||
(.conclusion == "success" or .conclusion == "failure" or .conclusion == "cancelled")) | .id
|
||||
run: |
|
||||
head=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.sha)
|
||||
run=$(gh api -X GET "repos/$GITHUB_REPOSITORY/actions/workflows/pr-captures.yml/runs" \
|
||||
-f event=pull_request -f head_sha="$head" -f per_page=1 --jq '.workflow_runs[0].id // empty')
|
||||
if [ -z "$run" ]; then
|
||||
echo "::notice::No pull_request run at $head yet; it reads the comments when it runs."
|
||||
exit 0
|
||||
fi
|
||||
gh run watch "$run" -R "$GITHUB_REPOSITORY" > /dev/null || true
|
||||
ran=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run" --jq "$RERUNNABLE")
|
||||
if [ -z "$ran" ]; then
|
||||
echo "::notice::Run $run did not finish a check (waiting for approval, or skipped); not re-run."
|
||||
exit 0
|
||||
fi
|
||||
gh run rerun "$ran" -R "$GITHUB_REPOSITORY"
|
||||
echo "Re-ran run $ran, which reports on $head."
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
// Fail a PR touching packages/studio or packages/player unless its body has Before and After sections with media.
|
||||
// Fail a PR touching packages/studio or packages/player unless its body, or one comment by its author, has Before
|
||||
// and After sections with media.
|
||||
// Markdown and tests under them are not behaviour a user sees, so they are not watched.
|
||||
// usage: node scripts/check-pr-captures.mjs --base origin/main --head <sha>; the body arrives in the env (see main).
|
||||
// usage: node scripts/check-pr-captures.mjs --base origin/main --head <sha>; the body, author and comments file arrive
|
||||
// in the env (see main).
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { readFileSync, realpathSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
export const WATCHED_PREFIXES = ["packages/studio/", "packages/player/"];
|
||||
@@ -154,7 +156,7 @@ export function noVisibleChangeFailures(files) {
|
||||
}
|
||||
|
||||
function sectionProblem(section, name) {
|
||||
if (!section) return `the body has no "${name}" heading`;
|
||||
if (!section) return `no "${name}" heading`;
|
||||
return hasMedia(section.text) ? null : `the "${name}" section has no image or video`;
|
||||
}
|
||||
|
||||
@@ -445,14 +447,12 @@ function readNumstat(base, head) {
|
||||
}
|
||||
}
|
||||
|
||||
function printFailure(problems, prNumber) {
|
||||
console.error(
|
||||
"This PR changes packages/studio or packages/player, so its body must show the behaviour.",
|
||||
);
|
||||
for (const problem of problems) console.error(` - ${problem}`);
|
||||
function printFailure(prNumber) {
|
||||
console.error("\nAdd '## Before' and '## After' sections, each with an image or video, then:");
|
||||
console.error(` ${attachCommand(prNumber)}`);
|
||||
console.error("Only the PR description counts; captures posted as comments are not read.");
|
||||
console.error(
|
||||
"The PR description counts, and so does one comment by the PR's author on its own; nobody else's comment counts.",
|
||||
);
|
||||
console.error(
|
||||
"Edit the body text first: gh pr edit --body-file replaces the body and drops attachments.",
|
||||
);
|
||||
@@ -485,26 +485,70 @@ function reportCaptureProblems({ unreadable, identical, refused, notices }, env)
|
||||
printList("Links the duplicate check could not compare:", notices, console.log);
|
||||
}
|
||||
|
||||
const prFromEnv = (env) => ({ body: env.PR_BODY ?? "", number: env.PR_NUMBER ?? "<number>" });
|
||||
const findProblems = (body, files) =>
|
||||
files.length > 0 ? duplicateCaptureProblems(body) : noProblems();
|
||||
/** The description, then each comment by the PR's author; each is checked alone, never joined to the body. */
|
||||
export function captureSources(body, comments, author) {
|
||||
const own = author ? comments.filter((comment) => comment.user?.login === author) : [];
|
||||
return [
|
||||
{ label: "the PR description", text: body },
|
||||
...own.map((comment) => ({ label: `comment ${comment.html_url}`, text: comment.body ?? "" })),
|
||||
];
|
||||
}
|
||||
|
||||
/** The verdict for one source: the section check, then the duplicate check only when the sections hold. */
|
||||
export async function checkSource(text, files, download, env) {
|
||||
const { ok, problems } = evaluate({ body: text, files });
|
||||
if (!ok) return { ok: false, problems };
|
||||
const found = await duplicateCaptureProblems(text, download);
|
||||
return { ok: !blocking(found.unreadable, [...found.identical, ...found.refused], env), found };
|
||||
}
|
||||
|
||||
/** `gh api --paginate --slurp` gives one array per page. Unset means no comments (a local run). */
|
||||
function readComments(path) {
|
||||
if (!path) return [];
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8")).flat();
|
||||
} catch (error) {
|
||||
console.error(`cannot read the PR comments from ${path}: ${error.message}`);
|
||||
return process.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
function reportSource(label, verdict, env) {
|
||||
console.error(`${label}:`);
|
||||
if (verdict.found) reportCaptureProblems(verdict.found, env);
|
||||
else printList("does not show the behaviour:", verdict.problems);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const numstat = readNumstat(flag(args, "--base", "origin/main"), flag(args, "--head", "HEAD"));
|
||||
const { body, number } = prFromEnv(process.env);
|
||||
const env = process.env;
|
||||
const files = parseNumstat(numstat);
|
||||
const { ok, problems } = evaluate({ body, files });
|
||||
if (!ok) {
|
||||
printFailure(problems, number);
|
||||
const sources = captureSources(
|
||||
env.PR_BODY ?? "",
|
||||
readComments(env.PR_COMMENTS_FILE),
|
||||
env.PR_AUTHOR,
|
||||
);
|
||||
const download = perCheckDownloader();
|
||||
const failed = [];
|
||||
for (const source of files.length > 0 ? sources : []) {
|
||||
const verdict = await checkSource(source.text, files, download, env);
|
||||
if (verdict.ok) {
|
||||
if (verdict.found) reportCaptureProblems(verdict.found, env);
|
||||
console.log(`packages/studio and packages/player: captures present in ${source.label}.`);
|
||||
return;
|
||||
}
|
||||
failed.push([source.label, verdict]);
|
||||
}
|
||||
if (failed.length > 0) {
|
||||
console.error(
|
||||
"This PR changes packages/studio or packages/player, so its body or its author's comment must show the behaviour.",
|
||||
);
|
||||
for (const [label, verdict] of failed) reportSource(label, verdict, env);
|
||||
printFailure(env.PR_NUMBER ?? "<number>");
|
||||
process.exit(1);
|
||||
}
|
||||
const found = await findProblems(body, files);
|
||||
reportCaptureProblems(found, process.env);
|
||||
if (blocking(found.unreadable, [...found.identical, ...found.refused], process.env)) {
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("packages/studio and packages/player: captures present, or nothing to show.");
|
||||
console.log("packages/studio and packages/player: nothing to show.");
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href)
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { copyFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { parse } from "yaml";
|
||||
|
||||
import {
|
||||
blocking,
|
||||
isFork,
|
||||
attachCommand,
|
||||
captureSources,
|
||||
checkSource,
|
||||
downloadAsset,
|
||||
duplicateCaptureProblems,
|
||||
LimitExceeded,
|
||||
@@ -36,7 +39,7 @@ test("a missing After heading fails and names it", () => {
|
||||
files: [studio("packages/player/src/a.ts")],
|
||||
});
|
||||
assert.equal(ok, false);
|
||||
assert.deepEqual(problems, ['the body has no "After" heading']);
|
||||
assert.deepEqual(problems, ['no "After" heading']);
|
||||
});
|
||||
|
||||
test("a heading with no media fails and names the section", () => {
|
||||
@@ -732,3 +735,137 @@ test("the CLI passes on notices alone", () => {
|
||||
assert.equal(result.status, 0, result.stdout + result.stderr);
|
||||
assert.match(result.stdout, /not compared/);
|
||||
});
|
||||
|
||||
const NO_VISIBLE = "## No visible change\nOnly a helper moved.\n";
|
||||
function commentsFile(pages) {
|
||||
const path = join(mkdtempSync(join(tmpdir(), "captures-comments-")), "comments.json");
|
||||
writeFileSync(path, JSON.stringify(pages));
|
||||
return path;
|
||||
}
|
||||
const comment = (login, body, id = 1) => ({
|
||||
user: { login },
|
||||
body,
|
||||
html_url: `https://github.com/a/r/pull/1#issuecomment-${id}`,
|
||||
});
|
||||
const withComments = (pages, author = "author") => ({
|
||||
HEAD_REPO: "a/r",
|
||||
BASE_REPO: "a/r",
|
||||
PR_AUTHOR: author,
|
||||
PR_COMMENTS_FILE: commentsFile(pages),
|
||||
});
|
||||
|
||||
test("the section in a comment by the PR's author passes, read across pages", () => {
|
||||
const pages = [[comment("someone", "thanks", 1)], [comment("author", NO_VISIBLE, 2)]];
|
||||
const result = runCli(withComments(pages), "Moves a helper.");
|
||||
assert.equal(result.status, 0, result.stdout + result.stderr);
|
||||
assert.match(result.stdout, /issuecomment-2/);
|
||||
});
|
||||
|
||||
test("the same section in anyone else's comment fails", () => {
|
||||
const result = runCli(withComments([[comment("reviewer", NO_VISIBLE)]]), "Moves a helper.");
|
||||
assert.equal(result.status, 1, result.stdout + result.stderr);
|
||||
assert.match(result.stderr, /nobody else's comment counts/);
|
||||
});
|
||||
|
||||
test("the body alone still passes with an empty comment list", () => {
|
||||
const result = runCli(withComments([[]]), NO_VISIBLE);
|
||||
assert.equal(result.status, 0, result.stdout + result.stderr);
|
||||
assert.match(result.stdout, /the PR description/);
|
||||
});
|
||||
|
||||
test("a comment counts on its own: Before in the body and After in a comment is no section", async () => {
|
||||
const sources = captureSources(
|
||||
`## Before\n[a](${OLD})\n`,
|
||||
[comment("author", `## After\n[b](${NEW})\n`)],
|
||||
"author",
|
||||
);
|
||||
const files = [studio("packages/studio/src/a.tsx")];
|
||||
for (const { text } of sources)
|
||||
assert.equal((await checkSource(text, files, fromMap, {})).ok, false);
|
||||
});
|
||||
|
||||
test("an author comment with good captures passes over a body whose captures are duplicates", async () => {
|
||||
const sources = captureSources(
|
||||
bodyWith(`[a](${OLD})`, `[b](${sameBytes})`),
|
||||
[comment("author", bodyWith(`[a](${OLD})`, `[b](${NEW})`))],
|
||||
"author",
|
||||
);
|
||||
const files = [studio("packages/studio/src/a.tsx")];
|
||||
const verdicts = [];
|
||||
for (const { text } of sources) verdicts.push((await checkSource(text, files, fromMap, {})).ok);
|
||||
assert.deepEqual(verdicts, [false, true]);
|
||||
});
|
||||
|
||||
test("no author means no comment counts", () => {
|
||||
assert.deepEqual(
|
||||
captureSources("b", [comment("x", NO_VISIBLE)], undefined).map((source) => source.label),
|
||||
["the PR description"],
|
||||
);
|
||||
});
|
||||
|
||||
test("an unreadable comments file fails closed", () => {
|
||||
const result = runCli(
|
||||
{ PR_COMMENTS_FILE: join(tmpdir(), "no-such-dir-xyz", "c.json") },
|
||||
NO_VISIBLE,
|
||||
);
|
||||
assert.equal(result.status, 2, result.stdout + result.stderr);
|
||||
assert.match(result.stderr, /cannot read the PR comments/);
|
||||
});
|
||||
|
||||
test("a comment event never runs the PR's code and re-checks only for the PR's own author", () => {
|
||||
const { jobs, on } = parse(
|
||||
readFileSync(new URL("../.github/workflows/pr-captures.yml", import.meta.url), "utf8"),
|
||||
);
|
||||
assert.deepEqual(on.issue_comment.types, ["created", "edited", "deleted"]);
|
||||
assert.match(jobs.captures.if, /github\.event_name != 'issue_comment'/);
|
||||
assert.match(jobs.recheck.if, /github\.event\.issue\.pull_request/);
|
||||
assert.match(
|
||||
jobs.recheck.if,
|
||||
/github\.event\.comment\.user\.login == github\.event\.issue\.user\.login/,
|
||||
);
|
||||
assert.ok(
|
||||
jobs.recheck.steps.every((step) => !step.uses),
|
||||
"recheck checks nothing out",
|
||||
);
|
||||
assert.deepEqual(jobs.recheck.permissions, { actions: "write", "pull-requests": "read" });
|
||||
});
|
||||
|
||||
const capturesWorkflow = () =>
|
||||
parse(readFileSync(new URL("../.github/workflows/pr-captures.yml", import.meta.url), "utf8"));
|
||||
|
||||
test("a comment run whose job is skipped joins no shared group, so it cannot cancel the author's re-check", () => {
|
||||
const { concurrency, jobs } = capturesWorkflow();
|
||||
assert.match(concurrency.group, /github\.event_name == 'issue_comment' && github\.run_id/);
|
||||
assert.doesNotMatch(concurrency.group, /format\('comment-\{0\}', github\.event\.issue\.number\)/);
|
||||
assert.equal(
|
||||
jobs.recheck.concurrency.group,
|
||||
"pr-captures-recheck-${{ github.event.issue.number }}",
|
||||
);
|
||||
assert.equal(jobs.recheck.concurrency["cancel-in-progress"], true);
|
||||
});
|
||||
|
||||
// Shapes as the runs API reports them; a fork PR's run waiting for approval is completed + action_required.
|
||||
const RUNS = {
|
||||
awaitingApproval: { id: 1, status: "completed", conclusion: "action_required" },
|
||||
running: { id: 2, status: "in_progress", conclusion: null },
|
||||
queued: { id: 3, status: "queued", conclusion: null },
|
||||
skipped: { id: 4, status: "completed", conclusion: "skipped" },
|
||||
success: { id: 5, status: "completed", conclusion: "success" },
|
||||
failure: { id: 6, status: "completed", conclusion: "failure" },
|
||||
cancelled: { id: 7, status: "completed", conclusion: "cancelled" },
|
||||
};
|
||||
|
||||
test("the re-check re-runs only a finished run that ran, never one waiting for approval", () => {
|
||||
const step = capturesWorkflow().jobs.recheck.steps.find((s) => s.run?.includes("gh run rerun"));
|
||||
assert.ok(step.env?.RERUNNABLE, "the re-run goes through the RERUNNABLE filter");
|
||||
assert.match(step.run, /--jq "\$RERUNNABLE"\)/);
|
||||
const picked = Object.entries(RUNS).flatMap(([name, run]) => {
|
||||
const out = spawnSync("jq", ["-r", step.env.RERUNNABLE], {
|
||||
input: JSON.stringify(run),
|
||||
encoding: "utf8",
|
||||
});
|
||||
assert.equal(out.status, 0, out.stderr);
|
||||
return out.stdout.trim() ? [name] : [];
|
||||
});
|
||||
assert.deepEqual(picked, ["success", "failure", "cancelled"]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user