mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:08:38 +00:00
252 lines
12 KiB
Python
252 lines
12 KiB
Python
"""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())
|