gen_project_status.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Generate docs/wiki/Project-Status.md from a saved snapshot of GitHub.
  3. The page answers "where exactly are we" from GitHub itself, never from memory.
  4. Three parts, kept apart on purpose:
  5. render(snapshot) a pure function: already-fetched JSON in, Markdown out. No
  6. network, no clock. Every test uses it with fixtures.
  7. fetch_snapshot() a thin layer over the `gh` CLI. Argument lists only, never
  8. a shell. Needs the maintainer's login; CI never runs it.
  9. main() --refresh fetches and rewrites the snapshot and the page;
  10. --check (the default gate) re-renders the committed
  11. snapshot and fails when the committed page differs, so a
  12. hand edit, a stale page or a missing time stamp all fail.
  13. Why a snapshot: CI has no maintainer token and the Projects data is private to
  14. the maintainer's login. The snapshot (docs/wiki/.status-snapshot.json) is what a
  15. refresh saw; the page is a pure function of it. The page therefore shows when
  16. the snapshot was taken, and a reader can re-run the stated commands to compare.
  17. Usage (from anywhere inside a clone):
  18. python -I scripts/gen_project_status.py --check offline; exit 1 when stale
  19. python -I scripts/gen_project_status.py re-render from the snapshot
  20. python -I scripts/gen_project_status.py --refresh fetch live data (needs gh
  21. logged in as the maintainer),
  22. then rewrite both files
  23. Exit codes: 0 ok, 1 stale or invalid page or snapshot (--check), or a fetch
  24. failure (--refresh), 2 usage.
  25. """
  26. from __future__ import annotations
  27. import argparse
  28. import datetime
  29. import json
  30. import re
  31. import subprocess
  32. import sys
  33. import time
  34. import unicodedata
  35. from pathlib import Path
  36. SNAPSHOT = Path("docs") / "wiki" / ".status-snapshot.json"
  37. PAGE = Path("docs") / "wiki" / "Project-Status.md"
  38. DEFAULT_REPO = "ChiefGyk3D/Clouds-Against-Humanity"
  39. DEFAULT_OWNER = "ChiefGyk3D"
  40. DEFAULT_PROJECT = 4
  41. SCHEMA = 1
  42. BOARD_FIELDS = ("Status", "Kind", "Area", "Epic", "Size", "Agent", "Sprint")
  43. MAINTAINER_LABEL = "needs-maintainer"
  44. DONE_STATUS = "Done"
  45. STAMP_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")
  46. STAMP_LINE_RE = re.compile(r"^\*\*Generated at:\*\* (\S+) \(UTC\)", re.MULTILINE)
  47. CLOSING_WORDS = ("close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved")
  48. REF_WORDS = ("ref", "refs", "reference", "references")
  49. KEYWORD_RE = re.compile(
  50. r"\b(" + "|".join(CLOSING_WORDS + REF_WORDS) + r")\b:?[ \t]+((?:#\d+|[\w.-]+/[\w.-]+#\d+)(?:[ \t]*(?:,|and|&)[ \t]*(?:#\d+|[\w.-]+/[\w.-]+#\d+))*)",
  51. re.IGNORECASE,
  52. )
  53. NUMBER_RE = re.compile(r"([\w.-]+/[\w.-]+)?#(\d+)")
  54. # --- parsing ------------------------------------------------------------------
  55. def pr_links(body: str, repo: str) -> dict[int, str]:
  56. """Issue numbers a PR body mentions with a keyword: {number: "closes" | "refs"}.
  57. A closing keyword wins over Refs for the same number. A reference into some
  58. other repository is ignored.
  59. """
  60. found: dict[int, str] = {}
  61. for match in KEYWORD_RE.finditer(body or ""):
  62. kind = "refs" if match.group(1).lower() in REF_WORDS else "closes"
  63. for repo_part, number in NUMBER_RE.findall(match.group(2)):
  64. if repo_part and repo_part.lower() != repo.lower():
  65. continue
  66. n = int(number)
  67. if found.get(n) != "closes":
  68. found[n] = kind
  69. return found
  70. def reduce_body(body: str, repo: str) -> str:
  71. """Keep only the linking phrases of a PR body, so the snapshot stays small."""
  72. return "\n".join(
  73. f"{m.group(1)} {m.group(2)}" for m in KEYWORD_RE.finditer(body or "")
  74. )
  75. def ci_state(rollup: list[dict] | None) -> str:
  76. """Reduce statusCheckRollup to passing, failing, pending or none."""
  77. if not rollup:
  78. return "none"
  79. state = "passing"
  80. for item in rollup:
  81. conclusion = (item.get("conclusion") or "").upper()
  82. status = (item.get("status") or "").upper()
  83. context = (item.get("state") or "").upper()
  84. if conclusion in {"FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"} or context in {"FAILURE", "ERROR"}:
  85. return "failing"
  86. if (status and status != "COMPLETED") or context in {"PENDING", "EXPECTED"}:
  87. state = "pending"
  88. return state
  89. # --- classification -----------------------------------------------------------
  90. IN_FLIGHT = "in flight"
  91. MERGED = "has merged PR"
  92. MAINTAINER = "needs the maintainer"
  93. NOT_STARTED = "not started"
  94. CATEGORIES = (IN_FLIGHT, MERGED, MAINTAINER, NOT_STARTED)
  95. def classify(snapshot: dict) -> dict:
  96. """The 2026-10-22 audit's classification, as data.
  97. Order matters and is the audit's: an open PR that mentions the issue (any
  98. keyword, Refs included) makes it IN-FLIGHT; otherwise a merged PR that
  99. mentions it makes it HAS MERGED PR (a review-for-close candidate, not
  100. proof of done); otherwise the needs-maintainer label; otherwise NOT STARTED.
  101. A PR that was closed without merging counts for nothing.
  102. """
  103. repo = snapshot["repo"]
  104. open_links: dict[int, list[tuple[int, str]]] = {}
  105. merged_links: dict[int, list[tuple[int, str]]] = {}
  106. pr_linked: dict[int, dict[int, str]] = {}
  107. for pr in snapshot["prs"]:
  108. links = pr_links(pr.get("body", ""), repo)
  109. pr_linked[pr["number"]] = links
  110. if pr["state"] == "OPEN":
  111. target = open_links
  112. elif pr["state"] == "MERGED":
  113. target = merged_links
  114. else:
  115. continue
  116. for n, kind in links.items():
  117. target.setdefault(n, []).append((pr["number"], kind))
  118. categories: dict[str, list[dict]] = {c: [] for c in CATEGORIES}
  119. for issue in snapshot["issues"]:
  120. if issue["state"] != "OPEN":
  121. continue
  122. n = issue["number"]
  123. if n in open_links:
  124. cat, prs = IN_FLIGHT, open_links[n]
  125. elif n in merged_links:
  126. cat, prs = MERGED, merged_links[n]
  127. elif MAINTAINER_LABEL in issue.get("labels", []):
  128. cat, prs = MAINTAINER, []
  129. else:
  130. cat, prs = NOT_STARTED, []
  131. categories[cat].append({"issue": issue, "prs": sorted(prs)})
  132. for items in categories.values():
  133. items.sort(key=lambda e: e["issue"]["number"])
  134. return {"categories": categories, "pr_linked": pr_linked}
  135. def board_gaps(snapshot: dict) -> dict:
  136. repo = snapshot["repo"]
  137. items = [i for i in snapshot["board"]["items"] if i.get("repo", repo).lower() == repo.lower()]
  138. on_board = {(i["type"], i["number"]): i for i in items}
  139. missing_issues = [i for i in snapshot["issues"] if ("Issue", i["number"]) not in on_board]
  140. missing_prs = [p for p in snapshot["prs"] if ("PullRequest", p["number"]) not in on_board]
  141. not_done = []
  142. for issue in snapshot["issues"]:
  143. entry = on_board.get(("Issue", issue["number"]))
  144. if issue["state"] == "CLOSED" and entry is not None:
  145. status = entry.get("fields", {}).get("Status")
  146. if status != DONE_STATUS:
  147. not_done.append((issue, status))
  148. on_board_issues = sum(1 for key in on_board if key[0] == "Issue")
  149. return {
  150. "on_board": on_board,
  151. "missing_issues": missing_issues,
  152. "missing_prs": missing_prs,
  153. "closed_not_done": not_done,
  154. "board_issue_count": on_board_issues,
  155. }
  156. # --- rendering ----------------------------------------------------------------
  157. MAX_CELL = 200
  158. PIPE_LOOKALIKE = "\u2223" # DIVIDES, looks like a pipe
  159. BACKSLASH_LOOKALIKE = "\u29f5" # REVERSE SOLIDUS OPERATOR, looks like a backslash
  160. NAME_RE = re.compile(r"^[A-Za-z0-9_.-]+$")
  161. def cell(value: object) -> str:
  162. """Render untrusted text (a title, a board value) as an inert code span.
  163. A title is typed by anyone who can open an issue or a pull request, so it
  164. must never become Markdown: no link, image, autolink, HTML or table break.
  165. Inside a code span none of those is interpreted. Control characters and
  166. backticks are removed (a backtick would end the span), whitespace is
  167. collapsed, the text is cut to MAX_CELL characters, and every pipe and
  168. backslash becomes a look-alike character (see the comment below).
  169. """
  170. text = "".join(" " if unicodedata.category(c) in ("Cc", "Zl", "Zp") else c for c in str(value))
  171. text = " ".join(text.replace("`", "").split())
  172. if len(text) > MAX_CELL:
  173. text = text[: MAX_CELL - 3] + "..."
  174. if not text:
  175. return ""
  176. # A pipe or a backslash is replaced by a look-alike, never escaped. GFM
  177. # splits a table row on `\|` before it parses inline Markdown, so any escaping
  178. # scheme that keeps a backslash or a pipe can be made to disagree with the
  179. # code span. With neither character present in the cell, nothing can.
  180. text = text.replace("|", PIPE_LOOKALIKE).replace("\\", BACKSLASH_LOOKALIKE)
  181. return "`" + text + "`"
  182. def ref(snapshot: dict, kind: str, number: int) -> str:
  183. segment = "pull" if kind == "pr" else "issues"
  184. return f"[#{number}](https://github.com/{snapshot['repo']}/{segment}/{number})"
  185. def pr_refs(snapshot: dict, prs: list[tuple[int, str]]) -> str:
  186. return ", ".join(
  187. f"{ref(snapshot, 'pr', n)} ({'refs only' if kind == 'refs' else 'closes'})"
  188. for n, kind in prs
  189. )
  190. def table(headers: list[str], rows: list[list[str]]) -> list[str]:
  191. out = ["| " + " | ".join(headers) + " |", "|" + "---|" * len(headers)]
  192. out += ["| " + " | ".join(r) + " |" for r in rows]
  193. return out + [""]
  194. def board_cell(gaps: dict, number: int, field: str) -> str:
  195. entry = gaps["on_board"].get(("Issue", number))
  196. if entry is None:
  197. return "not on board"
  198. return cell(entry.get("fields", {}).get(field) or "")
  199. def section_for(snapshot: dict, gaps: dict, title: str, blurb: str, entries: list[dict], with_prs: bool) -> list[str]:
  200. out = [f"### {title} ({len(entries)})", "", blurb, ""]
  201. if not entries:
  202. return out + ["None.", ""]
  203. headers = ["Issue", "Title", "Board status", "Size", "Sprint"] + (["Linked PRs"] if with_prs else [])
  204. rows = []
  205. for e in entries:
  206. n = e["issue"]["number"]
  207. row = [
  208. ref(snapshot, "issue", n),
  209. cell(e["issue"]["title"]),
  210. board_cell(gaps, n, "Status"),
  211. board_cell(gaps, n, "Size"),
  212. board_cell(gaps, n, "Sprint"),
  213. ]
  214. if with_prs:
  215. row.append(pr_refs(snapshot, e["prs"]))
  216. rows.append(row)
  217. return out + table(headers, rows)
  218. HEADER = """\
  219. <!-- GENERATED from docs/wiki/.status-snapshot.json by scripts/gen_project_status.py. Do not
  220. edit this page by hand: the snapshot is refreshed from the maintainer's GitHub login with
  221. `python -I scripts/gen_project_status.py --refresh`. CI fails when this page does not match
  222. the snapshot. -->
  223. # Project status: where we are
  224. > Prerequisites: [How this project is planned](How-This-Project-Is-Planned.md), because it explains the board, sprints and sizes this page counts.
  225. > Unfamiliar word or acronym? The [Glossary](Glossary.md) defines it.
  226. This page is regenerated from GitHub's own issues, pull requests and project board, not from memory. It is a reference page, not a lesson. A refresh saves a snapshot of what GitHub said at one moment, and everything below is counted and listed by code from that snapshot.
  227. """
  228. HEURISTICS = """\
  229. ## How each open issue is classified
  230. The rules are the ones the 2026-10-22 audit used, applied in this order. Only an issue that is open is classified.
  231. 1. **In flight:** an open pull request mentions the issue with `Closes`, `Fixes`, `Resolves` or `Refs` followed by `#N`.
  232. 2. **Has merged PR:** no open pull request, but a merged one mentions it the same way. This is a candidate to review for closing. **A `Refs` link is not proof the work is done**: it only says the pull request touched the issue, so each row says whether the link was a closing word or `refs only`.
  233. 3. **Needs the maintainer:** neither of the above, and the issue has the `needs-maintainer` label.
  234. 4. **Not started:** none of the above.
  235. A pull request closed without merging counts for nothing. A reference into another repository is ignored. Linking is by keyword in the pull request body; a number in a title or a branch name is not a link.\n\nTitles and other text from GitHub are shown as plain code text. Special characters in titles are shown as look-alikes: a pipe appears as \u2223 and a backslash as \u29f5, so no title can break a table.
  236. """
  237. def render(snapshot: dict) -> str:
  238. repo = snapshot["repo"]
  239. stamp = snapshot["fetched_at"]
  240. cls = classify(snapshot)
  241. cats = cls["categories"]
  242. gaps = board_gaps(snapshot)
  243. issues, prs = snapshot["issues"], snapshot["prs"]
  244. open_issues = [i for i in issues if i["state"] == "OPEN"]
  245. open_prs = [p for p in prs if p["state"] == "OPEN"]
  246. merged_prs = [p for p in prs if p["state"] == "MERGED"]
  247. board_total = snapshot["board"]["total"]
  248. hidden = len(gaps["missing_issues"])
  249. out = [HEADER.rstrip("\n"), ""]
  250. out += [f"**Generated at:** {stamp} (UTC), from `{repo}` and the maintainer's project board. This is a snapshot: GitHub may have moved since.", ""]
  251. if board_total < len(issues) or hidden:
  252. out += [
  253. f"> **Board data may lag.** The board holds {board_total} items and the repository has {len(issues)} issues, so {hidden} issues are not visible on the board. GitHub Projects had an incident on 2026-10-22 that delayed newly added items; the board lists below can undercount until they appear.",
  254. "",
  255. ]
  256. out += ["## The counts", ""]
  257. out += table(
  258. ["What", "Count"],
  259. [
  260. ["Issues, all states", str(len(issues))],
  261. ["Open issues", str(len(open_issues))],
  262. ["Open issues in flight", str(len(cats[IN_FLIGHT]))],
  263. ["Open issues with a merged PR, to review for close", str(len(cats[MERGED]))],
  264. ["Open issues that need the maintainer", str(len(cats[MAINTAINER]))],
  265. ["Open issues not started", str(len(cats[NOT_STARTED]))],
  266. ["Open pull requests", str(len(open_prs))],
  267. ["Merged pull requests", str(len(merged_prs))],
  268. ["Items on the board (all repositories)", str(board_total)],
  269. ["Issues not visible on the board", str(hidden)],
  270. ["Pull requests not visible on the board", str(len(gaps["missing_prs"]))],
  271. ["Closed issues not Done on the board", str(len(gaps["closed_not_done"]))],
  272. ],
  273. )
  274. out += [HEURISTICS.rstrip("\n"), ""]
  275. out += ["## Open issues by state", ""]
  276. out += section_for(snapshot, gaps, "In flight", "An open pull request mentions each of these.", cats[IN_FLIGHT], True)
  277. out += section_for(snapshot, gaps, "Has merged PR: review for close", "A merged pull request mentions each of these and the issue is still open. Check the work against the issue before closing; a `refs only` link is not proof of done.", cats[MERGED], True)
  278. out += section_for(snapshot, gaps, "Needs the maintainer", "Labeled `needs-maintainer`, with no pull request mentioning it.", cats[MAINTAINER], False)
  279. out += section_for(snapshot, gaps, "Not started", "Open, no pull request mentions it, no maintainer label.", cats[NOT_STARTED], False)
  280. out += [f"## Open pull requests ({len(open_prs)})", ""]
  281. if open_prs:
  282. rows = []
  283. for p in sorted(open_prs, key=lambda p: p["number"]):
  284. links = cls["pr_linked"][p["number"]]
  285. linked = ", ".join(f"{ref(snapshot, 'issue', n)} ({'refs only' if k == 'refs' else 'closes'})" for n, k in sorted(links.items())) or "none"
  286. rows.append([
  287. ref(snapshot, "pr", p["number"]),
  288. cell(p["title"]),
  289. "draft" if p.get("isDraft") else "ready",
  290. cell(p.get("ci", "none")),
  291. cell((p.get("reviewDecision") or "none").lower().replace("_", " ")),
  292. linked,
  293. ])
  294. out += table(["Pull request", "Title", "Draft", "CI", "Review", "Linked issues"], rows)
  295. else:
  296. out += ["None.", ""]
  297. out += ["## Board gaps", "", "These come from the project board's items, read through GitHub's GraphQL API. See the lag note at the top when the numbers look low.", ""]
  298. out += [f"### Issues missing from the board ({hidden})", ""]
  299. if gaps["missing_issues"]:
  300. out += table(["Issue", "State", "Title"], [[ref(snapshot, "issue", i["number"]), i["state"].lower(), cell(i["title"])] for i in gaps["missing_issues"]])
  301. else:
  302. out += ["None.", ""]
  303. out += [f"### Pull requests missing from the board ({len(gaps['missing_prs'])})", ""]
  304. if gaps["missing_prs"]:
  305. out += table(["Pull request", "State", "Title"], [[ref(snapshot, "pr", p["number"]), p["state"].lower(), cell(p["title"])] for p in gaps["missing_prs"]])
  306. else:
  307. out += ["None.", ""]
  308. out += [f"### Closed issues not Done on the board ({len(gaps['closed_not_done'])})", ""]
  309. if gaps["closed_not_done"]:
  310. out += table(["Issue", "Board status", "Title"], [[ref(snapshot, "issue", i["number"]), cell(s or "no status"), cell(i["title"])] for i, s in gaps["closed_not_done"]])
  311. else:
  312. out += ["None.", ""]
  313. unlinked = [p for p in prs if p["state"] in ("OPEN", "MERGED") and not cls["pr_linked"][p["number"]]]
  314. out += [f"## Pull requests with no linked issue ({len(unlinked)})", "", "Open or merged pull requests whose body has no `Closes`, `Fixes`, `Resolves` or `Refs` followed by an issue number.", ""]
  315. if unlinked:
  316. out += table(["Pull request", "State", "Title"], [[ref(snapshot, "pr", p["number"]), p["state"].lower(), cell(p["title"])] for p in sorted(unlinked, key=lambda p: p["number"])])
  317. else:
  318. out += ["None.", ""]
  319. owner, number = snapshot["project"]["owner"], snapshot["project"]["number"]
  320. out += [
  321. "## Reproduce every number",
  322. "",
  323. f"Run these from the maintainer's GitHub login (the board is private to it). `{repo}` is the repository and `{owner}` / `{number}` the owner and number of the project.",
  324. "",
  325. "```bash",
  326. f"gh issue list --repo {repo} --state all --limit 5000 --json number,title,state,labels,createdAt,closedAt,stateReason",
  327. f"gh pr list --repo {repo} --state all --limit 5000 --json number,title,state,isDraft,mergedAt,createdAt,body,headRefName",
  328. f"gh pr list --repo {repo} --state open --limit 500 --json number,statusCheckRollup,reviewDecision",
  329. f"gh project item-list {number} --owner {owner} --limit 5000 --format json",
  330. "python -I scripts/gen_project_status.py --refresh # does all of the above and rewrites this page",
  331. "```",
  332. "",
  333. "The classification above is applied to that data by `scripts/gen_project_status.py`. CI re-renders the committed snapshot, `docs/wiki/.status-snapshot.json`, and fails when this page does not match it or has no generated-at time; it does not call GitHub. The page is only as current as the last refresh, which the maintainer runs from a login: by hand, from a scheduled local job, or from a hook in the Scrum Around and Find Out (SAFO) audit.",
  334. "",
  335. "Next: [Roadmap](Roadmap.md), which says what is built and what is only planned; this page says what the work is doing right now. For how attention and work have moved week by week, see [Repository growth](Repository-Growth.md).",
  336. ]
  337. return "\n".join(out).rstrip("\n") + "\n"
  338. # --- snapshot validation ------------------------------------------------------
  339. def validate_snapshot(snap: object) -> list[str]:
  340. problems: list[str] = []
  341. if not isinstance(snap, dict):
  342. return ["snapshot is not a JSON object"]
  343. if snap.get("schema") != SCHEMA:
  344. problems.append(f"schema is not {SCHEMA}")
  345. for key in ("repo", "fetched_at"):
  346. if not isinstance(snap.get(key), str):
  347. problems.append(f"{key!r} missing")
  348. repo = snap.get("repo")
  349. if isinstance(repo, str) and not (repo.count("/") == 1 and all(NAME_RE.match(x) for x in repo.split("/"))):
  350. problems.append("repo is not owner/name")
  351. if isinstance(snap.get("fetched_at"), str) and not STAMP_RE.match(snap["fetched_at"]):
  352. problems.append("fetched_at is not YYYY-MM-DDTHH:MM:SSZ")
  353. project = snap.get("project")
  354. if not (isinstance(project, dict) and isinstance(project.get("owner"), str) and NAME_RE.match(project["owner"]) and isinstance(project.get("number"), int)):
  355. problems.append("project owner/number missing")
  356. for key in ("issues", "prs"):
  357. if not isinstance(snap.get(key), list):
  358. problems.append(f"{key!r} is not a list")
  359. continue
  360. for item in snap[key]:
  361. if not (isinstance(item, dict) and isinstance(item.get("number"), int) and isinstance(item.get("title"), str) and item.get("state") in {"OPEN", "CLOSED", "MERGED"}):
  362. problems.append(f"bad entry in {key!r}")
  363. break
  364. board = snap.get("board")
  365. if not (isinstance(board, dict) and isinstance(board.get("total"), int) and isinstance(board.get("items"), list)):
  366. problems.append("board total/items missing")
  367. return problems
  368. # --- fetch layer (maintainer login only) -------------------------------------
  369. GRAPHQL = """
  370. query($owner: String!, $number: Int!, $after: String) {
  371. user(login: $owner) {
  372. projectV2(number: $number) {
  373. items(first: 100, after: $after) {
  374. totalCount
  375. pageInfo { hasNextPage endCursor }
  376. nodes {
  377. content {
  378. __typename
  379. ... on Issue { number repository { nameWithOwner } }
  380. ... on PullRequest { number repository { nameWithOwner } }
  381. }
  382. fieldValues(first: 30) {
  383. nodes {
  384. __typename
  385. ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } }
  386. ... on ProjectV2ItemFieldIterationValue { title field { ... on ProjectV2FieldCommon { name } } }
  387. ... on ProjectV2ItemFieldTextValue { text field { ... on ProjectV2FieldCommon { name } } }
  388. ... on ProjectV2ItemFieldNumberValue { number field { ... on ProjectV2FieldCommon { name } } }
  389. }
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }
  396. """
  397. def run_gh(args: list[str]) -> str:
  398. """Run gh with an argument list. Never a shell."""
  399. result = None
  400. for attempt in range(3):
  401. result = subprocess.run(
  402. ["gh", *args], capture_output=True, text=True, check=False, timeout=300
  403. )
  404. # Retry only a gateway error; every other failure is final.
  405. if result.returncode == 0 or "HTTP 50" not in result.stderr:
  406. break
  407. time.sleep(2 * (attempt + 1))
  408. if result.returncode != 0:
  409. raise RuntimeError(f"gh {' '.join(args[:3])} failed: {result.stderr.strip()[:300]}")
  410. return result.stdout
  411. def parse_board_nodes(nodes: list[dict]) -> list[dict]:
  412. items = []
  413. for node in nodes:
  414. content = node.get("content") or {}
  415. if content.get("__typename") not in ("Issue", "PullRequest"):
  416. continue
  417. fields: dict[str, str] = {}
  418. for fv in (node.get("fieldValues") or {}).get("nodes", []):
  419. name = (fv.get("field") or {}).get("name")
  420. if name not in BOARD_FIELDS:
  421. continue
  422. value = fv.get("name", fv.get("title", fv.get("text", fv.get("number"))))
  423. if value is not None:
  424. fields[name] = str(value)
  425. items.append(
  426. {
  427. "type": content["__typename"],
  428. "number": content["number"],
  429. "repo": content["repository"]["nameWithOwner"],
  430. "fields": fields,
  431. }
  432. )
  433. return items
  434. def fetch_board(owner: str, number: int) -> dict:
  435. items: list[dict] = []
  436. total = 0
  437. after = ""
  438. while True:
  439. args = ["api", "graphql", "-f", f"query={GRAPHQL}", "-f", f"owner={owner}", "-F", f"number={number}"]
  440. if after:
  441. args += ["-f", f"after={after}"]
  442. data = json.loads(run_gh(args))["data"]["user"]["projectV2"]["items"]
  443. total = data["totalCount"]
  444. items += parse_board_nodes(data["nodes"])
  445. if not data["pageInfo"]["hasNextPage"]:
  446. break
  447. after = data["pageInfo"]["endCursor"]
  448. items.sort(key=lambda i: (i["type"], i["number"]))
  449. return {"total": total, "items": items}
  450. def fetch_snapshot(repo: str, owner: str, project: int) -> dict:
  451. issues_raw = json.loads(run_gh(["issue", "list", "--repo", repo, "--state", "all", "--limit", "5000", "--json", "number,title,state,labels,createdAt,closedAt,stateReason"]))
  452. prs_raw = json.loads(run_gh(["pr", "list", "--repo", repo, "--state", "all", "--limit", "5000", "--json", "number,title,state,isDraft,mergedAt,createdAt,body,headRefName"]))
  453. # CI and review state are fetched for open PRs only: asking for them on
  454. # every PR in the history times out on GitHub's side.
  455. open_raw = json.loads(run_gh(["pr", "list", "--repo", repo, "--state", "open", "--limit", "500", "--json", "number,statusCheckRollup,reviewDecision"]))
  456. open_by_number = {p["number"]: p for p in open_raw}
  457. issues = [
  458. {
  459. "number": i["number"],
  460. "title": i["title"],
  461. "state": i["state"],
  462. "labels": sorted(label["name"] for label in i.get("labels", [])),
  463. "createdAt": i.get("createdAt"),
  464. "closedAt": i.get("closedAt"),
  465. "stateReason": i.get("stateReason"),
  466. }
  467. for i in sorted(issues_raw, key=lambda i: i["number"])
  468. ]
  469. prs = [
  470. {
  471. "number": p["number"],
  472. "title": p["title"],
  473. "state": p["state"],
  474. "isDraft": bool(p.get("isDraft")),
  475. "createdAt": p.get("createdAt"),
  476. "mergedAt": p.get("mergedAt"),
  477. "headRefName": p.get("headRefName"),
  478. "body": reduce_body(p.get("body") or "", repo),
  479. "ci": ci_state(open_by_number.get(p["number"], {}).get("statusCheckRollup")),
  480. "reviewDecision": open_by_number.get(p["number"], {}).get("reviewDecision") or "",
  481. }
  482. for p in sorted(prs_raw, key=lambda p: p["number"])
  483. ]
  484. return {
  485. "schema": SCHEMA,
  486. "repo": repo,
  487. "project": {"owner": owner, "number": project},
  488. "fetched_at": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
  489. "issues": issues,
  490. "prs": prs,
  491. "board": fetch_board(owner, project),
  492. }
  493. # --- check and CLI ------------------------------------------------------------
  494. def check_page(root: Path) -> list[str]:
  495. """Problems with the committed page against the committed snapshot. Offline."""
  496. snap_path, page_path = root / SNAPSHOT, root / PAGE
  497. try:
  498. snap = json.loads(snap_path.read_text(encoding="utf-8"))
  499. except (OSError, ValueError) as exc:
  500. return [f"cannot read {SNAPSHOT}: {exc}"]
  501. problems = validate_snapshot(snap)
  502. if problems:
  503. return [f"{SNAPSHOT}: {p}" for p in problems]
  504. if not page_path.is_file():
  505. return [f"{PAGE} is missing"]
  506. have = page_path.read_text(encoding="utf-8")
  507. stamp = STAMP_LINE_RE.search(have)
  508. if stamp is None or not STAMP_RE.match(stamp.group(1)):
  509. return [f"{PAGE} has no valid 'Generated at' time stamp"]
  510. if stamp.group(1) != snap["fetched_at"]:
  511. return [f"{PAGE} says it was generated at {stamp.group(1)} but the snapshot was taken at {snap['fetched_at']}"]
  512. if have != render(snap):
  513. return [f"{PAGE} does not match {SNAPSHOT} (edited by hand, or the renderer changed)"]
  514. return []
  515. def main(argv: list[str] | None = None) -> int:
  516. parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
  517. mode = parser.add_mutually_exclusive_group()
  518. mode.add_argument("--check", action="store_true", help="offline: fail when the page is stale")
  519. mode.add_argument("--refresh", action="store_true", help="fetch live data with gh (maintainer login) and rewrite the snapshot and page")
  520. parser.add_argument("--root", default=str(Path(__file__).resolve().parent.parent), help="repository root")
  521. parser.add_argument("--repo", default=DEFAULT_REPO, help="owner/name (--refresh)")
  522. parser.add_argument("--owner", default=DEFAULT_OWNER, help="project owner login (--refresh)")
  523. parser.add_argument("--project", type=int, default=DEFAULT_PROJECT, help="project number (--refresh)")
  524. args = parser.parse_args(argv)
  525. root = Path(args.root)
  526. if args.check:
  527. problems = check_page(root)
  528. if problems:
  529. for p in problems:
  530. print(f"gen_project_status: {p}", file=sys.stderr)
  531. print("gen_project_status: refresh with: python -I scripts/gen_project_status.py --refresh (maintainer login), or re-render with: python -I scripts/gen_project_status.py", file=sys.stderr)
  532. return 1
  533. print(f"gen_project_status: {PAGE} matches {SNAPSHOT}")
  534. return 0
  535. if args.refresh:
  536. try:
  537. snap = fetch_snapshot(args.repo, args.owner, args.project)
  538. except (RuntimeError, OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
  539. print(f"gen_project_status: refresh failed: {exc}", file=sys.stderr)
  540. return 1
  541. (root / SNAPSHOT).write_text(json.dumps(snap, indent=1, sort_keys=True) + "\n", encoding="utf-8")
  542. else:
  543. try:
  544. snap = json.loads((root / SNAPSHOT).read_text(encoding="utf-8"))
  545. except (OSError, ValueError) as exc:
  546. print(f"gen_project_status: cannot read {SNAPSHOT}: {exc}", file=sys.stderr)
  547. return 1
  548. problems = validate_snapshot(snap)
  549. if problems:
  550. print(f"gen_project_status: {SNAPSHOT}: {'; '.join(problems)}", file=sys.stderr)
  551. return 1
  552. (root / PAGE).write_text(render(snap), encoding="utf-8")
  553. print(f"gen_project_status: wrote {PAGE}")
  554. return 0
  555. if __name__ == "__main__":
  556. sys.exit(main())