Merge pull request #3319 from MoonEyes/org/claims-table

ci: a daily table of open claims in the coordination issue
This commit is contained in:
MoonEyes
2026-12-03 11:10:45 +00:00
committed by GitHub
3 changed files with 640 additions and 0 deletions

View File

@ -0,0 +1,94 @@
name: Coordination claims table
# Rewrites one section of the body of the open issue titled "Coordinating who works on what" with the claims that
# have no `done:` or `released:` line since (tools/coordination_claims.py), so what is taken and what has gone stale
# can be seen without reading thousands of comments. Daily, and on demand from the Actions tab.
#
# Only the text between <!-- claims-table:start --> and <!-- claims-table:end --> is replaced; the rest of the body is
# kept as it was read. The comments of the newest thread and of the one it says it continues are read (two threads
# bound the API calls: about 25 requests per 2,500 comments), plus the open pull requests. No pull request code is
# checked out or run, and no third-party action is used.
on:
schedule:
- cron: '41 4 * * *'
workflow_dispatch:
permissions: {}
concurrency:
# One run at a time; a second one would read the same body and the later edit would win anyway.
group: coordination-claims
cancel-in-progress: false
jobs:
update:
runs-on: ubuntu-24.04
timeout-minutes: 20
permissions:
contents: read
issues: write
pull-requests: read
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
fetch-depth: 1
- name: Update the claims table in the coordination issue
shell: bash
run: |
set -euo pipefail
work="$RUNNER_TEMP/claims"
mkdir -p "$work"
# The newest open issue whose title starts with the name; the thread moves to a new issue when it fills up.
# Only an issue opened by an owner, member or collaborator counts, so anyone else's issue with the same title
# cannot take the bot over.
number=$(gh api -X GET search/issues -f per_page=50 \
-f q="repo:$GITHUB_REPOSITORY is:issue is:open in:title \"Coordinating who works on what\"" \
--jq '[.items[] | select((.title | startswith("Coordinating who works on what"))
and (.author_association | IN("OWNER", "MEMBER", "COLLABORATOR"))) | .number] | max // empty')
if [ -z "$number" ]; then
echo "::error::No open issue titled 'Coordinating who works on what' was found."
exit 1
fi
echo "Coordination issue: #$number"
# The body exactly as stored: `--jq .body` adds a newline, and the body would grow by one each day.
read_body() {
gh issue view "$number" --json body |
python3 -I -c 'import json, sys; sys.stdout.write(json.load(sys.stdin)["body"] or "")'
}
read_body > "$work/body.md"
# The thread this one continues, if its body says so ("Continued from #N", "Continuation of #N").
previous=$(grep -oiE '(continued from|continuation of) #[0-9]+' "$work/body.md" | head -n 1 | grep -oE '[0-9]+$' || true)
threads="$number"
if [ -n "$previous" ] && [ "$previous" != "$number" ]; then
threads="$previous $number"
fi
files=()
for t in $threads; do
echo "Reading the comments of #$t"
gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$t/comments?per_page=100" \
--jq '.[] | {user: (.user.login // "ghost"), created_at, body}' > "$work/comments-$t.jsonl"
files+=("$work/comments-$t.jsonl")
done
gh pr list --state open --limit 1000 --json number,title,body > "$work/prs.json"
python3 -I tools/coordination_claims.py --comments "${files[@]}" --prs "$work/prs.json" \
--update-body "$work/body.md" --out "$work/new_body.md"
if cmp -s "$work/body.md" "$work/new_body.md"; then
echo "The body of #$number is already up to date."
elif ! read_body | cmp -s - "$work/body.md"; then
# Someone edited the body while the comments were read: keep their edit; the next run redoes the table.
echo "::warning::The body of #$number changed during the run; not overwriting it."
else
gh issue edit "$number" --body-file "$work/new_body.md"
echo "Updated the claims table in #$number."
fi

View File

