From 25dc9dec55ba35e01df0a9718d01564bc9271eb5 Mon Sep 17 00:00:00 2001
From: Pat Hickey
Date: Fri, 20 Nov 2026 12:50:22 -0800
Subject: [PATCH 1/4] limit closing PRs to those opened in the last 24h
---
README.md | 12 +++++++-----
src/main.js | 16 +++++++++++++++-
test/main.test.js | 28 +++++++++++++++++++++++++++-
3 files changed, 49 insertions(+), 7 deletions(-)
diff --git a/README.md b/README.md
index d13a217..c1e7c5d 100644
--- a/README.md
+++ b/README.md
@@ -7,13 +7,15 @@ small set of /vouch commands from maintainers to manage the allowlist.
## How it works
Each run sweeps the repository: it fetches the allowlist and blocklist,
-enumerates all open pull requests through the API, and comments on and closes
-every one whose author is neither on the list nor has write (or admin, or
+enumerates open pull requests opened within the last 24 hours, and comments
+on and closes every one whose author is neither on the list nor has write (or admin, or
maintain) access to the repository. Write access is checked with the
[collaborator permission
API](https://docs.github.com/en/rest/collaborators/collaborators#get-repository-permissions-for-a-user),
which reflects grants from teams and organization base permissions, so
-maintainers never need to be listed.
+maintainers never need to be listed. Pull requests older than 24 hours are
+never closed, so enabling the action (or revoking/blocking someone) does not
+close long-standing PRs.
An optional blocklist, in the same repository as the allowlist, names
accounts that are unwelcome to contribute. Their PRs are closed with a
@@ -40,8 +42,8 @@ commenting on a pull request:
| Comment | Effect |
|-----------------------------------------|--------|
| `/vouch allow` or just `/vouch` | Add the PR author to the allowlist, and reopen the PR if it was closed before the comment. |
-| `/vouch revoke` | Remove the PR author from the allowlist. The next sweep closes their open PRs. |
-| `/vouch block` | Add the PR author to the blocklist (requires `blocklist-path`). The next sweep closes their open PRs with `blocked-message`. |
+| `/vouch revoke` | Remove the PR author from the allowlist. The next sweep closes their open PRs opened in the last 24 hours. |
+| `/vouch block` | Add the PR author to the blocklist (requires `blocklist-path`). The next sweep closes their open PRs opened in the last 24 hours with `blocked-message`. |
Revoking means the author needs a new vouch; blocking is a stronger judgment
that the account is unwelcome. There is no command to unblock: maintainers
diff --git a/src/main.js b/src/main.js
index 29bdf85..499c4ce 100644
--- a/src/main.js
+++ b/src/main.js
@@ -15,6 +15,9 @@ import {
// skipped scheduled runs don't miss any.
const VOUCH_LOOKBACK_MS = 24 * 60 * 60 * 1000;
+// Only PRs opened this recently are closed; older ones are left alone.
+const CLOSE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
+
function input(name, { required = false } = {}) {
const value = (process.env[`INPUT_${name.toUpperCase()}`] ?? "").trim();
if (required && !value) throw new Error(`Input required and not supplied: ${name}`);
@@ -231,7 +234,18 @@ async function processVouches(ctx, allow, block) {
async function closeUnapproved(ctx, allow, block) {
const writers = new Map();
const closed = [];
- for (const pr of await paginate(ctx.token, `${ctx.repoUrl}/pulls?state=open&per_page=100`)) {
+ const cutoff = Date.now() - CLOSE_MAX_AGE_MS;
+ let url = `${ctx.repoUrl}/pulls?state=open&sort=created&direction=desc&per_page=100`;
+ const recent = [];
+ while (url) {
+ const res = await github(ctx.token, url);
+ const page = await res.json();
+ const fresh = page.filter((pr) => Date.parse(pr.created_at) >= cutoff);
+ recent.push(...fresh);
+ // Newest first, so a page with any old PR is the last one we need.
+ url = fresh.length === page.length ? nextLink(res.headers.get("link")) : null;
+ }
+ for (const pr of recent) {
const author = pr.user.login;
const blocked = block !== null && isApproved(block.logins, author);
if (!blocked && isApproved(allow.logins, author)) continue;
diff --git a/test/main.test.js b/test/main.test.js
index aa36676..465e622 100644
--- a/test/main.test.js
+++ b/test/main.test.js
@@ -34,7 +34,14 @@ async function runAction({
}) {
const requests = [];
let n = 0;
- const pageData = pages.map((p) => p.map((login) => ({ number: ++n, user: { login } })));
+ // Each entry is a login, or [login, ageInHours] (default: 1 hour old).
+ const pageData = pages.map((p) =>
+ p.map((e) => {
+ const [login, hours = 1] = Array.isArray(e) ? e : [e];
+ const created_at = new Date(Date.now() - hours * 3600e3).toISOString();
+ return { number: ++n, created_at, user: { login } };
+ }),
+ );
const files = {
"approved.txt": { text: list, sha: "sha0", status: listStatus },
"blocked.txt": { text: block, sha: "sha0", status: blockStatus },
@@ -159,6 +166,25 @@ test("authors with write access are never closed", async () => {
assert.equal(output, "closed=[4,5]\n");
});
+test("PRs opened more than 24 hours ago are not closed", async () => {
+ const { code, requests, writes, output } = await runAction({
+ pages: [["mallory", ["eve", 23]], [["oldie", 25]], ["unreached"]],
+ list: "alice\n",
+ });
+ assert.equal(code, 0);
+ assert.deepEqual(writes.map(([m, u]) => [m, u]), [
+ ["POST", "/repos/org/proj/issues/1/comments"],
+ ["PATCH", "/repos/org/proj/pulls/1"],
+ ["POST", "/repos/org/proj/issues/2/comments"],
+ ["PATCH", "/repos/org/proj/pulls/2"],
+ ]);
+ assert.equal(output, "closed=[1,2]\n");
+ // Newest-first ordering lets us stop at the first page with an old PR.
+ const lists = requests.filter((r) => r.url.startsWith("/repos/org/proj/pulls?"));
+ assert.equal(lists.length, 2);
+ assert.match(lists[0].url, /sort=created&direction=desc/);
+});
+
test("listed authors skip the permission lookup", async () => {
const { requests } = await runAction({ pages: [["alice"]], list: "alice\n" });
assert.ok(!requests.some((r) => r.url.includes("/collaborators/")));
From c502035b352cd2864afbf0aecb0c7f18d4a96faa Mon Sep 17 00:00:00 2001
From: Pat Hickey
Date: Fri, 20 Nov 2026 12:54:54 -0800
Subject: [PATCH 2/4] execution prints an audit log
---
README.md | 13 +++++++++
src/main.js | 38 +++++++++++++++++++++++---
test/main.test.js | 68 +++++++++++++++++++++++++++++++++++++++++++++--
3 files changed, 114 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index c1e7c5d..902e2f7 100644
--- a/README.md
+++ b/README.md
@@ -105,6 +105,19 @@ into `.github/workflows/`.
Output `closed` is a JSON array of the PR numbers closed by this run.
+Each run ends its log with an audit log of every write it made, one line per
+action, printed even if the run fails partway:
+
+```text
+Audit log: 4 action(s) taken.
+ 2026-11-20T10:00:01.123Z commit file=org/gov:approved.txt sha=3f9c... message="allow newbie by maint"
+ 2026-11-20T10:00:01.456Z reopen pr=7 via=https://github.com/org/proj/pull/7#issuecomment-1
+ 2026-11-20T10:00:02.789Z comment pr=9 author=mallory url=https://github.com/org/proj/pull/9#issuecomment-2
+ 2026-11-20T10:00:03.012Z close pr=9 author=mallory reason=not-approved
+```
+
+`reason` is `not-approved` or `blocked`.
+
If the allowlist cannot be fetched or is empty, or `blocklist-path` is set
but cannot be fetched, the action fails rather than closing anything. An
empty blocklist is fine.
diff --git a/src/main.js b/src/main.js
index 499c4ce..f4ef3e0 100644
--- a/src/main.js
+++ b/src/main.js
@@ -30,6 +30,19 @@ function setOutput(name, value) {
}
}
+// Records a write the run made, for the audit log printed at exit.
+function audit(ctx, action, details) {
+ ctx.audit.push({ time: new Date().toISOString(), action, ...details });
+}
+
+function printAudit(entries) {
+ console.log(`Audit log: ${entries.length} action(s) taken.`);
+ for (const { time, action, ...details } of entries) {
+ const fields = Object.entries(details).map(([k, v]) => `${k}=${v}`);
+ console.log(` ${time} ${action} ${fields.join(" ")}`);
+ }
+}
+
async function github(token, url, { method = "GET", body, allow404 = false } = {}) {
const res = await fetch(url, {
method,
@@ -93,17 +106,23 @@ async function writeList(ctx, list, text, message) {
});
list.text = text;
list.sha = (await res.json()).content.sha;
+ audit(ctx, "commit", {
+ file: `${ctx.permsRepo}:${list.path}`,
+ sha: list.sha,
+ message: JSON.stringify(message.split("\n")[0]),
+ });
list.logins = parseList(text);
}
-async function reopen(ctx, number) {
+async function reopen(ctx, number, via) {
console.log(`Reopening #${number}.`);
try {
await github(ctx.token, `${ctx.repoUrl}/pulls/${number}`, {
method: "PATCH",
body: { state: "open" },
});
+ audit(ctx, "reopen", { pr: number, via });
} catch (err) {
// e.g. the head branch was deleted; don't let one PR block the sweep.
console.log(`::warning::Could not reopen #${number}: ${err.message}`);
@@ -224,7 +243,7 @@ async function processVouches(ctx, allow, block) {
if (reopened.has(pr.number)) continue;
if (pr.state === "closed" && !pr.merged && Date.parse(pr.closed_at) < Date.parse(c.created_at)) {
reopened.add(pr.number);
- await reopen(ctx, pr.number);
+ await reopen(ctx, pr.number, c.html_url);
}
}
}
@@ -254,14 +273,17 @@ async function closeUnapproved(ctx, allow, block) {
console.log(
`Closing #${pr.number}: ${author} is ${blocked ? "blocked" : "not an approved contributor"}.`,
);
- await github(ctx.token, `${ctx.repoUrl}/issues/${pr.number}/comments`, {
+ const reason = blocked ? "blocked" : "not-approved";
+ const res = await github(ctx.token, `${ctx.repoUrl}/issues/${pr.number}/comments`, {
method: "POST",
body: { body: renderMessage(blocked ? ctx.blockedMessage : ctx.message, author) },
});
+ audit(ctx, "comment", { pr: pr.number, author, url: (await res.json()).html_url });
await github(ctx.token, `${ctx.repoUrl}/pulls/${pr.number}`, {
method: "PATCH",
body: { state: "closed" },
});
+ audit(ctx, "close", { pr: pr.number, author, reason });
closed.push(pr.number);
}
return closed;
@@ -283,7 +305,17 @@ async function run() {
allowPath: input("allowlist-path", { required: true }),
blockPath: input("blocklist-path"),
vouchTeam: input("vouch-team"),
+ audit: [],
};
+ try {
+ await sweep(ctx);
+ } finally {
+ // Also on failure, so partial runs are accounted for.
+ printAudit(ctx.audit);
+ }
+}
+
+async function sweep(ctx) {
if (ctx.blockPath) ctx.blockedMessage = input("blocked-message", { required: true });
parsePair(ctx.permsRepo, "permissions-repo");
diff --git a/test/main.test.js b/test/main.test.js
index 465e622..20f81f7 100644
--- a/test/main.test.js
+++ b/test/main.test.js
@@ -18,6 +18,7 @@ const b64 = (s) => Buffer.from(s).toString("base64");
// team: vouch-team member logins (null: team endpoint 404s)
// comments: issue comments returned by /issues/comments
// pulls: PR number -> PR object for GET /pulls/:n
+// fail: "METHOD /path" requests that get a 500
async function runAction({
pages = [[]],
list,
@@ -31,6 +32,7 @@ async function runAction({
team = [],
comments = [],
pulls = {},
+ fail = [],
}) {
const requests = [];
let n = 0;
@@ -55,6 +57,7 @@ async function runAction({
const base = `http://127.0.0.1:${server.address().port}`;
const url = new URL(req.url, base);
const path = url.pathname;
+ if (fail.includes(`${req.method} ${path}`)) return res.writeHead(500).end("{}");
const file = files[/^\/repos\/org\/gov\/contents\/(.*)$/.exec(path)?.[1]];
if (file) {
if (req.method === "PUT") {
@@ -91,6 +94,11 @@ async function runAction({
if (path === "/repos/org/proj/issues/comments") {
return res.writeHead(200, json).end(JSON.stringify(comments));
}
+ const posted = /^\/repos\/org\/proj\/issues\/(\d+)\/comments$/.exec(path);
+ if (req.method === "POST" && posted) {
+ const html_url = `https://github.com/org/proj/pull/${posted[1]}#issuecomment-c${posted[1]}`;
+ return res.writeHead(201, json).end(JSON.stringify({ html_url }));
+ }
res.writeHead(200, json).end("{}");
});
});
@@ -115,8 +123,8 @@ async function runAction({
"INPUT_BLOCKED-MESSAGE": blockedMessage,
INPUT_TOKEN: "pr-tok",
};
- const code = await new Promise((resolve) => {
- execFile(process.execPath, [MAIN], { env }, (err) => resolve(err ? err.code : 0));
+ const [code, stdout] = await new Promise((resolve) => {
+ execFile(process.execPath, [MAIN], { env }, (err, out) => resolve([err ? err.code : 0, out]));
});
server.close();
const writes = requests
@@ -129,6 +137,12 @@ async function runAction({
listText: files["approved.txt"].text,
blockText: files["blocked.txt"].text,
output: readFileSync(outputPath, "utf8"),
+ // Audit entries with the timestamp stripped.
+ audit: stdout
+ .split("\n")
+ .filter((l) => /^ \d{4}-\S+Z /.test(l))
+ .map((l) => l.trim().replace(/^\S+ /, "")),
+ stdout,
};
}
@@ -540,3 +554,53 @@ test("manually blocked authors: allow is ignored", async () => {
});
assert.deepEqual(writes, []);
});
+
+test("audit log: closes", async () => {
+ const { audit, stdout } = await runAction({
+ pages: [["alice", "mallory", "eve"]],
+ list: "alice\n",
+ block: "eve\n",
+ });
+ assert.match(stdout, /Audit log: 4 action\(s\) taken\./);
+ assert.deepEqual(audit, [
+ "comment pr=2 author=mallory url=https://github.com/org/proj/pull/2#issuecomment-c2",
+ "close pr=2 author=mallory reason=not-approved",
+ "comment pr=3 author=eve url=https://github.com/org/proj/pull/3#issuecomment-c3",
+ "close pr=3 author=eve reason=blocked",
+ ]);
+});
+
+test("audit log: commits and reopens", async () => {
+ const { audit } = await runAction({
+ list: "alice\n",
+ vouchTeam: "org/maintainers",
+ team: ["maint"],
+ comments: [comment(1, "maint", "/vouch allow")],
+ pulls: { 7: closedPr },
+ });
+ assert.deepEqual(audit, [
+ 'commit file=org/gov:approved.txt sha=sha1 message="allow newbie by maint"',
+ "reopen pr=7 via=https://github.com/org/proj/pull/7#issuecomment-1",
+ ]);
+});
+
+test("audit log: nothing done", async () => {
+ const { audit, stdout } = await runAction({ pages: [["alice"]], list: "alice\n" });
+ assert.match(stdout, /Audit log: 0 action\(s\) taken\./);
+ assert.deepEqual(audit, []);
+});
+
+test("audit log: printed when the run fails partway", async () => {
+ const { code, audit, stdout } = await runAction({
+ pages: [["mallory", "eve"]],
+ list: "alice\n",
+ fail: ["PATCH /repos/org/proj/pulls/2"],
+ });
+ assert.equal(code, 1);
+ assert.match(stdout, /::error::PATCH .* 500/);
+ assert.deepEqual(audit, [
+ "comment pr=1 author=mallory url=https://github.com/org/proj/pull/1#issuecomment-c1",
+ "close pr=1 author=mallory reason=not-approved",
+ "comment pr=2 author=eve url=https://github.com/org/proj/pull/2#issuecomment-c2",
+ ]);
+});
From 12e4d158b73973e152641b2d1b3320cb59f81642 Mon Sep 17 00:00:00 2001
From: Pat Hickey
Date: Fri, 20 Nov 2026 14:16:52 -0800
Subject: [PATCH 3/4] handle line breaks in mesages better
---
README.md | 2 +-
action.yml | 3 ++-
src/lib.js | 24 +++++++++++++++++++++++-
test/lib.test.js | 36 ++++++++++++++++++++++++++++++++++++
4 files changed, 62 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index 902e2f7..335dedc 100644
--- a/README.md
+++ b/README.md
@@ -99,7 +99,7 @@ into `.github/workflows/`.
| `allowlist-path` | yes | Path to the allowlist within `permissions-repo`. |
| `blocklist-path` | no | Path to the blocklist within `permissions-repo`. The blocklist is off when empty. |
| `vouch-team` | no | `org/team-slug` whose members can `/vouch`. Vouching is off when empty. |
-| `message` | yes | Comment posted before closing. `{author}` is replaced with the PR author's login. |
+| `message` | yes | Comment posted before closing. `{author}` is replaced with the PR author's login. Hard-wrapped lines in a paragraph are joined, so wrap freely and separate paragraphs with a blank line. |
| `blocked-message` | if `blocklist-path` | Comment posted before closing a blocked author's PR. `{author}` is substituted as in `message`. |
| `token` | no | Token used to list, comment on, and close PRs. Defaults to `github.token`. |
diff --git a/action.yml b/action.yml
index f54267e..8625ad5 100644
--- a/action.yml
+++ b/action.yml
@@ -46,7 +46,8 @@ inputs:
message:
description: >
Comment posted on each pull request before closing it. "{author}" is
- replaced with the PR author's login.
+ replaced with the PR author's login. Hard-wrapped lines within a
+ paragraph are joined; separate paragraphs with a blank line.
required: true
blocked-message:
description: >
diff --git a/src/lib.js b/src/lib.js
index e469a0e..b09249e 100644
--- a/src/lib.js
+++ b/src/lib.js
@@ -14,8 +14,30 @@ export function isApproved(logins, author) {
return logins.has(author.toLowerCase());
}
+// Lines that must keep their own line: blank, indented (code), lists,
+// headings, quotes, tables, fences, and rules.
+const STANDALONE = /^(\s*$|\s|[-*+>#|]|\d+[.)]\s|```|~~~)/;
+
+// GitHub renders every newline in a comment as a line break, so lines
+// hard-wrapped in YAML are joined back into flowing paragraphs.
+export function unwrap(text) {
+ const out = [];
+ let fenced = false;
+ for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
+ const fence = /^(```|~~~)/.test(line);
+ const prev = out.length ? out[out.length - 1] : null;
+ if (!fenced && !fence && prev !== null && !STANDALONE.test(prev) && !STANDALONE.test(line)) {
+ out[out.length - 1] = `${prev} ${line.trim()}`;
+ } else {
+ out.push(line);
+ }
+ if (fence) fenced = !fenced;
+ }
+ return out.join("\n");
+}
+
export function renderMessage(template, author) {
- return template.replaceAll("{author}", author);
+ return unwrap(template).replaceAll("{author}", author);
}
export function appendLogin(text, login) {
diff --git a/test/lib.test.js b/test/lib.test.js
index ff11140..a44529c 100644
--- a/test/lib.test.js
+++ b/test/lib.test.js
@@ -27,6 +27,42 @@ test("renderMessage substitutes every {author}", () => {
assert.equal(renderMessage("Hi @{author}, {author}!", "bob"), "Hi @bob, bob!");
});
+test("renderMessage joins hard-wrapped paragraphs", () => {
+ const template =
+ "Thanks @{author} for your contribution, but\nthis bot is closing this PR.\n\n" +
+ "See [the contributing\ndocs](https://example.com).\n";
+ assert.equal(
+ renderMessage(template, "bob"),
+ "Thanks @bob for your contribution, but this bot is closing this PR.\n\n" +
+ "See [the contributing docs](https://example.com).\n",
+ );
+});
+
+test("renderMessage keeps block markdown on its own lines", () => {
+ const template = [
+ "# Closed",
+ "Intro line one",
+ "line two:",
+ "- item one",
+ "- item two",
+ "1. first",
+ "> quoted",
+ "| a | b |",
+ "|---|---|",
+ "```",
+ "code line",
+ "more code",
+ "```",
+ " indented code",
+ "after",
+ "",
+ ].join("\n");
+ assert.equal(
+ renderMessage(template, "bob"),
+ template.replace("Intro line one\nline two:", "Intro line one line two:"),
+ );
+});
+
test("parsePair", () => {
assert.deepEqual(parsePair("org/repo.name", "x"), ["org", "repo.name"]);
assert.throws(() => parsePair("org", "x"), /x must be/);
From 3d76d8faf65e4538b49ed239a27d9065cca4aa25 Mon Sep 17 00:00:00 2001
From: Pat Hickey
Date: Fri, 20 Nov 2026 16:23:09 -0800
Subject: [PATCH 4/4] add dry run mode
---
README.md | 18 +++++++---
action.yml | 7 ++++
src/main.js | 87 +++++++++++++++++++++++++++++++++--------------
test/main.test.js | 71 +++++++++++++++++++++++++++++++++-----
4 files changed, 143 insertions(+), 40 deletions(-)
diff --git a/README.md b/README.md
index 335dedc..a97e395 100644
--- a/README.md
+++ b/README.md
@@ -102,6 +102,7 @@ into `.github/workflows/`.
| `message` | yes | Comment posted before closing. `{author}` is replaced with the PR author's login. Hard-wrapped lines in a paragraph are joined, so wrap freely and separate paragraphs with a blank line. |
| `blocked-message` | if `blocklist-path` | Comment posted before closing a blocked author's PR. `{author}` is substituted as in `message`. |
| `token` | no | Token used to list, comment on, and close PRs. Defaults to `github.token`. |
+| `dry-run` | no | `true` to change nothing (no comments, closes, reopens, or list commits) and only print the audit log of what would be done. Defaults to `false`. |
Output `closed` is a JSON array of the PR numbers closed by this run.
@@ -110,13 +111,20 @@ action, printed even if the run fails partway:
```text
Audit log: 4 action(s) taken.
- 2026-11-20T10:00:01.123Z commit file=org/gov:approved.txt sha=3f9c... message="allow newbie by maint"
- 2026-11-20T10:00:01.456Z reopen pr=7 via=https://github.com/org/proj/pull/7#issuecomment-1
- 2026-11-20T10:00:02.789Z comment pr=9 author=mallory url=https://github.com/org/proj/pull/9#issuecomment-2
- 2026-11-20T10:00:03.012Z close pr=9 author=mallory reason=not-approved
+ 2026-11-20T10:00:01.123Z commit file=org/gov:approved.txt sha=3f9c... pr=https://github.com/org/proj/pull/7 message="allow newbie by maint"
+ 2026-11-20T10:00:01.456Z reopen pr=https://github.com/org/proj/pull/7 via=https://github.com/org/proj/pull/7#issuecomment-1
+ 2026-11-20T10:00:02.789Z comment pr=https://github.com/org/proj/pull/9 author=mallory url=https://github.com/org/proj/pull/9#issuecomment-2
+ 2026-11-20T10:00:03.012Z close pr=https://github.com/org/proj/pull/9 author=mallory reason=not-approved
```
-`reason` is `not-approved` or `blocked`.
+`reason` is `not-approved` or `blocked`. For a `commit`, `pr` is the PR
+carrying the `/vouch` comment.
+
+With `dry-run: true`, the header reads `Audit log (dry run): N action(s)
+would be taken.` and entries omit `sha` and the comment `url`, which only
+exist once the write is made. Within a dry run, list changes from vouches
+are applied in memory, so the PRs it reports it would close are those a
+real run would close. The `closed` output is always `[]`.
If the allowlist cannot be fetched or is empty, or `blocklist-path` is set
but cannot be fetched, the action fails rather than closing anything. An
diff --git a/action.yml b/action.yml
index 8625ad5..de2eb12 100644
--- a/action.yml
+++ b/action.yml
@@ -64,6 +64,13 @@ inputs:
required: false
default: ${{ github.token }}
+ dry-run:
+ description: >
+ When "true", make no changes to pull requests, the allowlist, or the
+ blocklist; only print the audit log of actions a real run would take.
+ required: false
+ default: "false"
+
outputs:
closed:
description: JSON array of the pull request numbers that were closed.
diff --git a/src/main.js b/src/main.js
index f4ef3e0..b192a25 100644
--- a/src/main.js
+++ b/src/main.js
@@ -35,8 +35,13 @@ function audit(ctx, action, details) {
ctx.audit.push({ time: new Date().toISOString(), action, ...details });
}
-function printAudit(entries) {
- console.log(`Audit log: ${entries.length} action(s) taken.`);
+function printAudit(ctx) {
+ const entries = ctx.audit;
+ console.log(
+ ctx.dryRun
+ ? `Audit log (dry run): ${entries.length} action(s) would be taken.`
+ : `Audit log: ${entries.length} action(s) taken.`,
+ );
for (const { time, action, ...details } of entries) {
const fields = Object.entries(details).map(([k, v]) => `${k}=${v}`);
console.log(` ${time} ${action} ${fields.join(" ")}`);
@@ -94,35 +99,46 @@ async function readList(ctx, path) {
return { path, text, sha: file.sha, logins: parseList(text) };
}
-async function writeList(ctx, list, text, message) {
- const res = await github(ctx.permsToken, contentsUrl(ctx.apiUrl, ctx.permsRepo, list.path), {
- method: "PUT",
- body: {
- message,
- content: Buffer.from(text).toString("base64"),
- sha: list.sha,
- ...(ctx.permsRef && { branch: ctx.permsRef }),
- },
- });
+function prUrl(ctx, number) {
+ return `${ctx.serverUrl}/${ctx.repo}/pull/${number}`;
+}
+
+// In dry-run, only the in-memory list changes, so later decisions in the
+// run match what a real run would do.
+async function writeList(ctx, list, text, message, pr) {
+ if (!ctx.dryRun) {
+ const res = await github(ctx.permsToken, contentsUrl(ctx.apiUrl, ctx.permsRepo, list.path), {
+ method: "PUT",
+ body: {
+ message,
+ content: Buffer.from(text).toString("base64"),
+ sha: list.sha,
+ ...(ctx.permsRef && { branch: ctx.permsRef }),
+ },
+ });
+ list.sha = (await res.json()).content.sha;
+ }
list.text = text;
- list.sha = (await res.json()).content.sha;
+ list.logins = parseList(text);
audit(ctx, "commit", {
file: `${ctx.permsRepo}:${list.path}`,
- sha: list.sha,
+ ...(!ctx.dryRun && { sha: list.sha }),
+ pr: prUrl(ctx, pr),
message: JSON.stringify(message.split("\n")[0]),
});
- list.logins = parseList(text);
}
async function reopen(ctx, number, via) {
- console.log(`Reopening #${number}.`);
+ console.log(`${ctx.dryRun ? "Would reopen" : "Reopening"} #${number}.`);
try {
- await github(ctx.token, `${ctx.repoUrl}/pulls/${number}`, {
- method: "PATCH",
- body: { state: "open" },
- });
- audit(ctx, "reopen", { pr: number, via });
+ if (!ctx.dryRun) {
+ await github(ctx.token, `${ctx.repoUrl}/pulls/${number}`, {
+ method: "PATCH",
+ body: { state: "open" },
+ });
+ }
+ audit(ctx, "reopen", { pr: prUrl(ctx, number), via });
} catch (err) {
// e.g. the head branch was deleted; don't let one PR block the sweep.
console.log(`::warning::Could not reopen #${number}: ${err.message}`);
@@ -210,6 +226,7 @@ async function processVouches(ctx, allow, block) {
block,
appendLogin(block.text, author),
`block ${author} by ${blockVouch.c.user.login}\n\nVia: ${blockVouch.c.html_url}`,
+ blockVouch.pr.number,
);
}
if (!last) continue;
@@ -226,6 +243,7 @@ async function processVouches(ctx, allow, block) {
allow,
removeLogin(allow.text, author),
`revoke ${author} by ${last.c.user.login}\n\nVia: ${last.c.html_url}`,
+ last.pr.number,
);
continue;
}
@@ -236,6 +254,7 @@ async function processVouches(ctx, allow, block) {
allow,
appendLogin(allow.text, author),
`allow ${author} by ${last.c.user.login}\n\nVia: ${last.c.html_url}`,
+ last.pr.number,
);
}
const reopened = new Set();
@@ -271,19 +290,26 @@ async function closeUnapproved(ctx, allow, block) {
if (!writers.has(author)) writers.set(author, await hasWriteAccess(ctx, author));
if (writers.get(author)) continue;
console.log(
- `Closing #${pr.number}: ${author} is ${blocked ? "blocked" : "not an approved contributor"}.`,
+ `${ctx.dryRun ? "Would close" : "Closing"} #${pr.number}: ` +
+ `${author} is ${blocked ? "blocked" : "not an approved contributor"}.`,
);
const reason = blocked ? "blocked" : "not-approved";
+ const url = prUrl(ctx, pr.number);
+ if (ctx.dryRun) {
+ audit(ctx, "comment", { pr: url, author });
+ audit(ctx, "close", { pr: url, author, reason });
+ continue;
+ }
const res = await github(ctx.token, `${ctx.repoUrl}/issues/${pr.number}/comments`, {
method: "POST",
body: { body: renderMessage(blocked ? ctx.blockedMessage : ctx.message, author) },
});
- audit(ctx, "comment", { pr: pr.number, author, url: (await res.json()).html_url });
+ audit(ctx, "comment", { pr: url, author, url: (await res.json()).html_url });
await github(ctx.token, `${ctx.repoUrl}/pulls/${pr.number}`, {
method: "PATCH",
body: { state: "closed" },
});
- audit(ctx, "close", { pr: pr.number, author, reason });
+ audit(ctx, "close", { pr: url, author, reason });
closed.push(pr.number);
}
return closed;
@@ -294,9 +320,16 @@ async function closeUnapproved(ctx, allow, block) {
async function run() {
const apiUrl = process.env.GITHUB_API_URL ?? "https://api.github.com";
const token = input("token", { required: true });
+ const dryRun = input("dry-run") || "false";
+ if (dryRun !== "true" && dryRun !== "false") {
+ throw new Error(`dry-run must be "true" or "false", got "${dryRun}"`);
+ }
const ctx = {
apiUrl,
+ serverUrl: process.env.GITHUB_SERVER_URL ?? "https://github.com",
+ repo: process.env.GITHUB_REPOSITORY,
repoUrl: `${apiUrl}/repos/${process.env.GITHUB_REPOSITORY}`,
+ dryRun: dryRun === "true",
token,
message: input("message", { required: true }),
permsRepo: input("permissions-repo", { required: true }),
@@ -311,7 +344,7 @@ async function run() {
await sweep(ctx);
} finally {
// Also on failure, so partial runs are accounted for.
- printAudit(ctx.audit);
+ printAudit(ctx);
}
}
@@ -329,7 +362,9 @@ async function sweep(ctx) {
if (ctx.vouchTeam) await processVouches(ctx, allow, block);
const closed = await closeUnapproved(ctx, allow, block);
- console.log(closed.length ? `Closed ${closed.length} pull request(s).` : "Nothing to close.");
+ if (!ctx.dryRun) {
+ console.log(closed.length ? `Closed ${closed.length} pull request(s).` : "Nothing to close.");
+ }
setOutput("closed", JSON.stringify(closed));
}
diff --git a/test/main.test.js b/test/main.test.js
index 20f81f7..06cd1cc 100644
--- a/test/main.test.js
+++ b/test/main.test.js
@@ -19,6 +19,8 @@ const b64 = (s) => Buffer.from(s).toString("base64");
// comments: issue comments returned by /issues/comments
// pulls: PR number -> PR object for GET /pulls/:n
// fail: "METHOD /path" requests that get a 500
+// dryRun: value of the dry-run input
+// serverUrl: GITHUB_SERVER_URL (undefined: unset)
async function runAction({
pages = [[]],
list,
@@ -33,6 +35,8 @@ async function runAction({
comments = [],
pulls = {},
fail = [],
+ dryRun = "",
+ serverUrl,
}) {
const requests = [];
let n = 0;
@@ -122,6 +126,8 @@ async function runAction({
INPUT_MESSAGE: "Sorry @{author}",
"INPUT_BLOCKED-MESSAGE": blockedMessage,
INPUT_TOKEN: "pr-tok",
+ "INPUT_DRY-RUN": dryRun,
+ ...(serverUrl && { GITHUB_SERVER_URL: serverUrl }),
};
const [code, stdout] = await new Promise((resolve) => {
execFile(process.execPath, [MAIN], { env }, (err, out) => resolve([err ? err.code : 0, out]));
@@ -563,10 +569,10 @@ test("audit log: closes", async () => {
});
assert.match(stdout, /Audit log: 4 action\(s\) taken\./);
assert.deepEqual(audit, [
- "comment pr=2 author=mallory url=https://github.com/org/proj/pull/2#issuecomment-c2",
- "close pr=2 author=mallory reason=not-approved",
- "comment pr=3 author=eve url=https://github.com/org/proj/pull/3#issuecomment-c3",
- "close pr=3 author=eve reason=blocked",
+ "comment pr=https://github.com/org/proj/pull/2 author=mallory url=https://github.com/org/proj/pull/2#issuecomment-c2",
+ "close pr=https://github.com/org/proj/pull/2 author=mallory reason=not-approved",
+ "comment pr=https://github.com/org/proj/pull/3 author=eve url=https://github.com/org/proj/pull/3#issuecomment-c3",
+ "close pr=https://github.com/org/proj/pull/3 author=eve reason=blocked",
]);
});
@@ -579,8 +585,8 @@ test("audit log: commits and reopens", async () => {
pulls: { 7: closedPr },
});
assert.deepEqual(audit, [
- 'commit file=org/gov:approved.txt sha=sha1 message="allow newbie by maint"',
- "reopen pr=7 via=https://github.com/org/proj/pull/7#issuecomment-1",
+ 'commit file=org/gov:approved.txt sha=sha1 pr=https://github.com/org/proj/pull/7 message="allow newbie by maint"',
+ "reopen pr=https://github.com/org/proj/pull/7 via=https://github.com/org/proj/pull/7#issuecomment-1",
]);
});
@@ -599,8 +605,55 @@ test("audit log: printed when the run fails partway", async () => {
assert.equal(code, 1);
assert.match(stdout, /::error::PATCH .* 500/);
assert.deepEqual(audit, [
- "comment pr=1 author=mallory url=https://github.com/org/proj/pull/1#issuecomment-c1",
- "close pr=1 author=mallory reason=not-approved",
- "comment pr=2 author=eve url=https://github.com/org/proj/pull/2#issuecomment-c2",
+ "comment pr=https://github.com/org/proj/pull/1 author=mallory url=https://github.com/org/proj/pull/1#issuecomment-c1",
+ "close pr=https://github.com/org/proj/pull/1 author=mallory reason=not-approved",
+ "comment pr=https://github.com/org/proj/pull/2 author=eve url=https://github.com/org/proj/pull/2#issuecomment-c2",
]);
});
+
+test("dry run: no writes, audit lists what would happen", async () => {
+ const { code, requests, writes, audit, stdout, output, listText, blockText } = await runAction({
+ dryRun: "true",
+ serverUrl: "https://ghe.example",
+ pages: [["alice", "newbie", "mallory", "eve"]],
+ list: "alice\nrevoked\n",
+ block: "eve\n",
+ vouchTeam: "org/maintainers",
+ team: ["maint"],
+ comments: [
+ comment(1, "maint", "/vouch allow", 7),
+ comment(2, "maint", "/vouch revoke", 8),
+ comment(3, "maint", "/vouch block", 9),
+ ],
+ pulls: {
+ 7: closedPr,
+ 8: { ...closedPr, number: 8, user: { login: "revoked" } },
+ 9: { ...closedPr, number: 9, user: { login: "spammer" } },
+ },
+ });
+ assert.equal(code, 0);
+ assert.deepEqual(writes, []);
+ assert.ok(requests.every((r) => r.method === "GET"));
+ assert.equal(listText, "alice\nrevoked\n");
+ assert.equal(blockText, "eve\n");
+ assert.match(stdout, /Audit log \(dry run\): 8 action\(s\) would be taken\./);
+ const pr = (n) => `https://ghe.example/org/proj/pull/${n}`;
+ assert.deepEqual(audit, [
+ `commit file=org/gov:approved.txt pr=${pr(7)} message="allow newbie by maint"`,
+ `reopen pr=${pr(7)} via=https://github.com/org/proj/pull/7#issuecomment-1`,
+ `commit file=org/gov:approved.txt pr=${pr(8)} message="revoke revoked by maint"`,
+ `commit file=org/gov:blocked.txt pr=${pr(9)} message="block spammer by maint"`,
+ // newbie was allowed in memory, so PR 2 is not closed.
+ `comment pr=${pr(3)} author=mallory`,
+ `close pr=${pr(3)} author=mallory reason=not-approved`,
+ `comment pr=${pr(4)} author=eve`,
+ `close pr=${pr(4)} author=eve reason=blocked`,
+ ]);
+ assert.equal(output, "closed=[]\n");
+});
+
+test("dry run: invalid value fails", async () => {
+ const { code, requests } = await runAction({ dryRun: "yes", list: "alice\n" });
+ assert.equal(code, 1);
+ assert.equal(requests.length, 0);
+});