workdash 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- workdash/__init__.py +12 -0
- workdash/__main__.py +5 -0
- workdash/analysis_cache.py +184 -0
- workdash/analyzer.py +229 -0
- workdash/backend.py +248 -0
- workdash/config.py +207 -0
- workdash/github_client.py +1079 -0
- workdash/included_items.py +58 -0
- workdash/launcher.py +378 -0
- workdash/models.py +50 -0
- workdash/prompts/__init__.py +0 -0
- workdash/prompts/analyze_issue.txt +120 -0
- workdash/prompts/analyze_pr.txt +147 -0
- workdash/prompts/launch_issue.txt +20 -0
- workdash/prompts/launch_pr.txt +20 -0
- workdash/prompts/launch_review.txt +20 -0
- workdash/repo_resolver.py +112 -0
- workdash/repo_worktree.py +304 -0
- workdash/tui.py +608 -0
- workdash/workdash.py +207 -0
- workdash-0.1.0.dist-info/METADATA +890 -0
- workdash-0.1.0.dist-info/RECORD +26 -0
- workdash-0.1.0.dist-info/WHEEL +5 -0
- workdash-0.1.0.dist-info/entry_points.txt +2 -0
- workdash-0.1.0.dist-info/licenses/LICENSE +674 -0
- workdash-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1079 @@
|
|
|
1
|
+
"""GitHub data access wrappers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import TypedDict
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
from .models import WorkItem, WorkItemKind, WorkItemType
|
|
16
|
+
|
|
17
|
+
_GITHUB_HOSTS = {"github.com", "www.github.com"}
|
|
18
|
+
_ITEM_SEGMENT_TYPES = {"pull": WorkItemType.PR, "issues": WorkItemType.ISSUE}
|
|
19
|
+
_NUMBER_RE = re.compile(r"^\d+$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class ParsedGitHubItemURL:
|
|
24
|
+
"""A parsed GitHub issue or pull request URL."""
|
|
25
|
+
|
|
26
|
+
repo: str
|
|
27
|
+
number: int
|
|
28
|
+
item_type: WorkItemType
|
|
29
|
+
canonical_url: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_github_item_url(url: str) -> ParsedGitHubItemURL | None:
|
|
33
|
+
"""Parse a GitHub issue/PR URL, ignoring trailing path/query/fragment.
|
|
34
|
+
|
|
35
|
+
Returns ``None`` for any input that does not name a GitHub issue or
|
|
36
|
+
pull request: wrong host, wrong path shape, or a non-numeric item
|
|
37
|
+
number.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
if not isinstance(url, str):
|
|
41
|
+
return None
|
|
42
|
+
stripped = url.strip()
|
|
43
|
+
if not stripped:
|
|
44
|
+
return None
|
|
45
|
+
parts = urlsplit(stripped)
|
|
46
|
+
if parts.scheme not in {"http", "https"}:
|
|
47
|
+
return None
|
|
48
|
+
if parts.hostname is None or parts.hostname.lower() not in _GITHUB_HOSTS:
|
|
49
|
+
return None
|
|
50
|
+
segments = [segment for segment in parts.path.split("/") if segment]
|
|
51
|
+
if len(segments) < 4:
|
|
52
|
+
return None
|
|
53
|
+
owner, repository, kind_segment, number_segment = segments[:4]
|
|
54
|
+
if not owner or not repository:
|
|
55
|
+
return None
|
|
56
|
+
item_type = _ITEM_SEGMENT_TYPES.get(kind_segment)
|
|
57
|
+
if item_type is None:
|
|
58
|
+
return None
|
|
59
|
+
if not _NUMBER_RE.match(number_segment):
|
|
60
|
+
return None
|
|
61
|
+
number = int(number_segment)
|
|
62
|
+
canonical_url = f"https://github.com/{owner}/{repository}/{kind_segment}/{number}"
|
|
63
|
+
return ParsedGitHubItemURL(
|
|
64
|
+
repo=f"{owner}/{repository}",
|
|
65
|
+
number=number,
|
|
66
|
+
item_type=item_type,
|
|
67
|
+
canonical_url=canonical_url,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
_DEFAULT_PR_SEARCH_LIMIT = 1000
|
|
72
|
+
_DEFAULT_ASSIGNED_ISSUE_LIMIT = 20
|
|
73
|
+
_PR_JSON_FIELDS = "id,number,title,url,createdAt,updatedAt,isDraft,repository"
|
|
74
|
+
_ISSUE_JSON_FIELDS = "id,number,title,url,createdAt,updatedAt,repository"
|
|
75
|
+
_DEFAULT_RECENT_SEARCH_LIMIT = 1000
|
|
76
|
+
_RECENT_JSON_FIELDS = "id,number,title,url,createdAt,updatedAt,state,isPullRequest,repository"
|
|
77
|
+
_RECENT_QUALIFIER_BATCH_SIZE = 20
|
|
78
|
+
_TRANSIENT_RETRIES = 2
|
|
79
|
+
_TRANSIENT_RETRY_DELAY_SECONDS = 2.0
|
|
80
|
+
# gh surfaces transient API failures in several shapes we've seen in the wild:
|
|
81
|
+
# - "HTTP 5xx: ..." / "non-200 OK status code: 5xx ..." (5xx server errors)
|
|
82
|
+
# - "HTTP 429" / "API rate limit exceeded" / "abuse detection" (rate limiting)
|
|
83
|
+
# - "dial tcp ... no such host" / "connection reset" / "i/o timeout" ... (network)
|
|
84
|
+
# Each of these can succeed on a later retry, so the caller should retain the
|
|
85
|
+
# URL in the included-items store and retry on the next refresh.
|
|
86
|
+
_TRANSIENT_HTTP_STATUS_RE = re.compile(r"(?:HTTP |status code:?\s*)5\d{2}", re.IGNORECASE)
|
|
87
|
+
_TRANSIENT_SUBSTRINGS = (
|
|
88
|
+
"http 429",
|
|
89
|
+
"rate limit",
|
|
90
|
+
"abuse detection",
|
|
91
|
+
"dial tcp",
|
|
92
|
+
"connection refused",
|
|
93
|
+
"connection reset",
|
|
94
|
+
"no such host",
|
|
95
|
+
"i/o timeout",
|
|
96
|
+
"context deadline exceeded",
|
|
97
|
+
"eof",
|
|
98
|
+
)
|
|
99
|
+
_REPOSITORY_AUTHORIZATION_SUBSTRINGS = (
|
|
100
|
+
"resource protected by organization saml enforcement",
|
|
101
|
+
"saml enforcement",
|
|
102
|
+
"must grant your oauth token access",
|
|
103
|
+
"organization has enabled oauth app access restrictions",
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class TransientFetchError(RuntimeError):
|
|
108
|
+
"""Raised when a gh command failed with a retryable network/5xx/429 error.
|
|
109
|
+
|
|
110
|
+
Callers that maintain a persistent store of URLs should retain the
|
|
111
|
+
entry so the next refresh can try again.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class RepositoryAuthorizationError(RuntimeError):
|
|
116
|
+
"""Raised when gh reports repository-specific authorization is required."""
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _is_transient_gh_error(error: subprocess.CalledProcessError) -> bool:
|
|
120
|
+
stderr = (error.stderr or "").strip()
|
|
121
|
+
if not stderr:
|
|
122
|
+
return False
|
|
123
|
+
if _TRANSIENT_HTTP_STATUS_RE.search(stderr):
|
|
124
|
+
return True
|
|
125
|
+
stderr_lower = stderr.lower()
|
|
126
|
+
return any(needle in stderr_lower for needle in _TRANSIENT_SUBSTRINGS)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _is_repository_authorization_error(message: str) -> bool:
|
|
130
|
+
message_lower = message.lower()
|
|
131
|
+
return any(needle in message_lower for needle in _REPOSITORY_AUTHORIZATION_SUBSTRINGS)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _noop_progress_callback(_message: str) -> None:
|
|
135
|
+
"""Ignore progress updates when no reporting target is configured."""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _run_gh_command_with_retry(
|
|
139
|
+
command: list[str],
|
|
140
|
+
*,
|
|
141
|
+
not_found_message: str,
|
|
142
|
+
failure_message_prefix: str,
|
|
143
|
+
report_progress: Callable[[str], None] = _noop_progress_callback,
|
|
144
|
+
retry_label: str | None = None,
|
|
145
|
+
classify_repository_authorization: bool = False,
|
|
146
|
+
) -> subprocess.CompletedProcess[str]:
|
|
147
|
+
"""Run a ``gh`` subprocess with bounded retry on transient failures.
|
|
148
|
+
|
|
149
|
+
Raises ``TransientFetchError`` when retries are exhausted and the
|
|
150
|
+
final failure was classified transient (5xx, 429, rate-limit, common
|
|
151
|
+
network errors). Raises a plain ``RuntimeError`` for permanent errors
|
|
152
|
+
(bad auth, 404, malformed command) so existing callers continue to
|
|
153
|
+
surface the same descriptive message they did before. Raises
|
|
154
|
+
``RepositoryAuthorizationError`` for known repository-specific denial
|
|
155
|
+
shapes when ``classify_repository_authorization`` is enabled.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
for attempt in range(_TRANSIENT_RETRIES + 1):
|
|
159
|
+
try:
|
|
160
|
+
return subprocess.run(command, check=True, capture_output=True, text=True)
|
|
161
|
+
except FileNotFoundError as error:
|
|
162
|
+
# Missing gh is treated as transient: the user can install it and
|
|
163
|
+
# refresh. Raising a TransientFetchError (itself a RuntimeError)
|
|
164
|
+
# keeps the existing "gh CLI is not installed..." message so
|
|
165
|
+
# pytest.raises(RuntimeError, match=...) still matches, while
|
|
166
|
+
# letting fetch_item_by_url retain the URL for a later retry.
|
|
167
|
+
raise TransientFetchError(not_found_message) from error
|
|
168
|
+
except subprocess.CalledProcessError as error:
|
|
169
|
+
transient = _is_transient_gh_error(error)
|
|
170
|
+
if attempt < _TRANSIENT_RETRIES and transient:
|
|
171
|
+
if retry_label is not None:
|
|
172
|
+
report_progress(
|
|
173
|
+
f"{retry_label} got transient error, "
|
|
174
|
+
f"retrying ({attempt + 1}/{_TRANSIENT_RETRIES})..."
|
|
175
|
+
)
|
|
176
|
+
time.sleep(_TRANSIENT_RETRY_DELAY_SECONDS)
|
|
177
|
+
continue
|
|
178
|
+
stderr = (error.stderr or "").strip()
|
|
179
|
+
message = (
|
|
180
|
+
f"{failure_message_prefix}: "
|
|
181
|
+
f"{stderr or f'process exited with code {error.returncode}'}"
|
|
182
|
+
)
|
|
183
|
+
if transient:
|
|
184
|
+
raise TransientFetchError(message) from error
|
|
185
|
+
if classify_repository_authorization and _is_repository_authorization_error(stderr):
|
|
186
|
+
raise RepositoryAuthorizationError(message) from error
|
|
187
|
+
raise RuntimeError(message) from error
|
|
188
|
+
raise AssertionError("unreachable: retry loop exited without return or raise")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class AuthoredPullRequest(TypedDict):
|
|
192
|
+
"""Raw authored PR record from gh search, normalized for later conversion."""
|
|
193
|
+
|
|
194
|
+
id: str | int
|
|
195
|
+
repo: str
|
|
196
|
+
number: int
|
|
197
|
+
title: str
|
|
198
|
+
url: str
|
|
199
|
+
created_at: str
|
|
200
|
+
updated_at: str
|
|
201
|
+
is_draft: bool
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class ReviewRequestedPullRequest(TypedDict):
|
|
205
|
+
"""Raw review-requested PR record from gh search, normalized for conversion."""
|
|
206
|
+
|
|
207
|
+
id: str | int
|
|
208
|
+
repo: str
|
|
209
|
+
number: int
|
|
210
|
+
title: str
|
|
211
|
+
url: str
|
|
212
|
+
created_at: str
|
|
213
|
+
updated_at: str
|
|
214
|
+
is_draft: bool
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class RecentTrackedItem(TypedDict):
|
|
218
|
+
"""Raw issue/PR record from gh search, normalized for later conversion."""
|
|
219
|
+
|
|
220
|
+
id: str | int
|
|
221
|
+
repo: str
|
|
222
|
+
number: int
|
|
223
|
+
title: str
|
|
224
|
+
url: str
|
|
225
|
+
created_at: str
|
|
226
|
+
updated_at: str
|
|
227
|
+
is_pull_request: bool
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class AssignedIssue(TypedDict):
|
|
231
|
+
"""Raw assigned issue record from gh search, normalized for conversion."""
|
|
232
|
+
|
|
233
|
+
id: str | int
|
|
234
|
+
repo: str
|
|
235
|
+
number: int
|
|
236
|
+
title: str
|
|
237
|
+
url: str
|
|
238
|
+
created_at: str
|
|
239
|
+
updated_at: str
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def parse_github_datetime(timestamp: str) -> datetime:
|
|
243
|
+
"""Parse a GitHub ISO-8601 timestamp into a timezone-aware datetime."""
|
|
244
|
+
|
|
245
|
+
try:
|
|
246
|
+
parsed_timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
|
247
|
+
except ValueError as error:
|
|
248
|
+
raise RuntimeError(f"Invalid GitHub timestamp {timestamp!r}: {error}") from error
|
|
249
|
+
if parsed_timestamp.tzinfo is None:
|
|
250
|
+
raise RuntimeError(f"Invalid GitHub timestamp {timestamp!r}: timezone offset is required.")
|
|
251
|
+
return parsed_timestamp
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def normalize_authored_pull_request(item: AuthoredPullRequest) -> WorkItem:
|
|
255
|
+
"""Convert one raw authored PR payload into the internal WorkItem model."""
|
|
256
|
+
|
|
257
|
+
return WorkItem(
|
|
258
|
+
kind=WorkItemKind.AUTHORED_PR,
|
|
259
|
+
item_type=WorkItemType.PR,
|
|
260
|
+
repo=item["repo"],
|
|
261
|
+
number=item["number"],
|
|
262
|
+
title=item["title"],
|
|
263
|
+
created_at=parse_github_datetime(item["created_at"]),
|
|
264
|
+
updated_at=parse_github_datetime(item["updated_at"]),
|
|
265
|
+
url=item["url"],
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def normalize_review_requested_pull_request(item: ReviewRequestedPullRequest) -> WorkItem:
|
|
270
|
+
"""Convert one raw review-requested PR payload into the internal WorkItem model."""
|
|
271
|
+
|
|
272
|
+
return WorkItem(
|
|
273
|
+
kind=WorkItemKind.REVIEW_REQUESTED_PR,
|
|
274
|
+
item_type=WorkItemType.PR,
|
|
275
|
+
repo=item["repo"],
|
|
276
|
+
number=item["number"],
|
|
277
|
+
title=item["title"],
|
|
278
|
+
created_at=parse_github_datetime(item["created_at"]),
|
|
279
|
+
updated_at=parse_github_datetime(item["updated_at"]),
|
|
280
|
+
url=item["url"],
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def normalize_recent_tracked_item(item: RecentTrackedItem) -> WorkItem:
|
|
285
|
+
"""Convert one raw tracked issue/PR payload into the internal WorkItem model."""
|
|
286
|
+
|
|
287
|
+
return WorkItem(
|
|
288
|
+
kind=WorkItemKind.TRACKED_PR if item["is_pull_request"] else WorkItemKind.TRACKED_ISSUE,
|
|
289
|
+
item_type=WorkItemType.PR if item["is_pull_request"] else WorkItemType.ISSUE,
|
|
290
|
+
repo=item["repo"],
|
|
291
|
+
number=item["number"],
|
|
292
|
+
title=item["title"],
|
|
293
|
+
created_at=parse_github_datetime(item["created_at"]),
|
|
294
|
+
updated_at=parse_github_datetime(item["updated_at"]),
|
|
295
|
+
url=item["url"],
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def normalize_assigned_issue(item: AssignedIssue) -> WorkItem:
|
|
300
|
+
"""Convert one raw assigned issue payload into the internal WorkItem model."""
|
|
301
|
+
|
|
302
|
+
return WorkItem(
|
|
303
|
+
kind=WorkItemKind.ASSIGNED_ISSUE,
|
|
304
|
+
item_type=WorkItemType.ISSUE,
|
|
305
|
+
repo=item["repo"],
|
|
306
|
+
number=item["number"],
|
|
307
|
+
title=item["title"],
|
|
308
|
+
created_at=parse_github_datetime(item["created_at"]),
|
|
309
|
+
updated_at=parse_github_datetime(item["updated_at"]),
|
|
310
|
+
url=item["url"],
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def normalize_assigned_issues(items: list[AssignedIssue]) -> list[WorkItem]:
|
|
315
|
+
"""Convert assigned issue records into internal WorkItems."""
|
|
316
|
+
|
|
317
|
+
return [normalize_assigned_issue(item) for item in items]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def normalize_authored_pull_requests(items: list[AuthoredPullRequest]) -> list[WorkItem]:
|
|
321
|
+
"""Convert authored PR records into internal WorkItems."""
|
|
322
|
+
|
|
323
|
+
return [normalize_authored_pull_request(item) for item in items]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def normalize_review_requested_pull_requests(
|
|
327
|
+
items: list[ReviewRequestedPullRequest],
|
|
328
|
+
) -> list[WorkItem]:
|
|
329
|
+
"""Convert review-requested PR records into internal WorkItems."""
|
|
330
|
+
|
|
331
|
+
return [normalize_review_requested_pull_request(item) for item in items]
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def normalize_recent_tracked_items(items: list[RecentTrackedItem]) -> list[WorkItem]:
|
|
335
|
+
"""Convert tracked issue/PR records into internal WorkItems."""
|
|
336
|
+
|
|
337
|
+
return [normalize_recent_tracked_item(item) for item in items]
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def merge_normalized_work_items(
|
|
341
|
+
primary_items: list[WorkItem],
|
|
342
|
+
secondary_items: list[WorkItem],
|
|
343
|
+
) -> list[WorkItem]:
|
|
344
|
+
"""Merge normalized WorkItems with deterministic dedupe semantics.
|
|
345
|
+
|
|
346
|
+
Identity is ``(item_type, repo, number)`` so issues and PRs remain independent.
|
|
347
|
+
Output order is stable: primary input order first, then remaining secondary order.
|
|
348
|
+
The ``included`` flag is sticky: if either side of a collision was
|
|
349
|
+
included the surviving record keeps ``included=True``.
|
|
350
|
+
"""
|
|
351
|
+
|
|
352
|
+
merged_items: list[WorkItem] = []
|
|
353
|
+
indexes_by_identity: dict[tuple[WorkItemType, str, int], int] = {}
|
|
354
|
+
for item in primary_items:
|
|
355
|
+
identity = (item.item_type, item.repo, item.number)
|
|
356
|
+
if identity in indexes_by_identity:
|
|
357
|
+
continue
|
|
358
|
+
indexes_by_identity[identity] = len(merged_items)
|
|
359
|
+
merged_items.append(item)
|
|
360
|
+
for item in secondary_items:
|
|
361
|
+
identity = (item.item_type, item.repo, item.number)
|
|
362
|
+
if identity in indexes_by_identity:
|
|
363
|
+
if item.included:
|
|
364
|
+
merged_items[indexes_by_identity[identity]].included = True
|
|
365
|
+
continue
|
|
366
|
+
indexes_by_identity[identity] = len(merged_items)
|
|
367
|
+
merged_items.append(item)
|
|
368
|
+
return merged_items
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class GitHubClient:
|
|
372
|
+
"""Thin wrapper around the ``gh`` CLI for work item discovery.
|
|
373
|
+
|
|
374
|
+
Each method shells out to ``gh search`` or ``gh pr view`` and normalizes
|
|
375
|
+
the JSON payload into TypedDict records for downstream conversion.
|
|
376
|
+
"""
|
|
377
|
+
|
|
378
|
+
@staticmethod
|
|
379
|
+
def _parse_open_pull_request_payload(
|
|
380
|
+
payload: object,
|
|
381
|
+
*,
|
|
382
|
+
context: str,
|
|
383
|
+
) -> list[AuthoredPullRequest]:
|
|
384
|
+
if not isinstance(payload, list):
|
|
385
|
+
raise RuntimeError(f"Invalid gh {context} PR payload: expected a JSON array.")
|
|
386
|
+
|
|
387
|
+
pull_requests: list[AuthoredPullRequest] = []
|
|
388
|
+
for index, entry in enumerate(payload):
|
|
389
|
+
if not isinstance(entry, dict):
|
|
390
|
+
raise RuntimeError(
|
|
391
|
+
f"Invalid gh {context} PR payload: entry {index} is not an object."
|
|
392
|
+
)
|
|
393
|
+
repository = entry.get("repository")
|
|
394
|
+
if not isinstance(repository, dict):
|
|
395
|
+
raise RuntimeError(
|
|
396
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid repository."
|
|
397
|
+
)
|
|
398
|
+
repository_name_with_owner = repository.get("nameWithOwner")
|
|
399
|
+
if not isinstance(repository_name_with_owner, str) or not repository_name_with_owner:
|
|
400
|
+
raise RuntimeError(
|
|
401
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid repository.nameWithOwner."
|
|
402
|
+
)
|
|
403
|
+
pr_id = entry.get("id")
|
|
404
|
+
if not isinstance(pr_id, (str, int)):
|
|
405
|
+
raise RuntimeError(
|
|
406
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid id."
|
|
407
|
+
)
|
|
408
|
+
number = entry.get("number")
|
|
409
|
+
if not isinstance(number, int):
|
|
410
|
+
raise RuntimeError(
|
|
411
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid number."
|
|
412
|
+
)
|
|
413
|
+
title = entry.get("title")
|
|
414
|
+
if not isinstance(title, str):
|
|
415
|
+
raise RuntimeError(
|
|
416
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid title."
|
|
417
|
+
)
|
|
418
|
+
url = entry.get("url")
|
|
419
|
+
if not isinstance(url, str):
|
|
420
|
+
raise RuntimeError(
|
|
421
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid url."
|
|
422
|
+
)
|
|
423
|
+
created_at = entry.get("createdAt")
|
|
424
|
+
if not isinstance(created_at, str):
|
|
425
|
+
raise RuntimeError(
|
|
426
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid createdAt."
|
|
427
|
+
)
|
|
428
|
+
updated_at = entry.get("updatedAt")
|
|
429
|
+
if not isinstance(updated_at, str):
|
|
430
|
+
raise RuntimeError(
|
|
431
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid updatedAt."
|
|
432
|
+
)
|
|
433
|
+
is_draft = entry.get("isDraft")
|
|
434
|
+
if not isinstance(is_draft, bool):
|
|
435
|
+
raise RuntimeError(
|
|
436
|
+
f"Invalid gh {context} PR payload: entry {index} has missing or invalid isDraft."
|
|
437
|
+
)
|
|
438
|
+
pull_requests.append(
|
|
439
|
+
AuthoredPullRequest(
|
|
440
|
+
id=pr_id,
|
|
441
|
+
repo=repository_name_with_owner,
|
|
442
|
+
number=number,
|
|
443
|
+
title=title,
|
|
444
|
+
url=url,
|
|
445
|
+
created_at=created_at,
|
|
446
|
+
updated_at=updated_at,
|
|
447
|
+
is_draft=is_draft,
|
|
448
|
+
)
|
|
449
|
+
)
|
|
450
|
+
return pull_requests
|
|
451
|
+
|
|
452
|
+
@staticmethod
|
|
453
|
+
def _parse_issue_payload(
|
|
454
|
+
payload: object,
|
|
455
|
+
*,
|
|
456
|
+
context: str,
|
|
457
|
+
) -> list[AssignedIssue]:
|
|
458
|
+
if not isinstance(payload, list):
|
|
459
|
+
raise RuntimeError(f"Invalid gh {context} issue payload: expected a JSON array.")
|
|
460
|
+
|
|
461
|
+
issues: list[AssignedIssue] = []
|
|
462
|
+
for index, entry in enumerate(payload):
|
|
463
|
+
if not isinstance(entry, dict):
|
|
464
|
+
raise RuntimeError(
|
|
465
|
+
f"Invalid gh {context} issue payload: entry {index} is not an object."
|
|
466
|
+
)
|
|
467
|
+
repository = entry.get("repository")
|
|
468
|
+
if not isinstance(repository, dict):
|
|
469
|
+
raise RuntimeError(
|
|
470
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid repository."
|
|
471
|
+
)
|
|
472
|
+
repository_name_with_owner = repository.get("nameWithOwner")
|
|
473
|
+
if not isinstance(repository_name_with_owner, str) or not repository_name_with_owner:
|
|
474
|
+
raise RuntimeError(
|
|
475
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid repository.nameWithOwner."
|
|
476
|
+
)
|
|
477
|
+
record_id = entry.get("id")
|
|
478
|
+
if not isinstance(record_id, (str, int)):
|
|
479
|
+
raise RuntimeError(
|
|
480
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid id."
|
|
481
|
+
)
|
|
482
|
+
number = entry.get("number")
|
|
483
|
+
if not isinstance(number, int):
|
|
484
|
+
raise RuntimeError(
|
|
485
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid number."
|
|
486
|
+
)
|
|
487
|
+
title = entry.get("title")
|
|
488
|
+
if not isinstance(title, str):
|
|
489
|
+
raise RuntimeError(
|
|
490
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid title."
|
|
491
|
+
)
|
|
492
|
+
url = entry.get("url")
|
|
493
|
+
if not isinstance(url, str):
|
|
494
|
+
raise RuntimeError(
|
|
495
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid url."
|
|
496
|
+
)
|
|
497
|
+
created_at = entry.get("createdAt")
|
|
498
|
+
if not isinstance(created_at, str):
|
|
499
|
+
raise RuntimeError(
|
|
500
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid createdAt."
|
|
501
|
+
)
|
|
502
|
+
updated_at = entry.get("updatedAt")
|
|
503
|
+
if not isinstance(updated_at, str):
|
|
504
|
+
raise RuntimeError(
|
|
505
|
+
f"Invalid gh {context} issue payload: entry {index} has missing or invalid updatedAt."
|
|
506
|
+
)
|
|
507
|
+
issues.append(
|
|
508
|
+
AssignedIssue(
|
|
509
|
+
id=record_id,
|
|
510
|
+
repo=repository_name_with_owner,
|
|
511
|
+
number=number,
|
|
512
|
+
title=title,
|
|
513
|
+
url=url,
|
|
514
|
+
created_at=created_at,
|
|
515
|
+
updated_at=updated_at,
|
|
516
|
+
)
|
|
517
|
+
)
|
|
518
|
+
return issues
|
|
519
|
+
|
|
520
|
+
def list_open_authored_prs(
|
|
521
|
+
self,
|
|
522
|
+
author_login: str,
|
|
523
|
+
limit: int = _DEFAULT_PR_SEARCH_LIMIT,
|
|
524
|
+
) -> list[AuthoredPullRequest]:
|
|
525
|
+
"""List open authored PRs across accessible repositories.
|
|
526
|
+
|
|
527
|
+
This intentionally does not filter out draft PRs or fork PRs.
|
|
528
|
+
"""
|
|
529
|
+
|
|
530
|
+
command = [
|
|
531
|
+
"gh",
|
|
532
|
+
"search",
|
|
533
|
+
"prs",
|
|
534
|
+
"--author",
|
|
535
|
+
author_login,
|
|
536
|
+
"--state",
|
|
537
|
+
"open",
|
|
538
|
+
"--limit",
|
|
539
|
+
str(limit),
|
|
540
|
+
"--json",
|
|
541
|
+
_PR_JSON_FIELDS,
|
|
542
|
+
]
|
|
543
|
+
completed = _run_gh_command_with_retry(
|
|
544
|
+
command,
|
|
545
|
+
not_found_message=(
|
|
546
|
+
"Failed to run gh authored PR search: gh CLI is not installed or not on PATH."
|
|
547
|
+
),
|
|
548
|
+
failure_message_prefix=(
|
|
549
|
+
f"Failed to list open authored PRs for {author_login!r} via gh"
|
|
550
|
+
),
|
|
551
|
+
)
|
|
552
|
+
try:
|
|
553
|
+
payload = json.loads(completed.stdout)
|
|
554
|
+
except json.JSONDecodeError as error:
|
|
555
|
+
raise RuntimeError(
|
|
556
|
+
f"Failed to parse gh authored PR JSON for {author_login!r}: {error.msg}"
|
|
557
|
+
) from error
|
|
558
|
+
return self._parse_open_pull_request_payload(
|
|
559
|
+
payload,
|
|
560
|
+
context=f"authored for {author_login!r}",
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
def list_open_review_requested_prs(
|
|
564
|
+
self,
|
|
565
|
+
reviewer_login: str,
|
|
566
|
+
limit: int = _DEFAULT_PR_SEARCH_LIMIT,
|
|
567
|
+
progress_callback: Callable[[str], None] | None = None,
|
|
568
|
+
) -> list[ReviewRequestedPullRequest]:
|
|
569
|
+
"""List open PRs where the given user is a requested reviewer."""
|
|
570
|
+
|
|
571
|
+
report_progress = (
|
|
572
|
+
progress_callback if progress_callback is not None else _noop_progress_callback
|
|
573
|
+
)
|
|
574
|
+
command = [
|
|
575
|
+
"gh",
|
|
576
|
+
"search",
|
|
577
|
+
"prs",
|
|
578
|
+
"--review-requested",
|
|
579
|
+
reviewer_login,
|
|
580
|
+
"--state",
|
|
581
|
+
"open",
|
|
582
|
+
"--limit",
|
|
583
|
+
str(limit),
|
|
584
|
+
"--json",
|
|
585
|
+
_PR_JSON_FIELDS,
|
|
586
|
+
]
|
|
587
|
+
completed = _run_gh_command_with_retry(
|
|
588
|
+
command,
|
|
589
|
+
not_found_message=(
|
|
590
|
+
"Failed to run gh review-requested PR search: "
|
|
591
|
+
"gh CLI is not installed or not on PATH."
|
|
592
|
+
),
|
|
593
|
+
failure_message_prefix=(
|
|
594
|
+
f"Failed to list open review-requested PRs for {reviewer_login!r} via gh"
|
|
595
|
+
),
|
|
596
|
+
)
|
|
597
|
+
try:
|
|
598
|
+
payload = json.loads(completed.stdout)
|
|
599
|
+
except json.JSONDecodeError as error:
|
|
600
|
+
raise RuntimeError(
|
|
601
|
+
f"Failed to parse gh review-requested PR JSON for {reviewer_login!r}: {error.msg}"
|
|
602
|
+
) from error
|
|
603
|
+
parsed_items = [
|
|
604
|
+
ReviewRequestedPullRequest(**item)
|
|
605
|
+
for item in self._parse_open_pull_request_payload(
|
|
606
|
+
payload,
|
|
607
|
+
context=f"review-requested for {reviewer_login!r}",
|
|
608
|
+
)
|
|
609
|
+
]
|
|
610
|
+
direct_review_requested_items: list[ReviewRequestedPullRequest] = []
|
|
611
|
+
normalized_reviewer_login = reviewer_login.strip().lower()
|
|
612
|
+
for item in parsed_items:
|
|
613
|
+
review_request_command = [
|
|
614
|
+
"gh",
|
|
615
|
+
"pr",
|
|
616
|
+
"view",
|
|
617
|
+
str(item["number"]),
|
|
618
|
+
"--repo",
|
|
619
|
+
item["repo"],
|
|
620
|
+
"--json",
|
|
621
|
+
"reviewRequests",
|
|
622
|
+
]
|
|
623
|
+
try:
|
|
624
|
+
review_request_completed = _run_gh_command_with_retry(
|
|
625
|
+
review_request_command,
|
|
626
|
+
not_found_message=(
|
|
627
|
+
"Failed to run gh review-request metadata lookup: "
|
|
628
|
+
"gh CLI is not installed or not on PATH."
|
|
629
|
+
),
|
|
630
|
+
failure_message_prefix=(
|
|
631
|
+
"Failed to inspect review-request metadata for "
|
|
632
|
+
f"{item['repo']}#{item['number']} via gh"
|
|
633
|
+
),
|
|
634
|
+
classify_repository_authorization=True,
|
|
635
|
+
)
|
|
636
|
+
except RepositoryAuthorizationError as error:
|
|
637
|
+
report_progress(
|
|
638
|
+
"Warning: skipped review-requested pull request "
|
|
639
|
+
f"{item['repo']}#{item['number']} because GitHub denied access: {error}"
|
|
640
|
+
)
|
|
641
|
+
continue
|
|
642
|
+
try:
|
|
643
|
+
review_request_payload = json.loads(review_request_completed.stdout)
|
|
644
|
+
except json.JSONDecodeError as error:
|
|
645
|
+
raise RuntimeError(
|
|
646
|
+
"Failed to parse gh review-request metadata JSON for "
|
|
647
|
+
f"{item['repo']}#{item['number']}: {error.msg}"
|
|
648
|
+
) from error
|
|
649
|
+
if not isinstance(review_request_payload, dict):
|
|
650
|
+
raise RuntimeError(
|
|
651
|
+
"Invalid gh review-request metadata payload for "
|
|
652
|
+
f"{item['repo']}#{item['number']}: expected an object."
|
|
653
|
+
)
|
|
654
|
+
review_requests = review_request_payload.get("reviewRequests")
|
|
655
|
+
if not isinstance(review_requests, list):
|
|
656
|
+
raise RuntimeError(
|
|
657
|
+
"Invalid gh review-request metadata payload for "
|
|
658
|
+
f"{item['repo']}#{item['number']}: missing or invalid reviewRequests."
|
|
659
|
+
)
|
|
660
|
+
has_direct_request = False
|
|
661
|
+
for request in review_requests:
|
|
662
|
+
if not isinstance(request, dict):
|
|
663
|
+
continue
|
|
664
|
+
if request.get("__typename") != "User":
|
|
665
|
+
continue
|
|
666
|
+
login = request.get("login")
|
|
667
|
+
if isinstance(login, str) and login.strip().lower() == normalized_reviewer_login:
|
|
668
|
+
has_direct_request = True
|
|
669
|
+
break
|
|
670
|
+
if has_direct_request:
|
|
671
|
+
direct_review_requested_items.append(item)
|
|
672
|
+
return direct_review_requested_items
|
|
673
|
+
|
|
674
|
+
def list_open_reviewed_prs(
|
|
675
|
+
self,
|
|
676
|
+
reviewer_login: str,
|
|
677
|
+
limit: int = _DEFAULT_PR_SEARCH_LIMIT,
|
|
678
|
+
) -> list[ReviewRequestedPullRequest]:
|
|
679
|
+
"""List open PRs that the given user has already reviewed."""
|
|
680
|
+
|
|
681
|
+
command = [
|
|
682
|
+
"gh",
|
|
683
|
+
"search",
|
|
684
|
+
"prs",
|
|
685
|
+
"--reviewed-by",
|
|
686
|
+
reviewer_login,
|
|
687
|
+
"--state",
|
|
688
|
+
"open",
|
|
689
|
+
"--limit",
|
|
690
|
+
str(limit),
|
|
691
|
+
"--json",
|
|
692
|
+
_PR_JSON_FIELDS,
|
|
693
|
+
]
|
|
694
|
+
completed = _run_gh_command_with_retry(
|
|
695
|
+
command,
|
|
696
|
+
not_found_message=(
|
|
697
|
+
"Failed to run gh reviewed PR search: gh CLI is not installed or not on PATH."
|
|
698
|
+
),
|
|
699
|
+
failure_message_prefix=(
|
|
700
|
+
f"Failed to list open reviewed PRs for {reviewer_login!r} via gh"
|
|
701
|
+
),
|
|
702
|
+
)
|
|
703
|
+
try:
|
|
704
|
+
payload = json.loads(completed.stdout)
|
|
705
|
+
except json.JSONDecodeError as error:
|
|
706
|
+
raise RuntimeError(
|
|
707
|
+
f"Failed to parse gh reviewed PR JSON for {reviewer_login!r}: {error.msg}"
|
|
708
|
+
) from error
|
|
709
|
+
return [
|
|
710
|
+
ReviewRequestedPullRequest(**item)
|
|
711
|
+
for item in self._parse_open_pull_request_payload(
|
|
712
|
+
payload,
|
|
713
|
+
context=f"reviewed for {reviewer_login!r}",
|
|
714
|
+
)
|
|
715
|
+
]
|
|
716
|
+
|
|
717
|
+
def list_open_assigned_issues(
|
|
718
|
+
self,
|
|
719
|
+
assignee_login: str,
|
|
720
|
+
limit: int = _DEFAULT_ASSIGNED_ISSUE_LIMIT,
|
|
721
|
+
) -> list[AssignedIssue]:
|
|
722
|
+
"""List open issues assigned to the given user, most recently updated first."""
|
|
723
|
+
|
|
724
|
+
command = [
|
|
725
|
+
"gh",
|
|
726
|
+
"search",
|
|
727
|
+
"issues",
|
|
728
|
+
"--assignee",
|
|
729
|
+
assignee_login,
|
|
730
|
+
"--state",
|
|
731
|
+
"open",
|
|
732
|
+
"--sort",
|
|
733
|
+
"updated",
|
|
734
|
+
"--order",
|
|
735
|
+
"desc",
|
|
736
|
+
"--limit",
|
|
737
|
+
str(limit),
|
|
738
|
+
"--json",
|
|
739
|
+
_ISSUE_JSON_FIELDS,
|
|
740
|
+
]
|
|
741
|
+
completed = _run_gh_command_with_retry(
|
|
742
|
+
command,
|
|
743
|
+
not_found_message=(
|
|
744
|
+
"Failed to run gh assigned issue search: gh CLI is not installed or not on PATH."
|
|
745
|
+
),
|
|
746
|
+
failure_message_prefix=(
|
|
747
|
+
f"Failed to list open assigned issues for {assignee_login!r} via gh"
|
|
748
|
+
),
|
|
749
|
+
)
|
|
750
|
+
try:
|
|
751
|
+
payload = json.loads(completed.stdout)
|
|
752
|
+
except json.JSONDecodeError as error:
|
|
753
|
+
raise RuntimeError(
|
|
754
|
+
f"Failed to parse gh assigned issue JSON for {assignee_login!r}: {error.msg}"
|
|
755
|
+
) from error
|
|
756
|
+
return self._parse_issue_payload(
|
|
757
|
+
payload,
|
|
758
|
+
context=f"assigned for {assignee_login!r}",
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
def list_recent_tracked_items(
|
|
762
|
+
self,
|
|
763
|
+
repositories: list[str],
|
|
764
|
+
limit: int = _DEFAULT_RECENT_SEARCH_LIMIT,
|
|
765
|
+
progress_callback: Callable[[str], None] | None = None,
|
|
766
|
+
) -> list[RecentTrackedItem]:
|
|
767
|
+
report_progress = (
|
|
768
|
+
progress_callback if progress_callback is not None else _noop_progress_callback
|
|
769
|
+
)
|
|
770
|
+
if not repositories:
|
|
771
|
+
return []
|
|
772
|
+
|
|
773
|
+
deduped_repositories = list(dict.fromkeys(repositories))
|
|
774
|
+
if not deduped_repositories:
|
|
775
|
+
return []
|
|
776
|
+
|
|
777
|
+
batch_count = (
|
|
778
|
+
len(deduped_repositories) + _RECENT_QUALIFIER_BATCH_SIZE - 1
|
|
779
|
+
) // _RECENT_QUALIFIER_BATCH_SIZE
|
|
780
|
+
report_progress(
|
|
781
|
+
f"Prepared {len(deduped_repositories)} repository filter(s) across {batch_count} batch(es)."
|
|
782
|
+
)
|
|
783
|
+
items: list[RecentTrackedItem] = []
|
|
784
|
+
seen_keys: set[tuple[str, int, bool]] = set()
|
|
785
|
+
for batch_start in range(0, len(deduped_repositories), _RECENT_QUALIFIER_BATCH_SIZE):
|
|
786
|
+
batch_number = (batch_start // _RECENT_QUALIFIER_BATCH_SIZE) + 1
|
|
787
|
+
repository_batch = deduped_repositories[
|
|
788
|
+
batch_start : batch_start + _RECENT_QUALIFIER_BATCH_SIZE
|
|
789
|
+
]
|
|
790
|
+
report_progress(
|
|
791
|
+
f"Querying recent items batch {batch_number}/{batch_count} for: {', '.join(repository_batch)}"
|
|
792
|
+
)
|
|
793
|
+
completed_batches: list[tuple[list[str], subprocess.CompletedProcess[str]]] = []
|
|
794
|
+
try:
|
|
795
|
+
completed_batches.append(
|
|
796
|
+
(
|
|
797
|
+
repository_batch,
|
|
798
|
+
self._run_recent_tracked_items_search(
|
|
799
|
+
repository_batch,
|
|
800
|
+
limit=limit,
|
|
801
|
+
report_progress=report_progress,
|
|
802
|
+
retry_label=f"Batch {batch_number}/{batch_count}",
|
|
803
|
+
),
|
|
804
|
+
)
|
|
805
|
+
)
|
|
806
|
+
except RepositoryAuthorizationError as error:
|
|
807
|
+
if len(repository_batch) == 1:
|
|
808
|
+
report_progress(
|
|
809
|
+
"Warning: skipped repository "
|
|
810
|
+
f"{repository_batch[0]} because GitHub denied access: {error}"
|
|
811
|
+
)
|
|
812
|
+
continue
|
|
813
|
+
report_progress(
|
|
814
|
+
"A repository in this batch needs additional GitHub "
|
|
815
|
+
"authorization; checking repositories individually."
|
|
816
|
+
)
|
|
817
|
+
for repository in repository_batch:
|
|
818
|
+
try:
|
|
819
|
+
completed_batches.append(
|
|
820
|
+
(
|
|
821
|
+
[repository],
|
|
822
|
+
self._run_recent_tracked_items_search(
|
|
823
|
+
[repository],
|
|
824
|
+
limit=limit,
|
|
825
|
+
report_progress=report_progress,
|
|
826
|
+
retry_label=f"Repository {repository}",
|
|
827
|
+
),
|
|
828
|
+
)
|
|
829
|
+
)
|
|
830
|
+
except RepositoryAuthorizationError as single_error:
|
|
831
|
+
report_progress(
|
|
832
|
+
"Warning: skipped repository "
|
|
833
|
+
f"{repository} because GitHub denied access: {single_error}"
|
|
834
|
+
)
|
|
835
|
+
continue
|
|
836
|
+
|
|
837
|
+
for payload_repositories, completed in completed_batches:
|
|
838
|
+
try:
|
|
839
|
+
payload = json.loads(completed.stdout)
|
|
840
|
+
except json.JSONDecodeError as error:
|
|
841
|
+
raise RuntimeError(
|
|
842
|
+
"Failed to parse gh recent tracked item JSON for repository batch "
|
|
843
|
+
f"{payload_repositories!r}: {error.msg}"
|
|
844
|
+
) from error
|
|
845
|
+
if not isinstance(payload, list):
|
|
846
|
+
raise RuntimeError(
|
|
847
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
848
|
+
f"{payload_repositories!r}: expected a JSON array."
|
|
849
|
+
)
|
|
850
|
+
|
|
851
|
+
# TODO(EVO-011): recent tracked item payload validation is repetitive;
|
|
852
|
+
# consider a structured parser/helper that preserves these precise
|
|
853
|
+
# error messages while reducing the long sequence of type checks.
|
|
854
|
+
for index, entry in enumerate(payload):
|
|
855
|
+
if not isinstance(entry, dict):
|
|
856
|
+
raise RuntimeError(
|
|
857
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
858
|
+
f"{payload_repositories!r}: entry {index} is not an object."
|
|
859
|
+
)
|
|
860
|
+
record_id = entry.get("id")
|
|
861
|
+
if not isinstance(record_id, (str, int)):
|
|
862
|
+
raise RuntimeError(
|
|
863
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
864
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid id."
|
|
865
|
+
)
|
|
866
|
+
number = entry.get("number")
|
|
867
|
+
if not isinstance(number, int):
|
|
868
|
+
raise RuntimeError(
|
|
869
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
870
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid number."
|
|
871
|
+
)
|
|
872
|
+
title = entry.get("title")
|
|
873
|
+
if not isinstance(title, str):
|
|
874
|
+
raise RuntimeError(
|
|
875
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
876
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid title."
|
|
877
|
+
)
|
|
878
|
+
url = entry.get("url")
|
|
879
|
+
if not isinstance(url, str):
|
|
880
|
+
raise RuntimeError(
|
|
881
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
882
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid url."
|
|
883
|
+
)
|
|
884
|
+
created_at = entry.get("createdAt")
|
|
885
|
+
if not isinstance(created_at, str):
|
|
886
|
+
raise RuntimeError(
|
|
887
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
888
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid createdAt."
|
|
889
|
+
)
|
|
890
|
+
updated_at = entry.get("updatedAt")
|
|
891
|
+
if not isinstance(updated_at, str):
|
|
892
|
+
raise RuntimeError(
|
|
893
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
894
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid updatedAt."
|
|
895
|
+
)
|
|
896
|
+
state = entry.get("state")
|
|
897
|
+
if not isinstance(state, str):
|
|
898
|
+
raise RuntimeError(
|
|
899
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
900
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid state."
|
|
901
|
+
)
|
|
902
|
+
is_pull_request = entry.get("isPullRequest")
|
|
903
|
+
if not isinstance(is_pull_request, bool):
|
|
904
|
+
raise RuntimeError(
|
|
905
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
906
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid isPullRequest."
|
|
907
|
+
)
|
|
908
|
+
repository = entry.get("repository")
|
|
909
|
+
if not isinstance(repository, dict):
|
|
910
|
+
raise RuntimeError(
|
|
911
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
912
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid repository."
|
|
913
|
+
)
|
|
914
|
+
repository_name_with_owner = repository.get("nameWithOwner")
|
|
915
|
+
if (
|
|
916
|
+
not isinstance(repository_name_with_owner, str)
|
|
917
|
+
or not repository_name_with_owner
|
|
918
|
+
):
|
|
919
|
+
raise RuntimeError(
|
|
920
|
+
"Invalid gh recent tracked item payload for repository batch "
|
|
921
|
+
f"{payload_repositories!r}: entry {index} has missing or invalid repository.nameWithOwner."
|
|
922
|
+
)
|
|
923
|
+
if state.upper() != "OPEN":
|
|
924
|
+
continue
|
|
925
|
+
dedupe_key = (repository_name_with_owner, number, is_pull_request)
|
|
926
|
+
if dedupe_key in seen_keys:
|
|
927
|
+
continue
|
|
928
|
+
seen_keys.add(dedupe_key)
|
|
929
|
+
items.append(
|
|
930
|
+
RecentTrackedItem(
|
|
931
|
+
id=record_id,
|
|
932
|
+
repo=repository_name_with_owner,
|
|
933
|
+
number=number,
|
|
934
|
+
title=title,
|
|
935
|
+
url=url,
|
|
936
|
+
created_at=created_at,
|
|
937
|
+
updated_at=updated_at,
|
|
938
|
+
is_pull_request=is_pull_request,
|
|
939
|
+
)
|
|
940
|
+
)
|
|
941
|
+
report_progress(
|
|
942
|
+
f"Processed batch {batch_number}/{batch_count}; accumulated {len(items)} unique item(s)."
|
|
943
|
+
)
|
|
944
|
+
return items
|
|
945
|
+
|
|
946
|
+
def _run_recent_tracked_items_search(
|
|
947
|
+
self,
|
|
948
|
+
repositories: list[str],
|
|
949
|
+
*,
|
|
950
|
+
limit: int,
|
|
951
|
+
report_progress: Callable[[str], None],
|
|
952
|
+
retry_label: str,
|
|
953
|
+
) -> subprocess.CompletedProcess[str]:
|
|
954
|
+
command = [
|
|
955
|
+
"gh",
|
|
956
|
+
"search",
|
|
957
|
+
"issues",
|
|
958
|
+
"--include-prs",
|
|
959
|
+
"--state",
|
|
960
|
+
"open",
|
|
961
|
+
"--limit",
|
|
962
|
+
str(limit),
|
|
963
|
+
"--json",
|
|
964
|
+
_RECENT_JSON_FIELDS,
|
|
965
|
+
]
|
|
966
|
+
for repository in repositories:
|
|
967
|
+
command.extend(["--repo", repository])
|
|
968
|
+
return _run_gh_command_with_retry(
|
|
969
|
+
command,
|
|
970
|
+
not_found_message=(
|
|
971
|
+
"Failed to run gh recent tracked item search: "
|
|
972
|
+
"gh CLI is not installed or not on PATH."
|
|
973
|
+
),
|
|
974
|
+
failure_message_prefix=(
|
|
975
|
+
f"Failed to list recent tracked items for repository batch {repositories!r} via gh"
|
|
976
|
+
),
|
|
977
|
+
report_progress=report_progress,
|
|
978
|
+
retry_label=retry_label,
|
|
979
|
+
classify_repository_authorization=True,
|
|
980
|
+
)
|
|
981
|
+
|
|
982
|
+
def fetch_item_by_url(self, parsed_url: ParsedGitHubItemURL) -> WorkItem | None:
|
|
983
|
+
"""Fetch a single issue or pull request described by ``parsed_url``.
|
|
984
|
+
|
|
985
|
+
Returns a ``WorkItem`` when the item is OPEN. Returns ``None`` for
|
|
986
|
+
permanent-drop cases: state != OPEN (closed/merged) or a permanent
|
|
987
|
+
``gh`` error (e.g. 404 not-found). Raises ``TransientFetchError``
|
|
988
|
+
on retryable failures (5xx, 429, common network errors, missing
|
|
989
|
+
``gh`` binary, malformed JSON) so callers can retain the URL for
|
|
990
|
+
a later retry.
|
|
991
|
+
"""
|
|
992
|
+
|
|
993
|
+
kind_subcommand = "pr" if parsed_url.item_type == WorkItemType.PR else "issue"
|
|
994
|
+
command = [
|
|
995
|
+
"gh",
|
|
996
|
+
kind_subcommand,
|
|
997
|
+
"view",
|
|
998
|
+
str(parsed_url.number),
|
|
999
|
+
"--repo",
|
|
1000
|
+
parsed_url.repo,
|
|
1001
|
+
"--json",
|
|
1002
|
+
"number,title,url,createdAt,updatedAt,state",
|
|
1003
|
+
]
|
|
1004
|
+
try:
|
|
1005
|
+
completed = _run_gh_command_with_retry(
|
|
1006
|
+
command,
|
|
1007
|
+
not_found_message=(
|
|
1008
|
+
"Failed to run gh item view: gh CLI is not installed or not on PATH."
|
|
1009
|
+
),
|
|
1010
|
+
failure_message_prefix=(
|
|
1011
|
+
f"Failed to view {parsed_url.item_type.value} "
|
|
1012
|
+
f"{parsed_url.repo}#{parsed_url.number} via gh"
|
|
1013
|
+
),
|
|
1014
|
+
)
|
|
1015
|
+
except TransientFetchError:
|
|
1016
|
+
raise
|
|
1017
|
+
except RuntimeError:
|
|
1018
|
+
# Permanent error (e.g. 404 "not found", bad auth). Treat as gone
|
|
1019
|
+
# so the caller drops the URL from the store.
|
|
1020
|
+
return None
|
|
1021
|
+
# Malformed responses from gh are treated as transient so a botched
|
|
1022
|
+
# upstream response does not silently prune a valid URL from the store.
|
|
1023
|
+
try:
|
|
1024
|
+
payload = json.loads(completed.stdout)
|
|
1025
|
+
except json.JSONDecodeError as error:
|
|
1026
|
+
raise TransientFetchError(
|
|
1027
|
+
f"Malformed gh view JSON for {parsed_url.repo}#{parsed_url.number}: {error.msg}"
|
|
1028
|
+
) from error
|
|
1029
|
+
if not isinstance(payload, dict):
|
|
1030
|
+
raise TransientFetchError(
|
|
1031
|
+
f"Malformed gh view payload for {parsed_url.repo}#{parsed_url.number}: "
|
|
1032
|
+
"expected an object."
|
|
1033
|
+
)
|
|
1034
|
+
state = payload.get("state")
|
|
1035
|
+
if not isinstance(state, str):
|
|
1036
|
+
raise TransientFetchError(
|
|
1037
|
+
f"Malformed gh view payload for {parsed_url.repo}#{parsed_url.number}: "
|
|
1038
|
+
"missing state."
|
|
1039
|
+
)
|
|
1040
|
+
if state.upper() != "OPEN":
|
|
1041
|
+
return None
|
|
1042
|
+
title = payload.get("title")
|
|
1043
|
+
url = payload.get("url")
|
|
1044
|
+
created_at = payload.get("createdAt")
|
|
1045
|
+
updated_at = payload.get("updatedAt")
|
|
1046
|
+
if not (
|
|
1047
|
+
isinstance(title, str)
|
|
1048
|
+
and isinstance(url, str)
|
|
1049
|
+
and isinstance(created_at, str)
|
|
1050
|
+
and isinstance(updated_at, str)
|
|
1051
|
+
):
|
|
1052
|
+
raise TransientFetchError(
|
|
1053
|
+
f"Malformed gh view payload for {parsed_url.repo}#{parsed_url.number}: "
|
|
1054
|
+
"missing required fields."
|
|
1055
|
+
)
|
|
1056
|
+
# Convert parse errors into TransientFetchError so the included-items
|
|
1057
|
+
# store keeps the URL for a later retry instead of aborting the refresh
|
|
1058
|
+
# (other callers of parse_github_datetime still want the plain RuntimeError).
|
|
1059
|
+
try:
|
|
1060
|
+
created_at_parsed = parse_github_datetime(created_at)
|
|
1061
|
+
updated_at_parsed = parse_github_datetime(updated_at)
|
|
1062
|
+
except RuntimeError as error:
|
|
1063
|
+
raise TransientFetchError(
|
|
1064
|
+
f"gh payload contains invalid timestamp for "
|
|
1065
|
+
f"{parsed_url.repo}#{parsed_url.number}: {error}"
|
|
1066
|
+
) from error
|
|
1067
|
+
return WorkItem(
|
|
1068
|
+
kind=WorkItemKind.TRACKED_PR
|
|
1069
|
+
if parsed_url.item_type == WorkItemType.PR
|
|
1070
|
+
else WorkItemKind.TRACKED_ISSUE,
|
|
1071
|
+
item_type=parsed_url.item_type,
|
|
1072
|
+
repo=parsed_url.repo,
|
|
1073
|
+
number=parsed_url.number,
|
|
1074
|
+
title=title,
|
|
1075
|
+
created_at=created_at_parsed,
|
|
1076
|
+
updated_at=updated_at_parsed,
|
|
1077
|
+
url=url,
|
|
1078
|
+
included=True,
|
|
1079
|
+
)
|