lib/utils/github.py
114 lines · 3783 bytes
1"""GitHub API helpers and read-only accessors for repo metadata."""
2
3import logging
4from datetime import datetime, timezone
5
6import requests
7
8from .http import DEFAULT_TIMEOUT, make_session
9
10AI_BOT_AUTHORS = [
11 "noreply@anthropic.com",
12 "devin-ai-integration[bot]",
13 "copilot-swe-agent.github.com",
14 "noreply@cursor.com",
15]
16
17
18def parse_github_field(value):
19 """Parse a `github` field into (owner, repo), or (None, None) on failure."""
20 if not value:
21 return None, None
22 if value.startswith("https://github.com/"):
23 parts = value.removeprefix("https://github.com/").strip("/").split("/")
24 if len(parts) >= 2 and parts[0] and parts[1]:
25 return parts[0], parts[1]
26 return None, None
27 if "/" in value:
28 parts = value.split("/")
29 if len(parts) == 2 and parts[0] and parts[1]:
30 return parts[0], parts[1]
31 return None, None
32
33
34def gh_get(path, token, session=None, params=None, timeout=DEFAULT_TIMEOUT, label=""):
35 """GET https://api.github.com{path}. Returns parsed JSON on 200, else None.
36
37 Catches any exception raised during the request or JSON decode, so callers
38 can treat None as a generic failure signal without needing their own guard.
39 """
40 session = session or make_session()
41 headers = {"Accept": "application/vnd.github.v3+json"}
42 if token:
43 headers["Authorization"] = f"token {token}"
44 try:
45 resp = session.get(
46 f"https://api.github.com{path}",
47 headers=headers, params=params, timeout=timeout,
48 )
49 remaining = resp.headers.get("X-RateLimit-Remaining")
50 if remaining is not None:
51 try:
52 if int(remaining) < 100:
53 logging.warning("[%s] GitHub rate limit low: %s/%s remaining",
54 label, remaining, resp.headers.get("X-RateLimit-Limit"))
55 except ValueError:
56 pass
57 if resp.status_code == 200:
58 return resp.json()
59 logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path)
60 except Exception as exc:
61 logging.warning("[%s] request error for %s: %s", label, path, exc)
62 return None
63
64
65def fetch_repo(owner, repo, token, session=None):
66 """Fetch GitHub repo metadata, returning None on any error."""
67 return gh_get(f"/repos/{owner}/{repo}", token, session=session, label="repos")
68
69
70def commit_has_bot(commit, bot_set):
71 """Return True if a commit was authored or co-authored by a known AI bot."""
72 author = commit.get("commit", {}).get("author", {})
73 email = (author.get("email") or "").lower()
74 name = (author.get("name") or "").lower()
75 if email in bot_set or name in bot_set:
76 return True
77 message = (commit.get("commit", {}).get("message") or "").lower()
78 for line in message.splitlines():
79 if line.strip().startswith("co-authored-by:"):
80 if any(bot in line for bot in bot_set):
81 return True
82 return False
83
84
85def _days_since(iso_str):
86 if not iso_str:
87 return None
88 try:
89 dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
90 except (ValueError, AttributeError):
91 return None
92 return (datetime.now(timezone.utc) - dt).days
93
94
95def repo_is_fork(data):
96 return bool(data and data.get("fork"))
97
98
99def repo_is_archived(data):
100 return bool(data and data.get("archived"))
101
102
103def repo_has_license(data):
104 return bool(data and data.get("license"))
105
106
107def repo_pushed_days_ago(data):
108 """Days since last push, or None if unknown."""
109 return _days_since(data.get("pushed_at")) if data else None
110
111
112def repo_age_days(data):
113 """Days since repo creation, or None if unknown."""
114 return _days_since(data.get("created_at")) if data else None