main
1#!/usr/bin/env python3
2"""Raffi script filter for GitHub pull requests.
3
4Lists the open pull requests of a repository, or the open pull requests you
5wrote, were asked to review, are assigned to, or are involved in. When Raffi
6sets RAFFI_PREVIEW=1, it prints a preview of the pull request whose URL is in
7RAFFI_VALUE instead.
8"""
9
10import argparse
11import base64
12import json
13import os
14import re
15import subprocess
16import urllib.request
17from collections import Counter
18from datetime import UTC, datetime
19from pathlib import Path
20
21API_HOST = os.environ.get("API_HOST", "github.com")
22CACHE_PULLS = os.environ.get("CACHE_PULLS", "10m")
23ICON = "github"
24# Raffi gives the preview command 3 seconds in total.
25PREVIEW_TIMEOUT = 2.5
26PREVIEW_REFRESH_SECONDS = 20
27PREVIEW_COMMENTS = 3
28PREVIEW_FILES = 50
29# Accounts whose comments the preview skips, besides GitHub Apps.
30BOT_SUFFIXES = ("[bot]", "-bot", "-robot")
31
32CACHE_HOME = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
33AVATAR_DIR = CACHE_HOME / "raffi" / "github-avatars" / API_HOST
34AVATAR_TIMEOUT = 3
35# Raffi loads PNG and SVG icons only and GitHub avatars can be JPEG, so they
36# are embedded in an SVG, clipped to a circle.
37AVATAR_SVG = (
38 '<svg xmlns="http://www.w3.org/2000/svg" '
39 'xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 128 128">'
40 '<clipPath id="round"><circle cx="64" cy="64" r="64"/></clipPath>'
41 '<image width="128" height="128" clip-path="url(#round)" '
42 'xlink:href="data:{mime};base64,{data}"/></svg>'
43)
44
45REPO = re.compile(r"[\w.-]+/[\w.-]+")
46PR_URL = re.compile(r"https?://[^/]+/([\w.-]+)/([\w.-]+)/pull/(\d+)")
47ANSI = re.compile(r"\x1b\[[0-9;]*m")
48HTML_COMMENT = re.compile(r"<!--.*?-->", re.DOTALL)
49BLANK_LINES = re.compile(r"\n{3,}")
50
51# Markdown, rendered with the ANSI codes Raffi supports: colours, bold, underline.
52FENCE = re.compile(r"\s*(```|~~~)")
53HEADING = re.compile(r"#{1,6}\s+(.*?)[\s#]*$")
54RULE = re.compile(r"\s*([-*_])(\s*\1){2,}\s*$")
55LIST_ITEM = re.compile(r"(\s*)[-*+]\s+(?:\[([ xX])\]\s+)?(.*)")
56QUOTE = re.compile(r"\s*>\s?(.*)")
57ALERT = re.compile(r"\[!(\w+)\]$")
58TABLE_RULE = re.compile(r"\s*\|?(\s*:?-+:?\s*\|)+\s*(:?-+:?)?\s*$")
59CODE_SPAN = re.compile(r"(`+)(.+?)\1")
60HTML_TAG = re.compile(r"</?[a-zA-Z][^>]*>")
61IMAGE = re.compile(r"!\[([^\]]*)\]\([^)]*\)")
62LINK = re.compile(r"\[([^\]]+)\]\([^)]*\)")
63STRONG = re.compile(r"(\*\*|__)(.+?)\1")
64EMPHASIS = re.compile(r"(?<![\w*])([*_])(?!\s)(.+?)(?<!\s)\1(?![\w*])")
65
66GREEN = "\033[32m"
67RED = "\033[31m"
68YELLOW = "\033[33m"
69GREY = "\033[90m"
70RESET = "\033[0m"
71
72# In the order checks are listed in the preview.
73CI_STYLES = {
74 "failed": ("\uf057", RED, "Failed"),
75 "pending": ("\uf017", YELLOW, "InProgress"),
76 "passed": ("\uf058", GREEN, "Passing"),
77 "skipped": ("\uf056", GREY, "Skipped"),
78}
79FAILED = {
80 "FAILURE",
81 "ERROR",
82 "TIMED_OUT",
83 "CANCELLED",
84 "ACTION_REQUIRED",
85 "STARTUP_FAILURE",
86}
87PENDING = {"PENDING", "EXPECTED"}
88
89REVIEW = {
90 "APPROVED": "Approved",
91 "CHANGES_REQUESTED": "Changes requested",
92 "REVIEW_REQUIRED": "Review required",
93}
94REVIEW_COLORS = {"APPROVED": GREEN, "CHANGES_REQUESTED": RED, "REVIEW_REQUIRED": YELLOW}
95# Verdicts of individual reviewers, in the order they are listed.
96REVIEWER_MARKS = {
97 "APPROVED": "\u2713",
98 "CHANGES_REQUESTED": "\u2717",
99 "COMMENTED": "\U0001f4ac",
100}
101
102MERGE_STATE = {
103 "BEHIND": "Behind base",
104 "BLOCKED": "Blocked",
105 "CLEAN": "Ready",
106 "DIRTY": "Conflicts",
107 "DRAFT": "Draft",
108 "HAS_HOOKS": "Ready",
109 "UNKNOWN": "Checking",
110 "UNSTABLE": "Ready, with failing checks",
111}
112
113CHANGE_STYLES = {
114 "ADDED": ("A", GREEN),
115 "DELETED": ("D", RED),
116 "RENAMED": ("R", "\033[36m"),
117 "COPIED": ("C", "\033[36m"),
118}
119
120# First query words listing pull requests across every repository: the search
121# query, then the title and GitHub page of the first row.
122MODES = {
123 "myprs": ("author:@me", "Open your pull requests dashboard", "pulls"),
124 "review": (
125 "review-requested:@me",
126 "Open your review requests",
127 "pulls/review-requested",
128 ),
129 "assigned": ("assignee:@me", "Open your assigned pull requests", "pulls/assigned"),
130 "involved": (
131 "involves:@me",
132 "Open the pull requests involving you",
133 "pulls?q=is%3Aopen+is%3Apr+involves%3A%40me",
134 ),
135}
136
137PR_FRAGMENT = """
138fragment pr on PullRequest {
139 number title url isDraft headRefName reviewDecision mergeable
140 additions deletions updatedAt
141 repository { nameWithOwner owner { login avatarUrl(size: 128) } }
142 author { login avatarUrl(size: 128) }
143 reviewThreads(first: 100) { nodes { isResolved } }
144 commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
145}
146"""
147REPO_QUERY = (
148 """
149query($owner: String!, $name: String!) {
150 repository(owner: $owner, name: $name) {
151 pullRequests(states: OPEN, first: 50, orderBy: {field: CREATED_AT, direction: DESC}) {
152 nodes { ...pr }
153 }
154 }
155}
156"""
157 + PR_FRAGMENT
158)
159SEARCH_QUERY = (
160 """
161query($q: String!) {
162 search(query: $q, type: ISSUE, first: 50) {
163 nodes { ...pr }
164 }
165}
166"""
167 + PR_FRAGMENT
168)
169
170# Everything the preview shows, in one request: each request costs about a
171# second and Raffi gives the preview 3.
172PREVIEW_QUERY = """
173query($owner: String!, $name: String!, $number: Int!, $files: Int!) {
174 repository(owner: $owner, name: $name) {
175 pullRequest(number: $number) {
176 number title url state isDraft body createdAt updatedAt mergedAt
177 headRefName baseRefName reviewDecision mergeable mergeStateStatus
178 additions deletions changedFiles
179 author { login }
180 repository { nameWithOwner }
181 autoMergeRequest { mergeMethod enabledBy { login } }
182 milestone { title }
183 assignees(first: 10) { nodes { login } }
184 labels(first: 20) { nodes { name } }
185 reviewRequests(first: 20) {
186 nodes { requestedReviewer { ... on User { login } ... on Team { name } } }
187 }
188 latestReviews(first: 20) { nodes { author { login } state } }
189 reviewThreads(first: 100) { nodes { isResolved } }
190 comments(last: 10) {
191 totalCount
192 nodes { author { __typename login } createdAt body }
193 }
194 closingIssuesReferences(first: 10) {
195 nodes { number title state repository { nameWithOwner } }
196 }
197 files(first: $files) {
198 totalCount
199 nodes { path additions deletions changeType }
200 }
201 commits(last: 1) {
202 totalCount
203 nodes {
204 commit {
205 messageHeadline
206 statusCheckRollup {
207 contexts(first: 100) {
208 nodes {
209 __typename
210 ... on CheckRun {
211 name status conclusion
212 checkSuite { workflowRun { workflow { name } } }
213 }
214 ... on StatusContext { context state }
215 }
216 }
217 }
218 }
219 }
220 }
221 }
222 }
223}
224"""
225
226
227class GhError(Exception):
228 pass
229
230
231def run_gh(*args: str, timeout: float = 30) -> dict:
232 try:
233 result = subprocess.run(
234 ["gh", *args], capture_output=True, text=True, timeout=timeout, check=False
235 )
236 except FileNotFoundError:
237 raise GhError("GitHub CLI not found, see https://cli.github.com") from None
238 except subprocess.TimeoutExpired:
239 raise GhError(f"gh did not answer within {timeout} seconds") from None
240 if result.returncode:
241 raise GhError(result.stderr.strip() or f"gh exited with {result.returncode}")
242 try:
243 return json.loads(result.stdout)
244 except json.JSONDecodeError as error:
245 raise GhError(f"gh returned invalid JSON: {error}") from None
246
247
248def graphql(
249 query: str, cache: str | None = CACHE_PULLS, timeout: float = 30, **variables
250) -> dict:
251 args = ["api", "graphql", "--hostname", API_HOST]
252 if cache:
253 args += ["--cache", cache]
254 for name, value in {"query": query, **variables}.items():
255 # -F sends integers as numbers, -f keeps everything else a string.
256 args += ["-F" if isinstance(value, int) else "-f", f"{name}={value}"]
257 response = run_gh(*args, timeout=timeout)
258 if errors := response.get("errors"):
259 raise GhError(errors[0].get("message", "GraphQL error"))
260 return response["data"]
261
262
263def parse_query(query: str, repo: str | None = None) -> tuple[str, str]:
264 """Split the typed text into (repository or a MODES key, filter)."""
265 query = query.strip()
266 if repo:
267 return os.environ.get(f"ALIAS_{repo}", repo), query
268 word, _, rest = query.partition(" ")
269 rest = rest.strip()
270 if word in MODES:
271 return word, rest
272 if alias := os.environ.get(f"ALIAS_{word}"):
273 return alias, rest
274 if "/" in word:
275 return word, rest
276 return "myprs", query
277
278
279def ci_group(state: str) -> str:
280 if state in FAILED:
281 return "failed"
282 if state in PENDING:
283 return "pending"
284 if state == "SUCCESS":
285 return "passed"
286 return "skipped"
287
288
289def colored(text: str, color: str) -> str:
290 return f"{color}{text}{RESET}"
291
292
293def author_login(pr: dict) -> str:
294 return (pr.get("author") or {}).get("login", "ghost")
295
296
297def nodes(pr: dict, field: str) -> list:
298 return [node for node in (pr.get(field) or {}).get("nodes") or [] if node]
299
300
301def unresolved_threads(pr: dict) -> int:
302 return sum(not thread["isResolved"] for thread in nodes(pr, "reviewThreads"))
303
304
305def size(change: dict) -> str:
306 added = colored("+{}".format(change["additions"]), GREEN)
307 deleted = colored("-{}".format(change["deletions"]), RED)
308 return f"{added} {deleted}"
309
310
311def build_item(pr: dict, show_repo: bool) -> dict:
312 url = pr["url"]
313 repo = pr["repository"]["nameWithOwner"]
314 suffix = repo if show_repo else author_login(pr)
315 status = "Draft" if pr["isDraft"] else "Open"
316 commits = pr["commits"]["nodes"]
317 rollup = commits[0]["commit"]["statusCheckRollup"] if commits else None
318 if rollup:
319 icon, color, label = CI_STYLES[ci_group(rollup["state"])]
320 status = f"{icon} {colored(f'CI: {label}', color)} \u00b7 {status}"
321 details = [status]
322 if review := REVIEW.get(pr.get("reviewDecision")):
323 details.append(colored(review, REVIEW_COLORS[pr["reviewDecision"]]))
324 if pr.get("mergeable") == "CONFLICTING":
325 details.append(colored("Conflicts", RED))
326 if threads := unresolved_threads(pr):
327 details.append(f"\U0001f4ac {threads} unresolved")
328 if "additions" in pr:
329 details.append(size(pr))
330 if updated := pr.get("updatedAt"):
331 details.append(colored(f"updated {ago(updated)}", GREY))
332 return {
333 "title": f"PR #{pr['number']}: {pr['title']} - {suffix}",
334 "subtitle": " \u00b7 ".join(details),
335 "arg": url,
336 "variables": {
337 "PR_URL": url,
338 "PR_REPO": repo,
339 "PR_NUMBER": str(pr["number"]),
340 "PR_BRANCH": pr.get("headRefName", ""),
341 },
342 }
343
344
345def avatar_path(owner: str) -> Path:
346 return AVATAR_DIR / f"{owner}.svg"
347
348
349def account_icon(account: dict | None) -> str | None:
350 """Path of a GitHub account's avatar, downloaded on first use."""
351 account = account or {}
352 if not account.get("avatarUrl"):
353 return None
354 path = avatar_path(account["login"])
355 if path.exists():
356 return str(path)
357 try:
358 with urllib.request.urlopen(
359 account["avatarUrl"], timeout=AVATAR_TIMEOUT
360 ) as response:
361 mime = response.headers.get_content_type()
362 data = base64.b64encode(response.read()).decode()
363 except OSError:
364 return None
365 if not mime.startswith("image/"):
366 return None
367 path.parent.mkdir(parents=True, exist_ok=True)
368 partial = path.with_suffix(".part")
369 partial.write_text(AVATAR_SVG.format(mime=mime, data=data))
370 partial.replace(path)
371 return str(path)
372
373
374def link_item(title: str, url: str) -> dict:
375 return {
376 "title": title,
377 "subtitle": url,
378 "arg": url,
379 "preview": {"title": title, "text": f"Opens {url}", "dynamic": False},
380 }
381
382
383def error_item(title: str, message: str) -> dict:
384 return {
385 "title": title,
386 "subtitle": message,
387 "preview": {"title": title, "text": message, "dynamic": False},
388 }
389
390
391def list_items(query: str, repo_arg: str | None = None) -> list[dict]:
392 target, needle = parse_query(query, repo_arg)
393 if target not in MODES and not REPO.fullmatch(target):
394 return [
395 error_item("Invalid repository", f"Expected owner/repo, got {target!r}")
396 ]
397
398 try:
399 if target in MODES:
400 search, title, page = MODES[target]
401 data = graphql(SEARCH_QUERY, q=f"is:pr is:open {search}")
402 pulls = data["search"]["nodes"]
403 items = [link_item(title, f"https://{API_HOST}/{page}")]
404 else:
405 owner, name = target.split("/")
406 data = graphql(REPO_QUERY, owner=owner, name=name)
407 pulls = data["repository"]["pullRequests"]["nodes"]
408 url = f"https://{API_HOST}/{target}/pulls"
409 items = [link_item("Open all pull requests page", url)]
410 except GhError as error:
411 return [error_item("GitHub error", str(error))]
412
413 needle = needle.casefold()
414 matches: list[tuple[dict, dict]] = []
415 for pr in filter(None, pulls):
416 item = build_item(pr, show_repo=target in MODES)
417 text = f"{item['title']} {item['subtitle']} {author_login(pr)}"
418 if needle in ANSI.sub("", text).casefold():
419 matches.append((pr, item))
420
421 # Within one repository every owner avatar is the same, so show who
422 # opened each pull request instead.
423 single_repo = len({pr["repository"]["nameWithOwner"] for pr, _ in matches}) == 1
424 for pr, item in matches:
425 account = pr.get("author") if single_repo else pr["repository"].get("owner")
426 if icon := account_icon(account):
427 item["icon"] = {"path": icon}
428
429 if target not in MODES:
430 items.extend(item for _, item in matches)
431 return items
432
433 groups: dict[str, list[dict]] = {}
434 for pr, item in matches:
435 owner = pr["repository"]["nameWithOwner"].split("/", 1)[0]
436 groups.setdefault(owner, []).append(item)
437
438 if len(groups) < 2:
439 items.extend(item for _, item in matches)
440 return items
441
442 for owner, owner_items in groups.items():
443 items.append({"title": owner, "indent": 0, "valid": False})
444 for item in owner_items:
445 item["indent"] = 1
446 items.append(item)
447 return items
448
449
450def check_name(check: dict) -> str:
451 name = check.get("name") or check.get("context") or "?"
452 run = ((check.get("checkSuite") or {}).get("workflowRun")) or {}
453 if workflow := (run.get("workflow") or {}).get("name"):
454 return f"{workflow} / {name}"
455 return name
456
457
458def check_state(check: dict) -> str:
459 if check.get("__typename") == "StatusContext":
460 return check.get("state", "")
461 if check.get("status") != "COMPLETED":
462 return "PENDING"
463 return check.get("conclusion", "")
464
465
466def checks_section(checks: list[dict]) -> dict:
467 order = list(CI_STYLES)
468 rows = sorted(
469 ((ci_group(check_state(check)), check_name(check)) for check in checks),
470 key=lambda row: (order.index(row[0]), row[1]),
471 )
472 counts = Counter(group for group, _ in rows)
473 summary = ", ".join(f"{counts[group]} {group}" for group in order if counts[group])
474 lines = []
475 for group, name in rows:
476 icon, color, _ = CI_STYLES[group]
477 lines.append(f"{colored(icon, color)} {name}")
478 return {
479 "type": "text",
480 "heading": f"Checks: {summary}",
481 "content": "\n".join(lines),
482 }
483
484
485def ago(timestamp: str) -> str:
486 seconds = (datetime.now(UTC) - datetime.fromisoformat(timestamp)).total_seconds()
487 for unit, length in (
488 ("y", 31536000),
489 ("mo", 2592000),
490 ("d", 86400),
491 ("h", 3600),
492 ("m", 60),
493 ):
494 if seconds >= length:
495 return f"{int(seconds // length)}{unit} ago"
496 return "just now"
497
498
499def pr_state(pr: dict) -> str:
500 if pr["state"] == "OPEN" and pr["isDraft"]:
501 return "Draft"
502 return pr["state"].capitalize()
503
504
505def sgr(text: str, on: str, off: str) -> str:
506 return f"\033[{on}m{text}\033[{off}m"
507
508
509def render_text(text: str) -> str:
510 text = HTML_TAG.sub("", text)
511 text = IMAGE.sub(lambda m: sgr(f"[image: {m[1] or 'image'}]", "90", "39"), text)
512 text = LINK.sub(lambda m: sgr(m[1], "4;34", "24;39"), text)
513 text = STRONG.sub(lambda m: sgr(m[2], "1", "22"), text)
514 # Raffi has no italics, so emphasis only loses its markers.
515 return EMPHASIS.sub(r"\2", text)
516
517
518def render_inline(line: str) -> str:
519 """Render inline markdown, leaving code spans untouched."""
520 parts, pos = [], 0
521 for match in CODE_SPAN.finditer(line):
522 parts.append(render_text(line[pos : match.start()]))
523 parts.append(sgr(match[2], "33", "39"))
524 pos = match.end()
525 parts.append(render_text(line[pos:]))
526 return "".join(parts)
527
528
529def render_markdown(text: str) -> str:
530 lines, in_code = [], False
531 for line in text.splitlines():
532 if FENCE.match(line):
533 in_code = not in_code
534 elif in_code:
535 lines.append(sgr(f" {line}", "33", "39"))
536 elif match := HEADING.match(line):
537 lines.append(sgr(render_inline(match[1]), "1;35", "0"))
538 elif RULE.match(line):
539 lines.append(sgr("\u2500" * 40, "90", "39"))
540 elif TABLE_RULE.match(line):
541 continue
542 elif match := LIST_ITEM.match(line):
543 indent, box, item = match.groups()
544 if box is None:
545 marker = "\u2022"
546 elif box == " ":
547 marker = "\u2610"
548 else:
549 marker = sgr("\u2611", "32", "39")
550 lines.append(f"{indent}{marker} {render_inline(item)}")
551 elif match := QUOTE.match(line):
552 quote = match[1]
553 if alert := ALERT.match(quote):
554 quote = sgr(alert[1].capitalize(), "1;33", "0")
555 else:
556 quote = render_inline(quote)
557 lines.append(sgr("\u2502 ", "90", "39") + quote)
558 else:
559 lines.append(render_inline(line))
560 return "\n".join(line.rstrip() for line in lines)
561
562
563def clean_body(body: str) -> str:
564 body = HTML_COMMENT.sub("", body.replace("\r\n", "\n"))
565 return BLANK_LINES.sub("\n\n", render_markdown(body)).strip()
566
567
568def is_bot(author: dict | None) -> bool:
569 author = author or {}
570 login = author.get("login", "")
571 return author.get("__typename") == "Bot" or login.endswith(BOT_SUFFIXES)
572
573
574def reviewers(pr: dict) -> str:
575 """Each reviewer's latest verdict, then the reviews still requested."""
576 verdicts = []
577 for review in nodes(pr, "latestReviews"):
578 if mark := REVIEWER_MARKS.get(review["state"]):
579 verdicts.append(f"{mark} {author_login(review)}")
580 for request in nodes(pr, "reviewRequests"):
581 reviewer = request.get("requestedReviewer") or {}
582 if who := reviewer.get("login") or reviewer.get("name"):
583 verdicts.append(f"\u23f3 {who}")
584 return ", ".join(verdicts)
585
586
587def merge_state(pr: dict) -> str:
588 if pr["state"] == "MERGED":
589 return f"Merged {ago(pr['mergedAt'])}" if pr.get("mergedAt") else "Merged"
590 if pr["state"] != "OPEN":
591 return ""
592 if pr.get("mergeable") == "CONFLICTING":
593 state = "Conflicts"
594 else:
595 state = MERGE_STATE.get(pr.get("mergeStateStatus"), "")
596 if auto := pr.get("autoMergeRequest"):
597 by = (auto.get("enabledBy") or {}).get("login")
598 method = (auto.get("mergeMethod") or "").lower()
599 state += f", auto-merge ({method})" + (f" by {by}" if by else "")
600 return state.strip(", ")
601
602
603def closes_section(pr: dict) -> dict | None:
604 issues = nodes(pr, "closingIssuesReferences")
605 if not issues:
606 return None
607 repo = pr["repository"]["nameWithOwner"]
608 lines = []
609 for issue in issues:
610 state = issue["state"].lower()
611 color = GREEN if state == "open" else "\033[35m"
612 where = issue["repository"]["nameWithOwner"]
613 ref = f"#{issue['number']}" if where == repo else f"{where}#{issue['number']}"
614 lines.append(
615 f"{sgr(ref, '1', '22')} {colored(f'[{state}]', color)} {issue['title']}"
616 )
617 return {"type": "text", "heading": "Closes", "content": "\n".join(lines)}
618
619
620def comment_sections(pr: dict) -> list[dict]:
621 comments = [c for c in nodes(pr, "comments") if not is_bot(c.get("author"))]
622 return [
623 {
624 "type": "text",
625 "heading": f"\U0001f4ac {author_login(comment)} \u00b7 {ago(comment['createdAt'])}",
626 "content": clean_body(comment["body"]) or "(empty)",
627 }
628 for comment in reversed(comments[-PREVIEW_COMMENTS:])
629 ]
630
631
632def files_section(pr: dict) -> dict | None:
633 files = nodes(pr, "files")
634 if not files:
635 return None
636 lines = []
637 for file in files:
638 letter, color = CHANGE_STYLES.get(file["changeType"], ("M", YELLOW))
639 lines.append(f"{colored(letter, color)} {file['path']} {size(file)}")
640 total = (pr.get("files") or {}).get("totalCount", len(files))
641 if total > len(files):
642 lines.append(colored(f"\u2026 and {total - len(files)} more", GREY))
643 return {"type": "text", "heading": f"Files ({total})", "content": "\n".join(lines)}
644
645
646def build_preview(pr: dict) -> dict:
647 repo = pr["repository"]["nameWithOwner"]
648 author = author_login(pr)
649 metadata = [
650 ["Repository", repo],
651 ["Author", author],
652 ["Branch", f"{pr['headRefName']} \u2192 {pr['baseRefName']}"],
653 ]
654 if review := REVIEW.get(pr["reviewDecision"]):
655 metadata.append(["Review", review])
656 if who := reviewers(pr):
657 metadata.append(["Reviewers", who])
658 if merge := merge_state(pr):
659 metadata.append(["Merge", merge])
660 if threads := unresolved_threads(pr):
661 metadata.append(["Threads", f"{threads} unresolved"])
662 commit_nodes = nodes(pr, "commits")
663 if commit_nodes:
664 total = pr["commits"]["totalCount"]
665 headline = commit_nodes[0]["commit"]["messageHeadline"]
666 label = f"{total} commit{'s' * (total != 1)}"
667 metadata.append(["Commits", f"{label}, last: {headline}"])
668 if assignees := ", ".join(a["login"] for a in nodes(pr, "assignees")):
669 metadata.append(["Assignees", assignees])
670 if milestone := (pr.get("milestone") or {}).get("title"):
671 metadata.append(["Milestone", milestone])
672 if labels := ", ".join(label["name"] for label in nodes(pr, "labels")):
673 metadata.append(["Labels", labels])
674 files = pr["changedFiles"]
675 changes = (
676 f"+{pr['additions']} -{pr['deletions']} in {files} file{'s' * (files != 1)}"
677 )
678 metadata += [
679 ["Changes", changes],
680 ["Created", ago(pr["createdAt"])],
681 ["Updated", ago(pr["updatedAt"])],
682 ]
683
684 rollup = commit_nodes[0]["commit"]["statusCheckRollup"] if commit_nodes else None
685 checks = nodes(rollup or {}, "contexts")
686 sections = [checks_section(checks)] if checks else []
687 if closes := closes_section(pr):
688 sections.append(closes)
689 sections.append(
690 {
691 "type": "text",
692 "heading": "Description",
693 "content": clean_body(pr["body"]) or "(no description)",
694 }
695 )
696 sections += comment_sections(pr)
697 if changed := files_section(pr):
698 sections.append(changed)
699
700 avatar = avatar_path(repo.split("/")[0])
701 preview = {
702 "title": f"#{pr['number']} {pr['title']}",
703 "subtitle": f"{repo} by {author}",
704 "badge": pr_state(pr),
705 "icon": str(avatar) if avatar.exists() else ICON,
706 "sections": sections,
707 "metadata": metadata,
708 }
709 if any(ci_group(check_state(check)) == "pending" for check in checks):
710 preview["refresh"] = PREVIEW_REFRESH_SECONDS
711 return preview
712
713
714def preview(url: str) -> dict:
715 match = PR_URL.match(url)
716 if not match:
717 return {
718 "title": url or "Pull request",
719 "icon": ICON,
720 "text": "Not a pull request URL.",
721 }
722 owner, name, number = match.groups()
723 try:
724 data = graphql(
725 PREVIEW_QUERY,
726 cache=None,
727 timeout=PREVIEW_TIMEOUT,
728 owner=owner,
729 name=name,
730 number=int(number),
731 files=PREVIEW_FILES,
732 )
733 pr = (data.get("repository") or {}).get("pullRequest")
734 if not pr:
735 raise GhError("pull request not found")
736 except GhError as error:
737 return {
738 "title": url,
739 "icon": ICON,
740 "text": f"Cannot load this pull request: {error}",
741 }
742 return build_preview(pr)
743
744
745def main(argv: list[str] | None = None) -> int:
746 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
747 parser.add_argument(
748 "--repo", help="owner/repo or alias to list; the query only filters"
749 )
750 parser.add_argument("query", nargs="*", help="text typed after the Raffi keyword")
751 args = parser.parse_args(argv)
752
753 if os.environ.get("RAFFI_PREVIEW") == "1":
754 output = preview(os.environ.get("RAFFI_VALUE", ""))
755 else:
756 output = {"items": list_items(" ".join(args.query), args.repo)}
757 print(json.dumps(output, ensure_ascii=False))
758 return 0
759
760
761if __name__ == "__main__":
762 raise SystemExit(main())