Coverage for src/keel/blockers.py: 100%
303 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-20 19:17 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-20 19:17 +0000
1"""Stated-blocker detection for open pull requests (#1512).
3A draft that says "do not merge before #3177" stays open long after #3177 closed, and
4nothing surfaced it. This module reads the *stated* blockers out of PR bodies and asks
5GitHub whether each has cleared.
7* :func:`parse_blockers` and :func:`scan_blockers` are pure: PR body text in, blocker
8 references and completeness out. It reuses :data:`keel.intake.BLOCKED_PHRASE_RE`,
9 the phrase set issue intake already uses.
10* :func:`resolve_blocker` and :func:`stale_blockers` are the thin, fail-soft ``gh`` I/O.
11 A read that fails is ``unknown``. ``all_cleared`` is a best-effort hint for an operator
12 to inspect, never a certificate: an operator must read the PR before acting.
13"""
15from __future__ import annotations
17import json
18import re
19from dataclasses import dataclass
20from typing import Any
22from .intake import BLOCKED_PHRASE_RE, NON_BLOCKING_DEPENDENCY_RE
23from .runner import run_argv
25ISSUE = "issue"
26TAG = "tag"
28CLEARED = "cleared"
29PENDING = "pending"
30#: Closed without the work landing: a PR closed unmerged, an issue closed as not planned or
31#: a duplicate. The blocker is gone but the thing it waited for never arrived, so it is
32#: reported and never counted as cleared.
33ABANDONED = "abandoned"
34UNKNOWN = "unknown"
36_ITEM = r"(?:(?:pull request|pr|issue)s?\s*)?#\d+"
37#: Between two items of one list: ``,`` ``, and`` ``, or`` ``and`` ``or`` ``&`` ``/`` ``+``,
38#: or a markdown bullet on the very next line (a blank line ends the list).
39_SEP = r"(?:\s*(?:,\s*(?:(?:and|or)\b\s*)?|&|/|\+|(?:and|or)\b)\s*|[ \t]*\n[ \t]*[-*+][ \t]+)"
40_REF_LIST = rf"(?P<refs>{_ITEM}(?:{_SEP}{_ITEM})*)"
41# --- Recognised phrases and reference zones (#1512) -----------------------------------
42# The parser reads the recognised phrases and marks a PR incomplete when it sees a
43# reference it could not read in a phrase's zone.
44#: The strict grammar for what may follow a blocked phrase: ``blocked by #N``,
45#: ``depends on: PR #N``, ``waiting on #1, #2, and #3``, or ``Depends on:`` and a bullet per
46#: ref. ``owner/repo#N`` does not match (the target must start with ``#N``, optionally after
47#: ``PR``/``issue``), so it is not resolved against this repository.
48_AFTER_BLOCKED_RE = re.compile(
49 rf"[ \t]*:?[ \t]*(?:\n[ \t]*)?(?:[-*+][ \t]+)?{_REF_LIST}", re.IGNORECASE
50)
51#: Phrases that are also ordinary nouns: "Upgrade dependency #123" quotes an upstream issue
52#: number, so they only count when written as a label ("Dependency: #123").
53_NOUN_PHRASES = frozenset({"dependency", "needs dependency"})
54#: Reference-like tokens in a blocker zone: this-repo `#N`, foreign `owner/repo#N`,
55#: URLs, issue/pull paths, and tag-like targets (`v1`, `v1.2.0`, `1.2.0`).
56_REFLIKE_RE = re.compile(
57 r"https?://\S+"
58 r"|(?<![\w.-])[\w.-]++/[\w.-]++#\d+"
59 r"|/(?:issues|pull)/\d+"
60 r"|#\d+"
61 r"|\bv\d\S*|\b\d{1,3}\.\d+\.\d\S*",
62 re.IGNORECASE,
63)
64_DO_NOT_MERGE = (
65 r"(?:do not|don't|dont|must not|should not|shouldn't|cannot|can't)\s+"
66 r"merge\s+(?:(?:this|the)(?:\s+(?:pr|pull request))?\s+|it\s+)?"
67 r"(?:before|until(?:\s+after)?|prior to)"
68)
69_BEFORE_PHRASE_RE = re.compile(rf"(?<![\w/]){_DO_NOT_MERGE}", re.IGNORECASE)
70#: What may follow ``do not merge before``: ``#N`` (or ``PR #N``), a ``v``-prefixed tag
71#: (``v2``, ``v1.2.0``) or a three-part dotted version (``1.2.0``). A bare word ("before
72#: release") or a time/count ("before 5pm", "before 3 reviewers") is not a reference.
73#: A tag target must end at whitespace or sentence punctuation (``[.,;:!?)\]}]``) so a
74#: foreign ``v2/sdk#12`` or unsupported ``v2.0.0@rc1`` continuation is not read as a tag
75#: prefix.
76_AFTER_BEFORE_RE = re.compile(
77 r"\s+(?:the\s+)?(?:"
78 r"(?P<issue>(?:(?:pull request|pr|issue)\s*)?#\d+)"
79 r"|(?P<tag>(?:v\d|\d{1,3}\.\d+\.\d)[\w.+\-/]*+)(?=[.,;:!?)\]}]*+(?!\S)))",
80 re.IGNORECASE,
81)
82_NEGATION_RE = re.compile(
83 r"(?:\bnot|\bno longer|\bnever|n't|\bnothing|\bpreviously|\bformerly|\bwas|\bwere)[ \t]+"
84 r"(?:(?:currently|really|yet)[ \t]+)?\Z",
85 re.IGNORECASE,
86)
87#: A terminated fence only: a stray unterminated opener must not swallow (hide) the rest of
88#: the body, an opener line may not carry a backtick after its opening run (so a one-line
89#: `````foo````` inline code span at line start is not read as a fence opener), and an opener
90#: must only close at a valid closing-fence line (the fence characters and optional trailing
91#: spaces/tabs).
92_FENCE_RE = re.compile(
93 r"^[ \t]*+([`~])(\1{2,}+)[^\n`]*\n(?:(?!^[ \t]*\1\2\1*[ \t]*$)[^\n]*\n)*?^[ \t]*\1\2\1*[ \t]*$",
94 re.MULTILINE,
95)
96_HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
97_DETAILS_TAG_RE = re.compile(r"<\s*(/)?\s*details(?=[\s>])[^>]*>", re.IGNORECASE)
98_INLINE_CODE_RE = re.compile(
99 r"(?<!`)(`+)(?!`)((?:(?!\n[ \t]*\n).)*?)(?<!`)\1(?!`)",
100 re.DOTALL,
101)
102#: ``[#12](https://...)`` reads as its link text; a link whose text carries no ``#N`` keeps
103#: its URL, so an issue URL behind prose stays visible to the "could not read" check.
104_LINK_RE = re.compile(r"\[([^\]\n]*)\]\(([^)\n]*)\)")
105#: Paired emphasis around a phrase or target (``**Blocked by:**``, ``_#12_``, ``__v1__rc__``)
106#: is unwrapped without stripping internal ``__`` inside a tag name like ``v1__rc``.
107_BOLD_RE = re.compile(r"\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<!\w)__(?=\S)(.+?)(?<=\S)__(?!\w)")
108_ITALIC_REF_RE = re.compile(r"([*_])(#\d+)\1")
111@dataclass(frozen=True)
112class Blocker:
113 """One stated blocker: an issue/PR number (``kind='issue'``) or a tag name."""
115 kind: str
116 ref: str # "3177" for an issue/PR, "v1.2.0" for a tag
118 def to_dict(self) -> dict[str, str]:
119 return {"kind": self.kind, "ref": self.ref}
122def _is_blocked_phrase(text: str, m: re.Match[str]) -> bool:
123 return m.group(1).lower() not in _NOUN_PHRASES or text[m.end() :].lstrip(" \t").startswith(":")
126def _unwrap_inline(match: re.Match[str]) -> str:
127 """Keep backticked content (a tag is routinely written ``v1.2.0``) unless the span
128 is itself a blocker phrase, which is documentation about the phrase, not a claim."""
129 inner = match.groups()[-1].replace("\n", " ")
130 if any(
131 _is_blocked_phrase(inner, m) for m in BLOCKED_PHRASE_RE.finditer(inner)
132 ) or _BEFORE_PHRASE_RE.search(inner):
133 return ""
134 return inner
137def _own_link(label: str, url: str, repo: str | None) -> bool:
138 """True when ``url`` points at this repository's own issue/PR *and* is the one ``label`` names.
140 A root-relative ``/issues/N`` or ``/pull/N`` (or a bare ``#N``) is this repository's. A
141 protocol-relative ``//host/...`` or ``../other/...`` path is not, and an absolute URL
142 counts only when ``repo`` (``owner/name``) is known and matches. A link whose URL names a
143 different number than its label (``[#12](.../issues/99)``) is not read as ``#12``.
144 """
145 if url.startswith("//"):
146 return False
147 named = re.search(r"(?:(?:issues|pull)/|^#)(\d+)", url)
148 labelled = re.search(r"#(\d+)", label)
149 if named and labelled and named.group(1) != labelled.group(1):
150 return False
151 if not re.match(r"[a-z][a-z0-9+.-]*:", url, re.IGNORECASE):
152 return bool(re.match(r"(?:/(?:issues|pull)/\d+|#\d+)$", url))
153 if repo is None:
154 return False
155 return bool(
156 re.match(
157 rf"https?://(?:www\.)?github\.com/{re.escape(repo)}/(?:issues|pull)/\d+(?:[/?#]|$)",
158 url,
159 re.IGNORECASE,
160 )
161 )
164def _unwrap_link(match: re.Match[str], repo: str | None) -> str:
165 """``[#12](own-repo url)`` reads as ``#12``. A ``#N`` label over any other URL is a
166 reference into another repository: it is renamed ``external#N`` (so it is not read as
167 this repository's ``#N``, yet still counts as an unread reference). Prose keeps its URL."""
168 label, url = match.groups()
169 if "#" not in label:
170 return f"{label} {url}"
171 return label if _own_link(label, url, repo) else label.replace("#", "external#")
174_ALERT_RE = re.compile(
175 r"^[ \t]*>[ \t]*\[!(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]",
176 re.IGNORECASE,
177)
180def _strip_blockquotes(text: str) -> str:
181 """Drop blockquote lines (first non-space character is '>'), except GitHub alert blocks
182 (> [!NOTE], > [!WARNING], > [!IMPORTANT], > [!CAUTION], > [!TIP] and lines quoted under
183 them) which are the author's own text."""
184 out: list[str] = []
185 in_alert = False
186 for line in text.split("\n"):
187 stripped = line.lstrip(" \t")
188 if stripped.startswith(">"):
189 if _ALERT_RE.match(line):
190 in_alert = True
191 if in_alert:
192 out.append(re.sub(r"^[ \t]*>[ \t]?", "", line))
193 else:
194 in_alert = False
195 out.append(line)
196 return "\n".join(out)
199def _strip_details(text: str) -> str:
200 """Drop everything between <details> and </details> (case-insensitive, may span lines,
201 may be nested; an unterminated <details> drops to the end of the body)."""
202 out: list[str] = []
203 depth = 0
204 last_end = 0
205 for m in _DETAILS_TAG_RE.finditer(text):
206 if not m.group(1):
207 if depth == 0:
208 out.append(text[last_end : m.start()])
209 depth += 1
210 elif depth > 0:
211 depth -= 1
212 if depth == 0:
213 last_end = m.end()
214 if depth == 0:
215 out.append(text[last_end:])
216 return "".join(out)
219def _prose(body: str, repo: str | None) -> str:
220 text = body.replace("\r\n", "\n").replace("\r", "\n").replace("\u2019", "'")
221 text = _HTML_COMMENT_RE.sub(" ", text)
222 text = _FENCE_RE.sub(" ", text)
223 text = _strip_blockquotes(text)
224 text = _FENCE_RE.sub(" ", text)
225 inlines: list[str] = []
227 def _stash_inline(m: re.Match[str]) -> str:
228 inlines.append(_unwrap_inline(m))
229 return f"\x00{len(inlines) - 1}\x00"
231 text = _INLINE_CODE_RE.sub(_stash_inline, text)
232 text = _strip_details(text)
233 text = _LINK_RE.sub(lambda m: _unwrap_link(m, repo), text)
234 text = _BOLD_RE.sub(lambda m: m.group(1) or m.group(2), text)
235 text = _ITALIC_REF_RE.sub(r"\2", text)
236 if inlines:
237 text = re.sub(r"\x00(\d+)\x00", lambda m: inlines[int(m.group(1))], text)
238 return text
241def _zone(text: str, pos: int) -> str:
242 """The span a blocker phrase governs: the rest of its line (or the next line when the
243 phrase ends its line), plus any bullet lines directly under that."""
244 rest = text[pos:]
245 nl = rest.find("\n")
246 if nl == -1:
247 return rest
248 head = rest[:nl]
249 lines = [head]
250 after = rest[nl + 1 :].split("\n")
251 if not head.strip(" \t:"):
252 if not after[0].strip(" \t"):
253 return head
254 lines.append(after.pop(0))
255 for line in after:
256 if re.match(r"^[ \t]*[-*+]", line):
257 lines.append(line)
258 else:
259 break
260 return "\n".join(lines)
263def _negated(text: str, start: int) -> bool:
264 line_start = text.rfind("\n", 0, start) + 1
265 return bool(_NEGATION_RE.search(text[line_start:start]))
268def scan_blockers(body: str | None, repo: str | None = None) -> tuple[tuple[Blocker, ...], bool]:
269 """``(blockers, incomplete)`` stated in ``body``.
271 The parser reads the recognised phrases and marks a PR incomplete when it sees a
272 reference it could not read in a phrase's zone. ``all_cleared`` is a best-effort hint
273 for an operator to look at, never a certificate: an operator must read the PR before
274 acting. ``repo`` (``owner/name``) lets a link to this repository's own issue read as
275 a bare ``#N``; without it every absolute link is treated as foreign.
276 """
277 text = _prose(body or "", repo)
278 matches: list[tuple[re.Match[str], str]] = []
279 for m in BLOCKED_PHRASE_RE.finditer(text):
280 if _negated(text, m.start()) or not _is_blocked_phrase(text, m):
281 continue
282 if NON_BLOCKING_DEPENDENCY_RE.match(text, m.start()):
283 continue
284 matches.append((m, "blocked"))
285 for m in _BEFORE_PHRASE_RE.finditer(text):
286 if _negated(text, m.start()):
287 continue
288 matches.append((m, "before"))
289 matches.sort(key=lambda item: item[0].start())
291 found: list[Blocker] = []
292 incomplete = False
293 for i, (m, kind) in enumerate(matches):
294 next_start = matches[i + 1][0].start() if i + 1 < len(matches) else len(text)
295 zone = _zone(text[:next_start], m.end())
296 zone_ref_spans = [
297 (rm.start(), rm.start() + len(rm.group(0).rstrip(".,;:!?)]}")))
298 for rm in _REFLIKE_RE.finditer(zone)
299 ]
300 this_found: list[Blocker] = []
301 captured_spans: list[tuple[int, int]] = []
302 if kind == "blocked":
303 ref = _AFTER_BLOCKED_RE.match(zone)
304 if ref:
305 base = ref.start("refs")
306 for rm in re.finditer(r"#(\d+)", ref.group("refs")):
307 this_found.append(Blocker(ISSUE, rm.group(1)))
308 captured_spans.append((base + rm.start(), base + rm.end()))
309 else:
310 target = _AFTER_BEFORE_RE.match(zone)
311 if target is not None:
312 if target.group("issue"):
313 num = re.sub(r"\D", "", target.group("issue"))
314 end = target.end("issue")
315 this_found.append(Blocker(ISSUE, num))
316 captured_spans.append((end - len(num) - 1, end))
317 else:
318 tag = target.group("tag").rstrip(".")
319 if not (".." in tag or tag.endswith("/")):
320 start = target.start("tag")
321 this_found.append(Blocker(TAG, tag))
322 captured_spans.append((start, start + len(tag)))
323 found.extend(this_found)
324 if captured_spans != zone_ref_spans:
325 incomplete = True
326 seen: set[Blocker] = set()
327 ordered: list[Blocker] = []
328 for b in found:
329 if b not in seen:
330 seen.add(b)
331 ordered.append(b)
332 return tuple(ordered), incomplete
335def parse_blockers(body: str | None) -> tuple[Blocker, ...]:
336 """Blockers stated in ``body``, de-duplicated: phrase forms first, then ``before`` forms.
338 Code fences, inline code spans that quote a blocker phrase, HTML comments (a PR
339 template's placeholder), standard blockquotes (author alerts like ``> [!NOTE]`` are
340 scanned), and HTML ``<details>`` blocks (bot-pasted release notes) are ignored as
341 non-claims. Negated phrases ("not blocked by #5") are skipped; "unblocked by #5"
342 does not match because the phrase needs a word boundary.
343 """
344 return scan_blockers(body)[0]
347#: One line: ``<state> <state_reason|-> <issue|unmerged|<merged_at>>``. The last field is
348#: how a PR is told from an issue, and whether it merged (``merged_at`` is null if not).
349# GitHub's issues endpoint includes ``pull_request.merged_at`` on PR items (timestamp when
350# merged, null when open or closed unmerged).
351_ISSUE_JQ = (
352 '.state + " " + (.state_reason // "-") + " " + '
353 '(if .pull_request then (.pull_request.merged_at // "unmerged") else "issue" end)'
354)
355_MERGED_AT_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})")
358def _kw(_run):
359 return {"_run": _run} if _run is not None else {}
362def _why(result) -> str:
363 """Why a ``gh`` call produced nothing usable: its first line of complaint, else its exit."""
364 for line in (result.stderr or result.output or "").splitlines():
365 if line.strip():
366 return line.strip()[:120]
367 return f"gh exited {result.code}"
370def resolve_detail(
371 blocker: Blocker, *, cwd: str | None = None, _run=None
372) -> tuple[str, str | None]:
373 """``(state, reason)`` for one blocker; ``reason`` is set only when the state is unknown.
375 An open issue or PR is pending. A closed one is cleared only when the work landed: a PR
376 that was merged, an issue closed as ``completed`` (or with no reason, as old issues
377 are). A PR closed unmerged, or an issue closed ``not_planned`` / as a duplicate, is
378 ``abandoned``. A tag is cleared once ``git/ref/tags/<tag>`` exists and pending only on
379 an HTTP 404 while the repository itself answers. Anything else — no ``gh``, offline, no
380 auth, rate limit, odd output — is ``unknown``: an operator must inspect before acting.
381 """
382 if blocker.kind == ISSUE:
383 argv = ["gh", "api", f"repos/{{owner}}/{{repo}}/issues/{blocker.ref}", "--jq", _ISSUE_JQ]
384 result = run_argv(argv, cwd=cwd, **_kw(_run))
385 if not result.ok:
386 return UNKNOWN, _why(result)
387 parts = result.stdout.split()
388 if (
389 len(parts) != 3
390 or parts[0] not in ("open", "closed")
391 or (parts[2] not in ("issue", "unmerged") and not _MERGED_AT_RE.fullmatch(parts[2]))
392 ):
393 return UNKNOWN, f"unexpected answer: {result.stdout.strip()[:60]!r}"
394 state, reason, merged = parts
395 if state == "open":
396 return PENDING, None
397 if merged == "issue":
398 return (CLEARED if reason in ("completed", "-") else ABANDONED), None
399 return (ABANDONED if merged == "unmerged" else CLEARED), None
400 argv = ["gh", "api", f"repos/{{owner}}/{{repo}}/git/ref/tags/{blocker.ref}", "--jq", ".ref"]
401 result = run_argv(argv, cwd=cwd, **_kw(_run))
402 if result.ok:
403 ans = result.stdout.strip()
404 if ans == f"refs/tags/{blocker.ref}":
405 return CLEARED, None
406 if not ans:
407 return UNKNOWN, "empty answer for the tag lookup"
408 return UNKNOWN, f"unexpected answer: {ans[:60]!r}"
409 if "HTTP 404" not in result.stderr:
410 return UNKNOWN, _why(result)
411 # A 404 also answers a repository the caller cannot see (private, no auth, wrong
412 # directory): only a repository that does answer makes it "the tag is not there yet".
413 repo = run_argv(["gh", "api", "repos/{owner}/{repo}", "--jq", ".id"], cwd=cwd, **_kw(_run))
414 if repo.ok and repo.stdout.strip():
415 return PENDING, None
416 return UNKNOWN, "tag lookup was a 404 and the repository could not be read"
419def resolve_blocker(blocker: Blocker, *, cwd: str | None = None, _run=None) -> str:
420 """``cleared`` / ``pending`` / ``abandoned`` / ``unknown`` for one blocker. Read-only."""
421 return resolve_detail(blocker, cwd=cwd, _run=_run)[0]
424def _open_prs(limit: int, cwd: str | None, _run) -> list[dict[str, Any]] | None:
425 argv = [
426 "gh",
427 "pr",
428 "list",
429 "--state",
430 "open",
431 "--limit",
432 str(limit + 1), # one more than asked, so "truncated" is exact
433 "--json",
434 "number,title,url,isDraft,body",
435 ]
436 result = run_argv(argv, cwd=cwd, **_kw(_run))
437 if not result.ok:
438 return None
439 try:
440 rows = json.loads(result.stdout or "[]")
441 except ValueError:
442 return None
443 return rows if isinstance(rows, list) else None
446_SLUG_RE = re.compile(r"[\w.-]+/[\w.-]+")
449def _repo_slug(cwd: str | None, _run) -> str | None:
450 """``owner/name`` of the checkout, or ``None`` when ``gh`` cannot say."""
451 result = run_argv(
452 ["gh", "repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"],
453 cwd=cwd,
454 **_kw(_run),
455 )
456 slug = result.stdout.strip() if result.ok else ""
457 return slug if _SLUG_RE.fullmatch(slug) else None
460def stale_blockers(*, limit: int = 200, cwd: str | None = None, _run=None) -> dict[str, Any]:
461 """Open PRs worth an operator's attention about their stated blockers.
463 Listed: a PR with a blocker that cleared or was abandoned, one whose blocker could not be
464 *checked* (``unknown``, with the reason), an incomplete PR (an unread reference was seen
465 in a blocker zone), and one whose references could not be read (``blockers`` empty,
466 ``incomplete`` true). ``ok`` is False (and ``error`` set) when the PR list itself cannot be
467 read. ``unknown_blockers`` counts the distinct blockers whose state could not be read.
468 ``all_cleared`` is a best-effort hint, never a certificate: an operator must read the PR
469 before acting. A PR is not reported against itself.
470 """
471 rows = _open_prs(limit, cwd, _run)
472 if rows is None:
473 return {
474 "ok": False,
475 "error": "could not list open pull requests",
476 "truncated": False,
477 "unknown_blockers": 0,
478 "prs": [],
479 }
480 truncated = len(rows) > limit
481 rows = rows[:limit]
482 # Only a body with an absolute link needs to know which repository is "this" one.
483 repo = (
484 _repo_slug(cwd, _run)
485 if any(isinstance(r, dict) and "](http" in str(r.get("body")).lower() for r in rows)
486 else None
487 )
488 resolved: dict[Blocker, tuple[str, str | None]] = {}
489 prs: list[dict[str, Any]] = []
490 for row in rows:
491 if not isinstance(row, dict) or type(row.get("number")) is not int:
492 continue
493 number = row["number"]
494 body = row["body"] if isinstance(row.get("body"), str) else None
495 found, incomplete = scan_blockers(body, repo)
496 stated = [b for b in found if not (b.kind == ISSUE and b.ref == str(number))]
497 if not stated and not incomplete:
498 continue
499 entries = []
500 for b in stated:
501 if b not in resolved:
502 resolved[b] = resolve_detail(b, cwd=cwd, _run=_run)
503 state, reason = resolved[b]
504 entry = {**b.to_dict(), "state": state}
505 if reason is not None:
506 entry["reason"] = reason
507 entries.append(entry)
508 # Shown, not dropped: a resolved or abandoned blocker, an unchecked one, or a PR
509 # whose references could not be read or whose blocker list may be incomplete.
510 noteworthy = {CLEARED, ABANDONED, UNKNOWN}
511 if not incomplete and not any(e["state"] in noteworthy for e in entries):
512 continue
513 prs.append(
514 {
515 "number": number,
516 "title": row.get("title") or "",
517 "url": row.get("url") or "",
518 "draft": bool(row.get("isDraft")),
519 "blockers": entries,
520 "incomplete": incomplete,
521 "all_cleared": not incomplete and all(e["state"] == CLEARED for e in entries),
522 }
523 )
524 prs.sort(key=lambda p: p["number"])
525 unknown = sum(1 for state, _ in resolved.values() if state == UNKNOWN)
526 return {
527 "ok": True,
528 "error": None,
529 "truncated": truncated,
530 "unknown_blockers": unknown,
531 "prs": prs,
532 }
535def render(report: dict[str, Any]) -> str:
536 """Human-readable form of a :func:`stale_blockers` report."""
537 if not report["ok"]:
538 return f"keel stale-blockers: {report['error']}"
539 lines = []
540 if not report["prs"]:
541 lines.append("No open PRs with a cleared, abandoned or unchecked blocker.")
542 for pr in report["prs"]:
543 states = {e["state"] for e in pr["blockers"]}
544 if pr["all_cleared"]:
545 kind = "all blockers cleared"
546 elif not pr["blockers"]:
547 kind = "blocker reference could not be read"
548 elif pr["incomplete"]:
549 kind = "blocker list may be incomplete"
550 elif states == {UNKNOWN}:
551 kind = "blocker state could not be checked"
552 elif states == {ABANDONED}:
553 kind = "blocker abandoned, none cleared"
554 elif states == {PENDING, UNKNOWN}:
555 kind = "no blocker cleared, some unchecked"
556 else:
557 kind = "some blockers cleared, abandoned or unchecked"
558 draft = " (draft)" if pr["draft"] else ""
559 lines.append(f"#{pr['number']}{draft} {pr['title']} — {kind}")
560 for e in pr["blockers"]:
561 label = f"#{e['ref']}" if e["kind"] == ISSUE else e["ref"]
562 why = f" ({e['reason']})" if e["state"] == UNKNOWN else ""
563 lines.append(f" - {label}: {e['state']}{why}")
564 if report["unknown_blockers"]:
565 lines.append(
566 f"{report['unknown_blockers']} blocker(s) could not be checked "
567 "(rate limit, token scope, network or a 5xx): the list above is incomplete, "
568 "so silence about a PR does not mean its blockers are open."
569 )
570 if report["truncated"]:
571 lines.append("Only the first --limit open PRs were read; raise --limit to read more.")
572 return "\n".join(lines)