Merge pull request #2910 from ludovic111/feat/triage-commands
🤖 Agent: Merged by Ludovic's AI agent (orchestrator) after review: comment commands for the trusted reviewers (/close, /reopen, /label, /unlabel), from main's code only, same list and pause as /nightly.
This commit is contained in:
@@ -1,7 +0,0 @@
|
||||
# Trusted reviewers: they pick the pull requests the Nightly holds with `/nightly 2640 2642` in any issue or pull
|
||||
# request (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). Ludovic is always allowed and isn't
|
||||
# listed. One GitHub login per line, with who added it and when. Removing a line revokes that login at once.
|
||||
# A line with only `paused` stops every reviewer's `/nightly` (Ludovic's still work).
|
||||
kacpherek # added by Ludovic, 2026-10-27
|
||||
rdbtCVS # added by Ludovic, 2026-10-27
|
||||
Online5277 # added by Ludovic, 2026-10-27 (his top three by merged pull requests)
|
||||
@@ -0,0 +1,8 @@
|
||||
# Trusted reviewers: one list for two things (docs/release-flow.md "Trusted reviewers").
|
||||
# - `/nightly 2640 2642` picks the pull requests the Nightly holds (tools/ci/nightly_set.py);
|
||||
# - `/close`, `/reopen`, `/label`, `/unlabel` triage issues and pull requests (tools/ci/triage_command.py).
|
||||
# Ludovic is always allowed and isn't listed. One GitHub login per line, with who added it and when. Removing a
|
||||
# line revokes that login at once. A line with only `paused` stops both for every reviewer (Ludovic's still work).
|
||||
kacpherek # added by Ludovic, 2026-10-27
|
||||
rdbtCVS # added by Ludovic, 2026-10-27
|
||||
Online5277 # added by Ludovic, 2026-10-27 (his top three by merged pull requests)
|
||||
@@ -1,5 +1,5 @@
|
||||
name: nightly command
|
||||
# `/nightly …` comments: the trusted reviewers in .github/nightly-reviewers.txt (and Ludovic) pick the pull requests
|
||||
# `/nightly …` comments: the trusted reviewers in .github/trusted-reviewers.txt (and Ludovic) pick the pull requests
|
||||
# the Nightly holds (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). This job only checks who asked,
|
||||
# saves the set on the nightly-state branch, starts `nightly build` and answers in the thread.
|
||||
#
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
.github/CODEOWNERS
|
||||
.github/nightly-reviewers.txt
|
||||
.github/trusted-reviewers.txt
|
||||
tools/ci/nightly_set.py
|
||||
sparse-checkout-cone-mode: false
|
||||
- name: Run the command
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
name: triage command
|
||||
# `/close`, `/reopen`, `/label`, `/unlabel` comments: the trusted reviewers in .github/trusted-reviewers.txt (and
|
||||
# Ludovic) triage issues and pull requests without any repository role (docs/release-flow.md "Trusted reviewers",
|
||||
# tools/ci/triage_command.py).
|
||||
#
|
||||
# Why no pull request's code runs here, though the token can write:
|
||||
# - `issue_comment` always runs this file from main, whoever comments and wherever.
|
||||
# - It checks out main's script and list only, never a pull request; it reads threads through the API.
|
||||
# - The comment's text and author reach the script as env vars, never in a shell line. The token stays in the step.
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
command:
|
||||
# Every other comment skips here, before a runner starts.
|
||||
if: >-
|
||||
github.event.comment.user.type != 'Bot' && (
|
||||
startsWith(github.event.comment.body, '/close') ||
|
||||
startsWith(github.event.comment.body, '/reopen') ||
|
||||
startsWith(github.event.comment.body, '/label') ||
|
||||
startsWith(github.event.comment.body, '/unlabel'))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
.github/trusted-reviewers.txt
|
||||
tools/ci/nightly_set.py
|
||||
tools/ci/triage_command.py
|
||||
sparse-checkout-cone-mode: false
|
||||
- name: Run the command
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
BODY: ${{ github.event.comment.body }}
|
||||
AUTHOR: ${{ github.event.comment.user.login }}
|
||||
ISSUE: ${{ github.event.issue.number }}
|
||||
REPO: ${{ github.repository }}
|
||||
COMMENT_URL: ${{ github.event.comment.html_url }}
|
||||
run: python3 tools/ci/triage_command.py command
|
||||
+30
-4
@@ -420,10 +420,36 @@ than main's head and holds something main lacks, otherwise main (`tools/ci/night
|
||||
new publishes nothing. A Nightly can include pull requests not reviewed yet: that is what it is for, playing them
|
||||
before the gate.
|
||||
|
||||
### Trusted reviewers pick the pull requests
|
||||
### Trusted reviewers
|
||||
|
||||
One list, `.github/trusted-reviewers.txt`, governs two things for the people on it (kacpherek, rdbtCVS and
|
||||
Online5277 since 2026-10-27) and for Ludovic, with no repository role: `/nightly` (below) and triage by comment.
|
||||
|
||||
```text
|
||||
/close closes an issue as completed; a pull request is closed without merging
|
||||
/close not planned closes an issue as not planned
|
||||
/close duplicate of #123 comments "Duplicate of #123", closes as a duplicate
|
||||
/reopen
|
||||
/label bug, good first issue existing labels only; never creates one
|
||||
/unlabel bug
|
||||
```
|
||||
|
||||
- **Where.** On the first line of a comment on the issue or pull request (`.github/workflows/triage-command.yml`,
|
||||
`tools/ci/triage_command.py`). The workflow answers with one comment, `🤖 Triage: <action>, on behalf of @login`,
|
||||
linking the comment that asked; a refusal answers too.
|
||||
- **Refused.** Any label with `release` in its name (`release-now`, `release-blocker`, `skip-release`) and
|
||||
`full-parity`; anything on Ludovic's own issues and pull requests; a merged pull request; a locked thread; more
|
||||
than 60 actions per reviewer in 24 hours (counted from the workflow's own comments).
|
||||
- **Safety.** Same as `/nightly`: main's copy of the workflow runs, no pull request's code is checked out or run,
|
||||
the comment reaches the script as env vars, and the token has `issues` and `pull-requests` write only.
|
||||
- **Ludovic stays in charge.** A one-line pull request removing a login from the list revokes it as soon as it merges
|
||||
(the file is his under CODEOWNERS). A line `paused` stops `/nightly` and the triage commands for every reviewer;
|
||||
his own still work.
|
||||
|
||||
### Trusted reviewers pick the Nightly's pull requests
|
||||
|
||||
The Nightly is where contributors test pull requests before the gate. The trusted reviewers listed in
|
||||
`.github/nightly-reviewers.txt` (kacpherek, rdbtCVS and Online5277 since 2026-10-27) and Ludovic pick them with a
|
||||
`.github/trusted-reviewers.txt` (kacpherek, rdbtCVS and Online5277 since 2026-10-27) and Ludovic pick them with a
|
||||
comment on any issue or pull request (`.github/workflows/nightly-command.yml`, `tools/ci/nightly_set.py`):
|
||||
|
||||
```text
|
||||
@@ -458,9 +484,9 @@ comment on any issue or pull request (`.github/workflows/nightly-command.yml`, `
|
||||
- **Ludovic stays in charge.**
|
||||
- Ludovic's `/nightly clear` or `/nightly remove` always applies. A pull request he removed can only come back
|
||||
when he adds it.
|
||||
- A one-line pull request removing a login from `.github/nightly-reviewers.txt` revokes it as soon as it merges
|
||||
- A one-line pull request removing a login from `.github/trusted-reviewers.txt` revokes it as soon as it merges
|
||||
(the file is his under CODEOWNERS).
|
||||
- A line `paused` in that file stops every reviewer's `/nightly`; his own still work.
|
||||
- A line `paused` in that file stops every reviewer's `/nightly` (and triage commands); his own still work.
|
||||
- Main, the gate and releases don't change: picks reach only players who turned Nightly on.
|
||||
|
||||
- **Jobs.** `pick` chooses or assembles the commit and writes the notes (each pull request in it with its title,
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from tools.ci import nightly_set as ns
|
||||
from tools.ci import triage_command as tc
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
NOW = datetime(2026, 10, 28, 12, tzinfo=timezone.utc)
|
||||
URL = "https://github.com/ludovic111/horizon/issues/5#issuecomment-1"
|
||||
LIST = ns.read_reviewers("kacpherek\nrdbtCVS\n")
|
||||
|
||||
|
||||
def thread(state="open", user="dev", labels=("bug",), pr=False, merged=False, locked=False):
|
||||
t = {"state": state, "user": {"login": user}, "labels": [{"name": n} for n in labels], "locked": locked}
|
||||
if pr:
|
||||
t["pull_request"] = {"merged_at": "2026-10-27T00:00:00Z" if merged else None}
|
||||
return t
|
||||
|
||||
|
||||
class Fake:
|
||||
def __init__(self, threads=None, labels=("bug", "good first issue", "release-now", "skip-release"), past=()):
|
||||
self.threads = {5: thread()} if threads is None else threads
|
||||
self.labels, self.past, self.calls = list(labels), list(past), []
|
||||
|
||||
def issue(self, n):
|
||||
return self.threads.get(n)
|
||||
|
||||
def label(self, name):
|
||||
return next((l for l in self.labels if l.lower() == name.lower()), None)
|
||||
|
||||
def add_labels(self, n, names):
|
||||
self.calls.append(("add", n, names))
|
||||
|
||||
def remove_label(self, n, name):
|
||||
self.calls.append(("remove", n, name))
|
||||
|
||||
def close(self, n, reason):
|
||||
self.calls.append(("close", n, reason))
|
||||
|
||||
def reopen(self, n):
|
||||
self.calls.append(("reopen", n))
|
||||
|
||||
def comment(self, n, text):
|
||||
self.calls.append(("comment", n, text))
|
||||
|
||||
def recent_comments(self, since):
|
||||
return self.past
|
||||
|
||||
|
||||
def do(text, api=None, login="kacpherek", reviewers=LIST, n=5):
|
||||
api = api or Fake()
|
||||
return tc.run(api, tc.parse(text), login, n, URL, reviewers, NOW), api
|
||||
|
||||
|
||||
class ParseTests(unittest.TestCase):
|
||||
def test_commands_and_case(self):
|
||||
self.assertEqual(tc.parse("/close"), tc.Command("close", "completed"))
|
||||
self.assertEqual(tc.parse(" /CLOSE Not Planned "), tc.Command("close", "not_planned"))
|
||||
self.assertEqual(tc.parse("/close completed"), tc.Command("close", "completed"))
|
||||
self.assertEqual(tc.parse("/close duplicate of #123"), tc.Command("close", "duplicate", 123))
|
||||
self.assertEqual(tc.parse("/Close duplicate of 7"), tc.Command("close", "duplicate", 7))
|
||||
self.assertEqual(tc.parse("/reopen"), tc.Command("reopen"))
|
||||
self.assertEqual(tc.parse("/label bug, good first issue ,bug"), tc.Command("label", labels=("bug", "good first issue")))
|
||||
self.assertEqual(tc.parse("/unlabel bug"), tc.Command("unlabel", labels=("bug",)))
|
||||
|
||||
def test_first_line_only(self):
|
||||
self.assertEqual(tc.parse("/close\n/label release-now"), tc.Command("close", "completed"))
|
||||
self.assertIsNone(tc.parse("thanks\n/close"))
|
||||
self.assertEqual(tc.parse("\n\n/reopen\nwhy"), tc.Command("reopen"))
|
||||
|
||||
def test_not_commands(self):
|
||||
for text in ("", "hello", "/nightly 5", "/closed", "/labels bug", "/closer", "close", "/unlabeled x"):
|
||||
self.assertIsNone(tc.parse(text), text)
|
||||
|
||||
def test_malformed(self):
|
||||
for text in ("/close maybe", "/close duplicate of", "/reopen now", "/label", "/label ,", "/unlabel a, b",
|
||||
"/label " + ",".join(str(i) for i in range(11))):
|
||||
with self.assertRaises(tc.Refused, msg=text):
|
||||
tc.parse(text)
|
||||
|
||||
def test_quoting_is_safe(self):
|
||||
with self.assertRaises(tc.Refused) as e:
|
||||
tc.parse("/close @ludovic111 [x](http://evil)")
|
||||
self.assertNotIn("@", str(e.exception))
|
||||
self.assertNotIn("](", str(e.exception))
|
||||
|
||||
|
||||
class AllowTests(unittest.TestCase):
|
||||
def test_listed_and_ludovic(self):
|
||||
do("/close", login="RDBTcvs")
|
||||
do("/close", login="ludovic111")
|
||||
|
||||
def test_stranger_refused(self):
|
||||
with self.assertRaisesRegex(tc.Refused, "Only Ludovic"):
|
||||
do("/close", login="someone")
|
||||
|
||||
def test_paused(self):
|
||||
paused = ns.read_reviewers("kacpherek\npaused\n")
|
||||
with self.assertRaisesRegex(tc.Refused, "paused"):
|
||||
do("/close", reviewers=paused)
|
||||
do("/close", reviewers=paused, login="ludovic111")
|
||||
|
||||
def test_the_repos_list_is_the_nightlys(self):
|
||||
self.assertEqual(ns.REVIEWERS, ".github/trusted-reviewers.txt")
|
||||
listed = ns.read_reviewers((ROOT / ns.REVIEWERS).read_text())
|
||||
self.assertEqual(listed.logins, {"kacpherek", "rdbtcvs", "online5277"})
|
||||
self.assertFalse(listed.paused)
|
||||
|
||||
|
||||
class ActionTests(unittest.TestCase):
|
||||
def test_close_issue(self):
|
||||
text, api = do("/close not planned")
|
||||
self.assertEqual(api.calls, [("close", 5, "not_planned")])
|
||||
self.assertIn("on behalf of @kacpherek", text)
|
||||
self.assertIn(URL, text)
|
||||
self.assertTrue(text.startswith("🤖 Triage: "))
|
||||
|
||||
def test_close_pr_has_no_reason(self):
|
||||
api = Fake({5: thread(pr=True)})
|
||||
text, _ = do("/close", api)
|
||||
self.assertEqual(api.calls, [("close", 5, None)])
|
||||
self.assertIn("without merging", text)
|
||||
|
||||
def test_duplicate(self):
|
||||
api = Fake({5: thread(), 9: thread()})
|
||||
text, _ = do("/close duplicate of #9", api)
|
||||
self.assertEqual(api.calls, [("comment", 5, "Duplicate of #9"), ("close", 5, "duplicate")])
|
||||
self.assertIn("#9", text)
|
||||
|
||||
def test_duplicate_of_missing_or_itself(self):
|
||||
with self.assertRaisesRegex(tc.Refused, "no #9"):
|
||||
do("/close duplicate of #9")
|
||||
with self.assertRaisesRegex(tc.Refused, "itself"):
|
||||
do("/close duplicate of #5")
|
||||
|
||||
def test_reopen(self):
|
||||
_, api = do("/reopen", Fake({5: thread("closed")}))
|
||||
self.assertEqual(api.calls, [("reopen", 5)])
|
||||
with self.assertRaisesRegex(tc.Refused, "already open"):
|
||||
do("/reopen")
|
||||
with self.assertRaisesRegex(tc.Refused, "already closed"):
|
||||
do("/close", Fake({5: thread("closed")}))
|
||||
|
||||
def test_label_uses_the_real_name_and_skips_present(self):
|
||||
_, api = do("/label Good First Issue, BUG")
|
||||
self.assertEqual(api.calls, [("add", 5, ["good first issue"])])
|
||||
with self.assertRaisesRegex(tc.Refused, "already has"):
|
||||
do("/label bug")
|
||||
|
||||
def test_label_must_exist(self):
|
||||
with self.assertRaisesRegex(tc.Refused, "no label"):
|
||||
do("/label nonsense")
|
||||
|
||||
def test_unlabel(self):
|
||||
_, api = do("/unlabel BUG")
|
||||
self.assertEqual(api.calls, [("remove", 5, "bug")])
|
||||
with self.assertRaisesRegex(tc.Refused, "doesn't have"):
|
||||
do("/unlabel good first issue")
|
||||
|
||||
|
||||
class RefusalTests(unittest.TestCase):
|
||||
def test_release_and_parity_labels(self):
|
||||
for name in ("release-now", "Release-Blocker", "skip-release", "full-parity", "prerelease"):
|
||||
for verb in ("/label", "/unlabel"):
|
||||
with self.assertRaisesRegex(tc.Refused, "release or parity", msg=name):
|
||||
do(f"{verb} {name}", Fake(labels=(name,)))
|
||||
with self.assertRaises(tc.Refused):
|
||||
do("/label bug, release-now")
|
||||
|
||||
def test_ludovics_threads(self):
|
||||
for text in ("/close", "/label bug", "/unlabel bug", "/reopen"):
|
||||
for t in (thread(user="ludovic111", state="closed" if text == "/reopen" else "open"),
|
||||
thread(user="Ludovic111", pr=True)):
|
||||
with self.assertRaisesRegex(tc.Refused, "Ludovic's"):
|
||||
do(text, Fake({5: t}))
|
||||
|
||||
def test_merged_pr(self):
|
||||
for text in ("/close", "/reopen", "/label bug", "/unlabel bug"):
|
||||
with self.assertRaisesRegex(tc.Refused, "merged"):
|
||||
do(text, Fake({5: thread("closed", pr=True, merged=True)}))
|
||||
|
||||
def test_locked(self):
|
||||
for text in ("/close", "/label good first issue", "/unlabel bug"):
|
||||
with self.assertRaisesRegex(tc.Refused, "locked"):
|
||||
do(text, Fake({5: thread(locked=True)}))
|
||||
|
||||
def test_missing_thread(self):
|
||||
with self.assertRaisesRegex(tc.Refused, "no such"):
|
||||
do("/close", Fake({}))
|
||||
|
||||
def test_nothing_written_on_refusal(self):
|
||||
api = Fake({5: thread(user="ludovic111")})
|
||||
with self.assertRaises(tc.Refused):
|
||||
do("/close", api)
|
||||
self.assertEqual(api.calls, [])
|
||||
|
||||
|
||||
def past(login, n, who="github-actions[bot]"):
|
||||
return [{"user": who, "body": f"🤖 Triage: closed as completed, on behalf of @{login} ([their comment](u))."}
|
||||
for _ in range(n)]
|
||||
|
||||
|
||||
class LimitTests(unittest.TestCase):
|
||||
def test_sixty_a_day(self):
|
||||
with self.assertRaisesRegex(tc.Refused, "60"):
|
||||
do("/close", Fake(past=past("kacpherek", 60)))
|
||||
do("/close", Fake(past=past("kacpherek", 59)))
|
||||
|
||||
def test_other_reviewers_and_forged_comments_dont_count(self):
|
||||
do("/close", Fake(past=past("rdbtcvs", 80)))
|
||||
do("/close", Fake(past=past("kacpherek", 80, who="someone")))
|
||||
|
||||
def test_refusals_dont_count(self):
|
||||
refusals = [{"user": "github-actions[bot]", "body": "🤖 Triage: refused, nope (asked by @kacpherek)"}] * 70
|
||||
do("/close", Fake(past=refusals))
|
||||
|
||||
def test_counts_case_insensitively(self):
|
||||
with self.assertRaises(tc.Refused):
|
||||
do("/close", Fake(past=past("kacpherek", 60)), login="Kacpherek")
|
||||
|
||||
def test_ludovic_is_unlimited(self):
|
||||
do("/close", Fake(past=past("ludovic111", 100)), login="ludovic111")
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
def test_workflow_is_safe(self):
|
||||
text = (ROOT / ".github/workflows/triage-command.yml").read_text()
|
||||
run_lines = [l for l in text.splitlines() if l.strip().startswith("run:")]
|
||||
self.assertEqual(run_lines, [" run: python3 tools/ci/triage_command.py command"])
|
||||
self.assertIn("persist-credentials: false", text)
|
||||
self.assertNotIn("pull_request_target", text)
|
||||
for perm in ("issues: write", "pull-requests: write", "contents: read"):
|
||||
self.assertIn(perm, text)
|
||||
self.assertNotIn("contents: write", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,7 +4,7 @@
|
||||
nightly_set.py command one `/nightly …` comment (nightly-command.yml): checks who asked, updates the set,
|
||||
starts the build and answers in the thread
|
||||
|
||||
A comment by Ludovic or by a login in .github/nightly-reviewers.txt, on any issue or pull request:
|
||||
A comment by Ludovic or by a login in .github/trusted-reviewers.txt, on any issue or pull request:
|
||||
|
||||
/nightly 2640 2642 the set becomes these pull requests, merged onto main in this order; builds now
|
||||
/nightly add 2650 adds one, or takes its newest head again; builds now
|
||||
@@ -35,7 +35,7 @@ from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
OWNER = "ludovic111"
|
||||
REVIEWERS = ".github/nightly-reviewers.txt"
|
||||
REVIEWERS = ".github/trusted-reviewers.txt"
|
||||
CODEOWNERS = ".github/CODEOWNERS"
|
||||
# What CODEOWNERS guards today, refused even if the file moved: what builds, signs and checks releases.
|
||||
ALWAYS_GUARDED = ["/.github/", "/tools/ci/", "/crates/horizon-release-sign/", "/crates/horizon-server/src/update.rs",
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Trusted reviewers triage issues and pull requests with comment commands (docs/release-flow.md "Trusted reviewers").
|
||||
|
||||
triage_command.py command one comment (triage-command.yml): checks who asked, acts, answers in the thread
|
||||
|
||||
A comment by Ludovic or by a login in .github/trusted-reviewers.txt, on the first line:
|
||||
|
||||
/close [completed|not planned] closes an issue (a pull request: closes it without merging)
|
||||
/close duplicate of #123 comments "Duplicate of #123" and closes it as a duplicate
|
||||
/reopen
|
||||
/label bug, good first issue existing labels only; never creates one
|
||||
/unlabel bug
|
||||
|
||||
Refused with a one-line answer: a label with `release` in it or `full-parity`; anything by Ludovic (his issues and
|
||||
pull requests); a merged pull request; a locked thread; more than 60 actions per reviewer in 24 hours. No code of any
|
||||
pull request is read or run: only the comment's text, its author and the API's answers, which reach this script as
|
||||
env vars.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import nightly_set as ns # noqa: E402 (the same list, owner and paused rule as /nightly)
|
||||
|
||||
MAX_PER_DAY = 60
|
||||
PREFIX = "🤖 Triage: "
|
||||
COMMANDS = ("close", "reopen", "label", "unlabel")
|
||||
REASONS = {"completed": "completed", "not planned": "not_planned", "not_planned": "not_planned"}
|
||||
DUPLICATE = re.compile(r"^(?:as\s+)?(?:a\s+)?duplicate\s+of\s+#?(\d{1,7})$", re.I)
|
||||
USAGE = ("Use `/close`, `/close not planned`, `/close duplicate of #123`, `/reopen`, `/label bug, good first issue` "
|
||||
"or `/unlabel bug`.")
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
"""A command that changes nothing; its text is the answer."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Command:
|
||||
verb: str # close, reopen, label, unlabel
|
||||
reason: str | None = None # close: completed, not_planned, duplicate
|
||||
original: int | None = None # close duplicate of #N
|
||||
labels: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def safe(text: str) -> str:
|
||||
"""Text of a comment, fit to quote back: no markdown, no mentions."""
|
||||
return re.sub(r"[^\w#:. -]", "", text)[:60].strip() or "?"
|
||||
|
||||
|
||||
def parse(body: str) -> Command | None:
|
||||
"""The command on a comment's first line; None when it isn't one. Raises Refused when it is one, but wrong."""
|
||||
line = next((line.strip() for line in body.splitlines() if line.strip()), "")
|
||||
m = re.match(r"^/(\w+)(?:\s+(.*))?$", line)
|
||||
if not m or m.group(1).lower() not in COMMANDS:
|
||||
return None
|
||||
verb, rest = m.group(1).lower(), (m.group(2) or "").strip()
|
||||
if verb == "reopen":
|
||||
if rest:
|
||||
raise Refused(f"`/reopen` takes no arguments. {USAGE}")
|
||||
return Command("reopen")
|
||||
if verb == "close":
|
||||
if not rest:
|
||||
return Command("close", "completed")
|
||||
dup = DUPLICATE.match(rest)
|
||||
if dup:
|
||||
return Command("close", "duplicate", int(dup.group(1)))
|
||||
reason = REASONS.get(" ".join(rest.lower().split()))
|
||||
if not reason:
|
||||
raise Refused(f"`{safe(rest)}` isn't a way to close. {USAGE}")
|
||||
return Command("close", reason)
|
||||
names = tuple(dict.fromkeys(n.strip() for n in rest.split(",") if n.strip()))
|
||||
if not names:
|
||||
raise Refused(f"`/{verb}` needs a label name. {USAGE}")
|
||||
if verb == "unlabel" and len(names) > 1:
|
||||
raise Refused(f"`/unlabel` takes one label. {USAGE}")
|
||||
if len(names) > 10:
|
||||
raise Refused("At most 10 labels at once.")
|
||||
return Command(verb, labels=names)
|
||||
|
||||
|
||||
def label_refusal(name: str) -> str | None:
|
||||
low = name.lower()
|
||||
if "release" in low or low == "full-parity":
|
||||
return f"`{safe(name)}` is a release or parity label: only Ludovic's side touches those."
|
||||
return None
|
||||
|
||||
|
||||
def authorize(login: str, reviewers: ns.Reviewers) -> None:
|
||||
"""Ludovic always; a listed reviewer unless the list is paused; nobody else."""
|
||||
if ns.is_owner(login):
|
||||
return
|
||||
if login.lower() not in reviewers.logins:
|
||||
raise Refused(f"Only Ludovic and the trusted reviewers listed in `{ns.REVIEWERS}` can triage this way.")
|
||||
if reviewers.paused:
|
||||
raise Refused(f"Triage commands are paused: Ludovic stopped them in `{ns.REVIEWERS}`.")
|
||||
|
||||
|
||||
def target_refusal(issue: dict, cmd: Command, login: str) -> str | None:
|
||||
"""Why this thread can't be acted on (None when it can). `issue` is GitHub's issue object."""
|
||||
is_pr = "pull_request" in issue
|
||||
kind = "pull request" if is_pr else "issue"
|
||||
if not ns.is_owner(login) and ns.is_owner((issue.get("user") or {}).get("login", "")):
|
||||
return f"This {kind} is Ludovic's: triage commands don't touch it."
|
||||
if is_pr and (issue["pull_request"] or {}).get("merged_at"):
|
||||
return "That pull request is already merged."
|
||||
if issue.get("locked"):
|
||||
return f"This {kind} is locked: triage commands don't act on it."
|
||||
closed = issue.get("state") == "closed"
|
||||
if cmd.verb == "close" and closed:
|
||||
return f"This {kind} is already closed."
|
||||
if cmd.verb == "reopen" and not closed:
|
||||
return f"This {kind} is already open."
|
||||
return None
|
||||
|
||||
|
||||
def names_of(issue: dict) -> set[str]:
|
||||
return {str(l.get("name", "") if isinstance(l, dict) else l).lower() for l in issue.get("labels", [])}
|
||||
|
||||
|
||||
# --- GitHub ------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def gh(*args: str, check: bool = True) -> str:
|
||||
r = subprocess.run(["gh", *args], capture_output=True, text=True)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError(f"gh {args[0]} {args[1] if len(args) > 1 else ''}: {r.stderr.strip()[:300]}")
|
||||
return r.stdout.strip() if r.returncode == 0 else ""
|
||||
|
||||
|
||||
class Api:
|
||||
"""The few GitHub calls this needs; tests replace it."""
|
||||
|
||||
def __init__(self, repo: str):
|
||||
self.repo = repo
|
||||
|
||||
def issue(self, n: int) -> dict | None:
|
||||
raw = gh("api", f"repos/{self.repo}/issues/{n}", check=False)
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
def label(self, name: str) -> str | None:
|
||||
"""The label's real name, or None when the repository has no such label."""
|
||||
raw = gh("api", f"repos/{self.repo}/labels/{name.replace('/', '%2F').replace(' ', '%20')}", check=False)
|
||||
return json.loads(raw)["name"] if raw else None
|
||||
|
||||
def add_labels(self, n: int, names: list[str]) -> None:
|
||||
args = ["api", f"repos/{self.repo}/issues/{n}/labels"]
|
||||
for name in names:
|
||||
args += ["-f", f"labels[]={name}"]
|
||||
gh(*args)
|
||||
|
||||
def remove_label(self, n: int, name: str) -> None:
|
||||
gh("api", "-X", "DELETE", f"repos/{self.repo}/issues/{n}/labels/{name.replace(' ', '%20')}")
|
||||
|
||||
def close(self, n: int, reason: str | None) -> None:
|
||||
args = ["api", "-X", "PATCH", f"repos/{self.repo}/issues/{n}", "-f", "state=closed"]
|
||||
if reason:
|
||||
args += ["-f", f"state_reason={reason}"]
|
||||
gh(*args)
|
||||
|
||||
def reopen(self, n: int) -> None:
|
||||
gh("api", "-X", "PATCH", f"repos/{self.repo}/issues/{n}", "-f", "state=open")
|
||||
|
||||
def comment(self, n: int, text: str) -> None:
|
||||
gh("api", f"repos/{self.repo}/issues/{n}/comments", "-f", f"body={text}")
|
||||
|
||||
def recent_comments(self, since: str) -> list[dict]:
|
||||
"""Comments of the whole repository since a time (ISO 8601), as {user, body}."""
|
||||
raw = gh("api", "--paginate", f"repos/{self.repo}/issues/comments?since={since}&per_page=100", "--jq",
|
||||
'.[] | {user: .user.login, body: .body}')
|
||||
return [json.loads(line) for line in raw.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def actions_by(api, login: str, now: datetime) -> int:
|
||||
"""Actions this workflow answered for `login` in the last 24 h, counted from its own comments."""
|
||||
since = (now - timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
tag = f"on behalf of @{login.lower()}"
|
||||
return sum(1 for c in api.recent_comments(since)
|
||||
if c["user"] == "github-actions[bot]" and c["body"].startswith(PREFIX)
|
||||
and c["body"].split("\n", 1)[0].lower().count(tag))
|
||||
|
||||
|
||||
def say(action: str, login: str, url: str) -> str:
|
||||
return f"{PREFIX}{action}, on behalf of @{login} ([their comment]({url}))."
|
||||
|
||||
|
||||
def run(api, cmd: Command, login: str, number: int, url: str, reviewers: ns.Reviewers, now: datetime) -> str:
|
||||
"""Does the command; returns the comment to post. Raises Refused for a refusal."""
|
||||
authorize(login, reviewers)
|
||||
for name in cmd.labels:
|
||||
if (why := label_refusal(name)):
|
||||
raise Refused(why)
|
||||
issue = api.issue(number)
|
||||
if issue is None:
|
||||
raise Refused("There is no such issue or pull request.")
|
||||
if (why := target_refusal(issue, cmd, login)):
|
||||
raise Refused(why)
|
||||
if cmd.original is not None:
|
||||
if cmd.original == number:
|
||||
raise Refused("An item cannot be a duplicate of itself.")
|
||||
if api.issue(cmd.original) is None:
|
||||
raise Refused(f"There is no #{cmd.original} in Horizon.")
|
||||
if not ns.is_owner(login) and actions_by(api, login, now) >= MAX_PER_DAY:
|
||||
raise Refused(f"You used your {MAX_PER_DAY} triage actions of the last 24 hours. Try again later.")
|
||||
is_pr = "pull_request" in issue
|
||||
if cmd.verb == "reopen":
|
||||
api.reopen(number)
|
||||
return say("reopened", login, url)
|
||||
if cmd.verb == "close":
|
||||
if cmd.reason == "duplicate":
|
||||
api.comment(number, f"Duplicate of #{cmd.original}")
|
||||
api.close(number, None if is_pr else "duplicate")
|
||||
return say(f"closed as a duplicate of #{cmd.original}", login, url)
|
||||
api.close(number, None if is_pr else cmd.reason)
|
||||
how = "closed without merging" if is_pr else f"closed as {cmd.reason.replace('_', ' ')}"
|
||||
return say(how, login, url)
|
||||
have = names_of(issue)
|
||||
real: list[str] = []
|
||||
for name in cmd.labels:
|
||||
found = api.label(name)
|
||||
if found is None:
|
||||
raise Refused(f"There is no label `{safe(name)}` in Horizon: triage doesn't create new ones.")
|
||||
if (why := label_refusal(found)):
|
||||
raise Refused(why)
|
||||
real.append(found)
|
||||
if cmd.verb == "label":
|
||||
new = [n for n in real if n.lower() not in have]
|
||||
if not new:
|
||||
raise Refused("It already has " + ("that label." if len(real) == 1 else "those labels."))
|
||||
api.add_labels(number, new)
|
||||
return say("added " + ", ".join(f"`{n}`" for n in new), login, url)
|
||||
name = real[0]
|
||||
if name.lower() not in have:
|
||||
raise Refused(f"It doesn't have `{name}`.")
|
||||
api.remove_label(number, name)
|
||||
return say(f"removed `{name}`", login, url)
|
||||
|
||||
|
||||
def command() -> int:
|
||||
body, login = os.environ["BODY"], os.environ["AUTHOR"]
|
||||
number, url, repo = int(os.environ["ISSUE"]), os.environ.get("COMMENT_URL", ""), os.environ["REPO"]
|
||||
api: Api = Api(repo)
|
||||
try:
|
||||
cmd = parse(body)
|
||||
if cmd is None:
|
||||
return 0
|
||||
reviewers = ns.read_reviewers(Path(ns.REVIEWERS).read_text())
|
||||
text = run(api, cmd, login, number, url, reviewers, datetime.now(timezone.utc))
|
||||
except Refused as e:
|
||||
text = f"{PREFIX}refused, {e} (asked by @{safe(login)})"
|
||||
except RuntimeError as e:
|
||||
print(e, file=sys.stderr)
|
||||
text = f"{PREFIX}GitHub refused that, nothing more was done (asked by @{safe(login)})."
|
||||
api.comment(number, text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1:] != ["command"]:
|
||||
sys.exit(__doc__)
|
||||
sys.exit(command())
|
||||
Reference in New Issue
Block a user