@ -0,0 +1,295 @@
"""tools/coordination_claims.py builds the table of open claims of the coordination issue.
python -I tests/test_coordination_claims.py
Synthetic comments and pull requests only, no network and no game files. Covers the claim formats (several IDs on a
line, bold `**claiming:**`, arrows and parentheses that start prose), `done:`/`released:` closing and re-claiming, the
whole-token match of an ID in an open pull request (`D3D12-A` is not `D3D12-AB`), replacing only the text between the
markers of an issue body (and appending the block when they are absent), the cap on the body length, and that
`.github/workflows/coordination-claims.yml` runs the tool with the permissions it needs and no third-party action.
"""
import datetime
import json
import os
import re
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import coordination_claims as cc # noqa: E402
NOW = cc.parse_time("2026-12-03T12:00:00Z")
def comment(user, day, body, hour=9):
return {"user": user, "created_at": "2026-%sT%02d:00:00Z" % (day, hour), "body": body}
def claims(comments):
state, _ = cc.open_claims(comments)
return state
class Parsing(unittest.TestCase):
def test_one_id_and_several_ids_on_a_line(self):
state = claims([comment("ann", "11-20", "claiming: D3D12-HLE-A, VERIFY-2285 and VERIFY-7")])
self.assertEqual(sorted(state), ["D3D12-HLE-A", "VERIFY-2285", "VERIFY-7"])
self.assertEqual(state["VERIFY-2285"]["by"], "ann")
self.assertEqual(state["VERIFY-2285"]["date"], datetime.date(2026, 11, 20))
def test_bold_and_list_forms(self):
state = claims([comment("ann", "11-20", "**claiming:** AA-1\n- Claiming: BB-2\n**Claiming**: CC-3\n__claiming:__ DD-4")])
self.assertEqual(sorted(state), ["AA-1", "BB-2", "CC-3", "DD-4"])
def test_text_after_an_arrow_or_a_parenthesis_is_not_an_id_list(self):
state = claims([
comment("ann", "11-20", "claiming: AA-1 -> fix the CLI-OPTION table"),
comment("bob", "11-20", "claiming: BB-2 → see D3D12-NOT-THIS"),
comment("cy", "11-20", "claiming: CC-3 (follow-up of OLD-99)"),
])
self.assertEqual(sorted(state), ["AA-1", "BB-2", "CC-3"])
def test_the_keyword_must_start_the_line(self):
state = claims([comment("ann", "11-20", "I am not claiming: AA-1\nsee claiming: BB-2 above\nclaiming: CC-3")])
self.assertEqual(sorted(state), ["CC-3"])
def test_quotes_and_code_blocks_are_ignored(self):
text = "> claiming: QQ-1\n```\nclaiming: CC-1\n```\n~~~\nclaiming: TT-1\n~~~\nclaiming: REAL-1"
self.assertEqual(sorted(claims([comment("ann", "11-20", text)])), ["REAL-1"])
closed = claims([comment("ann", "11-20", "claiming: AA-1"),
comment("bob", "11-21", "> done: AA-1 -> #5\nnot yet")])
self.assertEqual(sorted(closed), ["AA-1"])
def test_the_first_claimant_keeps_an_open_claim(self):
state = claims([comment("bob", "11-22", "claiming: AA-1"), comment("ann", "11-20", "claiming: AA-1")])
self.assertEqual(state["AA-1"]["by"], "ann") # input order does not matter, time does
self.assertEqual(state["AA-1"]["date"], datetime.date(2026, 11, 20))
def test_not_an_id(self):
self.assertEqual(claims([comment("ann", "11-20", "claiming: the shader work, UTF8 and x-y")]), {})
def test_input_shapes(self):
one = {"user": {"login": "ann"}, "created_at": "2026-11-20T09:00:00Z", "body": "claiming: AA-1"}
two = {"u": "bob", "t": "2026-11-21T09:00:00Z", "b": "claiming: BB-2"}
jsonl = json.dumps(one) + "\n" + json.dumps(two) + "\n"
glued = json.dumps([one]) + json.dumps([two]) # what `gh api --paginate` prints without --jq
for text in (jsonl, glued, json.dumps([one, two])):
state = claims(cc.load_json_values(text))
self.assertEqual({k: v["by"] for k, v in state.items()}, {"AA-1": "ann", "BB-2": "bob"})
self.assertEqual(cc.load_json_values(""), [])
class Closing(unittest.TestCase):
def test_done_and_released_close(self):
state = claims([
comment("ann", "11-20", "claiming: AA-1, BB-2, CC-3, DD-4"),
comment("ann", "11-21", "done: AA-1 -> #12"),
comment("bob", "11-21", "Released: BB-2"),
comment("cy", "11-22", "**done:** CC-3 → #13 (merged)"),
])
self.assertEqual(sorted(state), ["DD-4"])
def test_done_closes_every_id_named_before_the_arrow(self):
state = claims([comment("ann", "11-20", "claiming: AA-1, BB-2"), comment("ann", "11-21", "done: AA-1, BB-2 -> #4")])
self.assertEqual(state, {})
def test_a_claim_after_a_release_opens_it_again(self):
state = claims([
comment("ann", "11-20", "claiming: AA-1"),
comment("ann", "11-21", "released: AA-1"),
comment("bob", "11-25", "claiming: AA-1"),
])
self.assertEqual(state["AA-1"]["by"], "bob")
self.assertEqual(state["AA-1"]["date"], datetime.date(2026, 11, 25))
def test_a_close_before_the_claim_does_not_hide_it(self):
state = claims([comment("ann", "11-20", "done: AA-1 -> #1"), comment("bob", "11-21", "claiming: AA-1")])
self.assertEqual(sorted(state), ["AA-1"])
def test_the_count_of_ids_ever_claimed_includes_closed_ones(self):
_, ever = cc.open_claims([comment("ann", "11-20", "claiming: AA-1, BB-2"), comment("ann", "11-21", "done: AA-1")])
self.assertEqual(ever, 2)
class PullRequests(unittest.TestCase):
PRS = [
{"number": 30, "title": "D3D12-AB: other thing", "body": None},
{"number": 20, "title": "fix", "body": "Claim: `D3D12-A` in #3312"},
{"number": 10, "title": "D3D12-A", "body": ""},
{"number": 40, "title": "part of D3D12-A-2", "body": "and XD3D12-A, D3D12-A_ plus D3D12-A."},
{"number": 50, "title": "d3d12-a lowercase", "body": ""},
]
def test_whole_token_only(self):
self.assertEqual(cc.prs_naming("D3D12-A", self.PRS), [10, 20, 40]) # 40 only through the final "D3D12-A."
self.assertEqual(cc.prs_naming("D3D12-AB", self.PRS), [30])
self.assertEqual(cc.prs_naming("D3D12-A-2", self.PRS), [40])
def test_longer_id_does_not_match_a_prefix(self):
prs = [{"number": 1, "title": "D3D12-A-2 and VERIFY-12", "body": ""}]
self.assertEqual(cc.prs_naming("D3D12-A", prs), [])
self.assertEqual(cc.prs_naming("VERIFY-1", prs), [])
self.assertEqual(cc.prs_naming("VERIFY-12", prs), [1])
def test_at_most_three_lowest_first(self):
prs = [{"number": n, "title": "AA-1", "body": ""} for n in (9, 3, 7, 5, 1)]
self.assertEqual(cc.prs_naming("AA-1", prs), [1, 3, 5])
self.assertEqual(cc.prs_naming("AA-1", prs, limit=2), [1, 3])
class Table(unittest.TestCase):
def setUp(self):
self.comments = [
comment("bob", "11-25", "claiming: NEW-1"),
comment("ann", "11-20", "claiming: OLD-1, GONE-1"),
comment("ann", "11-26", "done: GONE-1 -> #3"),
]
self.prs = [{"number": 77, "title": "NEW-1 landing", "body": ""}]
def rows(self):
state, ever = cc.open_claims(self.comments)
return cc.build_rows(state, self.prs, NOW), ever
def test_oldest_first_with_age_and_prs(self):
rows, _ = self.rows()
self.assertEqual([r[1] for r in rows], ["OLD-1", "NEW-1"])
self.assertEqual([r[3] for r in rows], [13, 8])
self.assertEqual(cc.row_line(rows[0]), "| 2026-11-20 | `OLD-1` | ann | 13 | none |")
self.assertEqual(cc.row_line(rows[1]), "| 2026-11-25 | `NEW-1` | bob | 8 | #77 |")
def test_counts(self):
rows, ever = self.rows()
text, shown = cc.render_table(rows, ever, NOW)
self.assertEqual(shown, 2)
self.assertIn("3 IDs claimed in the threads read, 2 with no `done:`/`released:` line, 1 of those with no open "
"pull request naming them.", text)
self.assertIn("| Claimed | ID | By | Age (days) | Open PRs naming the ID |", text)
def test_empty(self):
text, shown = cc.render_table([], 0, NOW)
self.assertEqual(shown, 0)
self.assertIn("0 IDs claimed", text)
class UpdateBody(unittest.TestCase):
def rows(self, n=2):
comments = [comment("u%d" % i, "11-20", "claiming: ID-%d" % i, hour=i % 24) for i in range(n)]
state, ever = cc.open_claims(comments)
return cc.build_rows(state, [], NOW), ever
def test_replaces_only_between_markers(self):
rows, ever = self.rows()
body = "intro\n\n%s\nOLD TABLE\n%s\n\n## Tail\nkept\n" % (cc.START, cc.END)
new = cc.update_body(body, rows, ever, NOW)
self.assertTrue(new.startswith("intro\n\n" + cc.START + "\n"))
self.assertTrue(new.endswith(cc.END + "\n\n## Tail\nkept\n"))
self.assertNotIn("OLD TABLE", new)
self.assertIn("`ID-0`", new)
self.assertEqual(new.count(cc.START), 1)
self.assertEqual(new.count(cc.END), 1)
def test_running_twice_gives_the_same_body(self):
rows, ever = self.rows()
once = cc.update_body("intro", rows, ever, NOW)
self.assertEqual(cc.update_body(once, rows, ever, NOW), once)
def test_appends_the_block_when_the_markers_are_absent(self):
rows, ever = self.rows()
new = cc.update_body("intro\n", rows, ever, NOW)
self.assertTrue(new.startswith("intro\n\n" + cc.START + "\n"))
self.assertTrue(new.endswith("\n" + cc.END))
self.assertTrue(cc.update_body("", rows, ever, NOW).startswith(cc.START))
def test_one_marker_alone_is_refused(self):
rows, ever = self.rows()
for body in ("a\n" + cc.START + "\nb", "a\n" + cc.END + "\nb", cc.END + "\nx\n" + cc.START):
with self.assertRaises(ValueError):
cc.update_body(body, rows, ever, NOW)
def test_length_cap_truncates_the_table_and_says_how_many(self):
rows, ever = self.rows(400)
limit = 6000
body = "x" * 1000 + "\n" + cc.START + "\nold\n" + cc.END + "\ntail"
new = cc.update_body(body, rows, ever, NOW, limit=limit, safety=0)
self.assertLessEqual(len(new), limit)
self.assertTrue(new.startswith("x" * 1000))
self.assertTrue(new.endswith(cc.END + "\ntail"))
shown = new.count("| `ID-")
self.assertTrue(0 < shown < 400)
self.assertRegex(new, r"%d more claims not shown" % (400 - shown))
# the oldest rows are the ones kept
self.assertIn("`ID-0`", new)
self.assertNotIn("`ID-399`", new)
def test_default_limit_is_githubs(self):
rows, ever = self.rows(2500)
new = cc.update_body("intro", rows, ever, NOW)
self.assertLess(len(new), 65536)
self.assertGreater(len(new), 60000)
self.assertIn("more claims not shown", new)
def test_a_body_that_leaves_no_room_is_an_error(self):
rows, ever = self.rows()
with self.assertRaises(ValueError):
cc.update_body("x" * 7000, rows, ever, NOW, limit=7200, safety=0)
class CommandLine(unittest.TestCase):
def test_table_and_update_body_through_files(self):
with tempfile.TemporaryDirectory() as tmp:
def write(name, text):
path = os.path.join(tmp, name)
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
return path
comments = write("c.jsonl", "\n".join(json.dumps(c) for c in [
comment("ann", "11-20", "claiming: AA-1, BB-2"), comment("bob", "11-21", "done: BB-2 -> #9")]))
prs = write("prs.json", json.dumps([{"number": 5, "title": "AA-1", "body": ""}]))
body = write("body.md", "head\n" + cc.START + "\nold\n" + cc.END + "\n")
out = os.path.join(tmp, "out.md")
self.assertEqual(cc.main(["--comments", comments, "--prs", prs, "--now", "2026-12-03T00:00:00Z",
"--update-body", body, "--out", out]), 0)
with open(out, encoding="utf-8", newline="") as f:
text = f.read()
self.assertIn("| 2026-11-20 | `AA-1` | ann | 13 | #5 |", text)
self.assertNotIn("BB-2", text)
self.assertNotIn("\r", text)
self.assertTrue(text.startswith("head\n"))
class Workflow(unittest.TestCase):
def setUp(self):
with open(os.path.join(ROOT, ".github", "workflows", "coordination-claims.yml"), encoding="utf-8") as f:
self.text = f.read()
with open(os.path.join(ROOT, ".github", "workflows", "ci.yml"), encoding="utf-8") as f:
self.ci = f.read()
def test_triggers_and_permissions(self):
self.assertRegex(self.text, r"(?m)^on:\n schedule:\n - cron: '[^']+'\n workflow_dispatch:")
self.assertNotIn("pull_request", self.text)
job = self.text[self.text.index("\njobs:"):]
self.assertRegex(job, r"(?m)^ permissions:\n contents: read\n issues: write\n pull-requests: read\n")
self.assertRegex(self.text, r"(?m)^permissions: \{\}$")
self.assertRegex(job, r"(?m)^ timeout-minutes: \d+$")
def test_only_the_checkout_action_pinned_like_ci(self):
uses = re.findall(r"(?m)^\s*-?\s*uses:\s*(\S+)(?:\s*#.*)?$", self.text)
self.assertEqual(len(uses), 1)
self.assertTrue(uses[0].startswith("actions/checkout@"))
pinned = re.search(r"uses: (actions/checkout@[0-9a-f]{40}) # v\S+", self.ci).group(1)
self.assertEqual(uses[0], pinned)
self.assertIn("persist-credentials: false", self.text)
self.assertIn("GH_TOKEN: ${{ github.token }}", self.text)
def test_runs_the_tool_and_edits_the_body(self):
self.assertIn("python3 -I tools/coordination_claims.py", self.text)
self.assertIn("gh issue edit", self.text)
self.assertIn("--body-file", self.text)
self.assertIn("Coordinating who works on what", self.text)
self.assertIn("continued from|continuation of", self.text)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,251 @@
"""Table of the open claims in the coordination issue: claimed, and neither `done:` nor `released:` since.
python -I tools/coordination_claims.py --comments c1.jsonl [c2.jsonl ...] --prs prs.json [--now ISO8601]
python -I tools/coordination_claims.py --comments ... --prs ... --update-body body.md [--out new_body.md]
`.github/workflows/coordination-claims.yml` runs this daily and writes the result into the body of the issue titled
"Coordinating who works on what", so that what is taken and what has gone stale is visible without reading 2,500
comments. The comments follow the issue's own convention, one line each:
claiming: D3D12-HLE-KERNEL-LOADER-PARITY, VERIFY-2285 (comma-separated IDs; **claiming:** also counts)
done: VERIFY-2285 -> #3301 (text after `->`, a right arrow or `(` is not an ID list)
released: D3D12-HLE-KERNEL-LOADER-PARITY
A claim is open from its `claiming:` line until a later `done:` or `released:` (`releasing`, `dropped` and
`dropping` count as released) names the same ID; a `claiming:` after that opens it again. The second claimant of an
ID that is still open does not replace the first. Lines inside fenced code blocks and quoted lines (`>`) are
ignored, so a reply that quotes a claim does not make one. Several threads are read together, oldest comment first.
Input is JSON lines, one JSON array, or the concatenated arrays `gh api --paginate` prints without `--jq`. A comment
has an author login (`user` as a string or as an object with `login`, or `author`, `login`, `u`), a time
(`created_at` or `t`) and a text (`body` or `b`); an open pull request has `number`, `title` and `body`. The pull
requests listed for an ID are the open ones whose title or body names it as a whole token: `D3D12-A` is not found in
`D3D12-AB` or in `D3D12-A-2`.
`--update-body` replaces only the text between `<!-- claims-table:start -->` and `<!-- claims-table:end -->` of the
body it is given (the block, with both markers, is appended when they are absent) and keeps the body under GitHub's
65,536 characters by dropping the newest rows of the table and saying how many. The module makes no network calls.
Standard library only; no game files.
"""
import argparse
import datetime
import json
import re
import sys
START = "<!-- claims-table:start -->"
END = "<!-- claims-table:end -->"
BODY_LIMIT = 65536 # GitHub's cap on an issue body, in characters
SAFETY = 500 # kept free below it, so a count that differs a little cannot make the edit fail
MAX_PRS = 3
# A line that opens (`claiming:`) or closes a claim. Markdown emphasis may sit around the keyword and the colon.
_PREFIX = r"^[ \t*_-]*"
CLAIM = re.compile(_PREFIX + r"(?i:claiming)[*_]*[ \t]*:(.*)$", re.M)
CLOSE = re.compile(_PREFIX + r"(?i:done|released|releasing|dropped|dropping)[*_]*[ \t]*:(.*)$", re.M)
ID = re.compile(r"\b[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+\b")
FENCE = re.compile(r"^[ \t]*(```|~~~).*?^[ \t]*\1[ \t]*$", re.M | re.S)
QUOTE = re.compile(r"^[ \t]*>.*$", re.M)
def ids_in(rest):
"""The IDs of the text after a `claiming:`/`done:` keyword; what follows `->`, a right arrow or `(` is prose."""
return ID.findall(re.split(r"->|→|\(", rest, maxsplit=1)[0])
def strip_code_and_quotes(text):
return QUOTE.sub("", FENCE.sub("", text or ""))
def parse_time(value):
"""A timezone-aware UTC datetime from GitHub's `2026-11-28T09:15:00Z` (or any ISO 8601 form)."""
text = str(value).strip()
if text.endswith(("Z", "z")):
text = text[:-1] + "+00:00"
when = datetime.datetime.fromisoformat(text)
if when.tzinfo is None:
when = when.replace(tzinfo=datetime.timezone.utc)
return when.astimezone(datetime.timezone.utc)
def _login(comment):
for key in ("user", "author", "login", "u"):
value = comment.get(key)
if isinstance(value, dict):
value = value.get("login")
if value:
return str(value)
return "unknown"
def _first(comment, *keys):
for key in keys:
if comment.get(key) is not None:
return comment[key]
return None
def load_json_values(text):
"""Every JSON value in the text, one after another (JSON lines, one array, or arrays glued together), flattened
so that an array contributes its items."""
decoder = json.JSONDecoder()
values, pos, end = [], 0, len(text)
while True:
while pos < end and text[pos].isspace():
pos += 1
if pos >= end:
return values
value, pos = decoder.raw_decode(text, pos)
values.extend(value if isinstance(value, list) else [value])
def open_claims(comments):
"""{ID: {"date", "by", "at"}} of the claims with no later `done:`/`released:`, and the number of IDs ever claimed.
`comments` is an iterable of dicts (see the module docstring); order does not matter, they are sorted by time."""
events = []
for index, comment in enumerate(comments):
when = _first(comment, "created_at", "t")
if when is None:
continue
events.append((parse_time(when), index, _login(comment), _first(comment, "body", "b") or ""))
events.sort(key=lambda e: (e[0], e[1]))
state, ever = {}, set()
for when, _, login, body in events:
text = strip_code_and_quotes(body)
for match in CLAIM.finditer(text):
for claim_id in ids_in(match.group(1)):
ever.add(claim_id)
if claim_id not in state:
state[claim_id] = {"date": when.date(), "by": login, "at": when}
for match in CLOSE.finditer(text):
for claim_id in ids_in(match.group(1)):
state.pop(claim_id, None)
return state, len(ever)
def _token_pattern(claim_id):
# Not inside a longer ID: no letter, digit or `-<alnum>` before it and none after it.
return re.compile(r"(?<![A-Za-z0-9])(?<![A-Za-z0-9]-)" + re.escape(claim_id) + r"(?![A-Za-z0-9]|-[A-Za-z0-9])")
def prs_naming(claim_id, prs, limit=MAX_PRS):
"""Numbers of the open pull requests (lowest first) whose title or body names the ID as a whole token."""
pattern = _token_pattern(claim_id)
found = []
for pr in sorted(prs, key=lambda p: int(p["number"])):
if pattern.search("%s\n%s" % (pr.get("title") or "", pr.get("body") or "")):
found.append(int(pr["number"]))
if len(found) == limit:
break
return found
def build_rows(state, prs, now, max_prs=MAX_PRS):
"""Table rows, oldest claim first: (date, id, by, age in days, [PR numbers])."""
today = now.astimezone(datetime.timezone.utc).date()
rows = []
for claim_id, info in state.items():
age = max((today - info["date"]).days, 0)
rows.append((info["date"], claim_id, info["by"], age, prs_naming(claim_id, prs, max_prs)))
rows.sort(key=lambda r: (r[0], r[1]))
return rows
def row_line(row):
date, claim_id, by, age, numbers = row
shown = ", ".join("#%d" % n for n in numbers) or "none"
return "| %s | `%s` | %s | %d | %s |" % (date.isoformat(), claim_id, by, age, shown)
HEADER = "| Claimed | ID | By | Age (days) | Open PRs naming the ID |\n|---|---|---|---|---|"
def counts_line(rows, ever, now):
unmatched = sum(1 for r in rows if not r[4])
return ("%d IDs claimed in the threads read, %d with no `done:`/`released:` line, %d of those with no open pull "
"request naming them. Updated %s (UTC)."
% (ever, len(rows), unmatched, now.astimezone(datetime.timezone.utc).strftime("%Y-%m-%d")))
def render_table(rows, ever, now, budget=None):
"""The table and its counts, as markdown. With `budget` (characters) the newest rows are dropped to fit, and a
line says how many. Returns (text, rows shown)."""
intro = ("Built from the `claiming:`, `done:` and `released:` lines of the newest threads, so an item finished "
"in an older thread or by a pull request that does not name its ID still shows here. If one of these "
"is yours and it is finished or abandoned, post `done:` or `released:` in this issue.")
head = "%s\n\n%s\n\n" % (intro, counts_line(rows, ever, now))
lines = [row_line(r) for r in rows]
def assemble(count):
text = head + HEADER + "".join("\n" + line for line in lines[:count])
if count < len(lines):
text += "\n\n%d more claims not shown (newest last; the table is capped to keep the issue body under " \
"GitHub's limit)." % (len(lines) - count)
return text
count = len(lines)
if budget is not None:
while count > 0 and len(assemble(count)) > budget:
count -= 1
if len(assemble(count)) > budget:
raise ValueError("the table header alone is longer than the %d characters left in the body" % budget)
return assemble(count), count
def update_body(body, rows, ever, now, limit=BODY_LIMIT, safety=SAFETY):
"""The body with the block between the markers replaced (or appended, markers included), under `limit` characters."""
body = body or ""
start = body.find(START)
end = body.find(END, start + len(START)) if start >= 0 else body.find(END)
if start >= 0 and end < 0 or start < 0 and end >= 0:
raise ValueError("the body has one of %s / %s but not the other after it; fix it by hand" % (START, END))
if start >= 0:
before, after = body[:start], body[end + len(END):]
else:
before, after = body.rstrip("\n") + ("\n\n" if body.strip() else ""), ""
wrapper = len(START) + len(END) + 4 # the newlines around the table
budget = limit - safety - len(before) - len(after) - wrapper
table, _ = render_table(rows, ever, now, budget)
return "%s%s\n%s\n%s%s" % (before, START, table, END, after)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--comments", nargs="+", required=True, metavar="FILE",
help="JSON lines or JSON of the comments of one or more issues")
parser.add_argument("--prs", required=True, metavar="FILE", help="JSON list of the open pull requests")
parser.add_argument("--update-body", metavar="FILE", help="issue body to put the table into, between the markers")
parser.add_argument("--now", help="ISO 8601 time to count ages from (default: now, UTC)")
parser.add_argument("--max-prs", type=int, default=MAX_PRS, help="pull requests listed per ID (default %(default)s)")
parser.add_argument("--out", metavar="FILE", help="write the result here instead of standard output")
args = parser.parse_args(argv)
now = parse_time(args.now) if args.now else datetime.datetime.now(datetime.timezone.utc)
comments = []
for path in args.comments:
with open(path, encoding="utf-8") as f:
comments.extend(load_json_values(f.read()))
with open(args.prs, encoding="utf-8") as f:
prs = load_json_values(f.read())
state, ever = open_claims(comments)
rows = build_rows(state, prs, now, args.max_prs)
if args.update_body:
with open(args.update_body, encoding="utf-8") as f:
result = update_body(f.read(), rows, ever, now)
else:
table, _ = render_table(rows, ever, now)
result = table + "\n"
if args.out:
with open(args.out, "w", encoding="utf-8", newline="\n") as f:
f.write(result)
else:
sys.stdout.buffer.write(result.encode("utf-8"))
print("%d comments, %d PRs: %s" % (len(comments), len(prs), counts_line(rows, ever, now)), file=sys.stderr)
return 0
if __name__ == "__main__":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(errors="replace")
sys.exit(main())