lib/utils/github.py
200 lines · 7567 bytes
15 symbols in this file
1"""GitHub API helpers and read-only accessors for repo metadata."""
2
3import logging
4import re
5from datetime import datetime, timezone
6
7import requests
8
9from .http import DEFAULT_TIMEOUT, make_session
10
11# List of dirty AI users, we don't count them as real people because they have no soul
12AI_BOT_AUTHORS = [
13 "noreply@anthropic.com",
14 "devin-ai-integration[bot]",
15 "copilot-swe-agent.github.com",
16 "noreply@cursor.com",
17]
18
19AI_CONTRIBUTOR_LOGINS = {"cursoragent", "openhands-agent"}
20_BOT_LOGIN_RE = re.compile(r"[-_]bot$|\[bot\]$")
21
22
23def parse_github_field(value):
24 """Parse a `github` field into (owner, repo), or (None, None) on failure."""
25 if not value:
26 return None, None
27 if value.startswith("https://github.com/"):
28 parts = value.removeprefix("https://github.com/").strip("/").split("/")
29 if len(parts) >= 2 and parts[0] and parts[1]:
30 return parts[0], parts[1]
31 return None, None
32 if "/" in value:
33 parts = value.split("/")
34 if len(parts) == 2 and parts[0] and parts[1]:
35 return parts[0], parts[1]
36 return None, None
37
38
39def gh_get(path, token, session=None, params=None, timeout=DEFAULT_TIMEOUT, label=""):
40 """GET https://api.github.com{path}. Returns parsed JSON on 200, else None.
41
42 Catches any exception raised during the request or JSON decode, so callers
43 can treat None as a generic failure signal without needing their own guard.
44 """
45 session = session or make_session()
46 headers = {"Accept": "application/vnd.github.v3+json"}
47 if token:
48 headers["Authorization"] = f"token {token}"
49 try:
50 resp = session.get(
51 f"https://api.github.com{path}",
52 headers=headers, params=params, timeout=timeout,
53 )
54 remaining = resp.headers.get("X-RateLimit-Remaining")
55 if remaining is not None:
56 try:
57 if int(remaining) < 100:
58 logging.warning("[%s] GitHub rate limit low: %s/%s remaining",
59 label, remaining, resp.headers.get("X-RateLimit-Limit"))
60 except ValueError:
61 pass
62 if resp.status_code == 200:
63 return resp.json()
64 logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path)
65 except Exception as exc:
66 logging.warning("[%s] request error for %s: %s", label, path, exc)
67 return None
68
69
70def _gh_graphql(query, variables, token, session=None, timeout=DEFAULT_TIMEOUT, label=""):
71 """POST a GitHub GraphQL query. Returns the `data` dict, else None (needs a token)"""
72 if not token:
73 return None
74 session = session or make_session()
75 try:
76 resp = session.post(
77 "https://api.github.com/graphql",
78 headers={"Authorization": f"bearer {token}"},
79 json={"query": query, "variables": variables}, timeout=timeout
80 )
81 body = resp.json() if resp.status_code == 200 else {}
82 if isinstance(body.get("data"), dict) and not body.get("errors"):
83 return body["data"]
84 logging.warning("[%s] GraphQL HTTP %d: %s", label, resp.status_code, body.get("errors"))
85 except Exception as exc:
86 logging.warning("[%s] GraphQL request error: %s", label, exc)
87 return None
88
89
90def fetch_repo(owner, repo, token, session=None):
91 """Fetch GitHub repo metadata, returning None on any error."""
92 return gh_get(f"/repos/{owner}/{repo}", token, session=session, label="repos")
93
94
95def repo_status(owner, repo, token, session=None, timeout=DEFAULT_TIMEOUT):
96 """Return the HTTP status code for a repo, or None on transport error."""
97 session = session or make_session()
98 headers = {"Accept": "application/vnd.github.v3+json"}
99 if token:
100 headers["Authorization"] = f"token {token}"
101 try:
102 resp = session.get(
103 f"https://api.github.com/repos/{owner}/{repo}",
104 headers=headers, timeout=timeout,
105 )
106 return resp.status_code
107 except Exception as exc:
108 logging.warning("[repo-status] request error for %s/%s: %s", owner, repo, exc)
109 return None
110
111
112def commit_has_bot(commit, bot_set):
113 """Return True if a commit was authored or co-authored by a known AI bot."""
114 author = commit.get("commit", {}).get("author", {})
115 email = (author.get("email") or "").lower()
116 name = (author.get("name") or "").lower()
117 if email in bot_set or name in bot_set:
118 return True
119 message = (commit.get("commit", {}).get("message") or "").lower()
120 for line in message.splitlines():
121 if line.strip().startswith("co-authored-by:"):
122 if any(bot in line for bot in bot_set):
123 return True
124 return False
125
126
127def _is_human_contributor(contributor):
128 """Return True unless a contributor is a bot, automation account or AI agent."""
129 login = (contributor.get("login") or "").lower()
130 return (contributor.get("type") == "User"
131 and login not in AI_CONTRIBUTOR_LOGINS
132 and not _BOT_LOGIN_RE.search(login))
133
134
135def top_contributor_share(owner, repo, token, session=None, timeout=DEFAULT_TIMEOUT):
136 """Share of commits (0 to 1) by the top human contributor, ignoring bots and AI"""
137 contributors = gh_get(f"/repos/{owner}/{repo}/contributors", token, session=session,
138 params={"per_page": 100}, timeout=timeout, label="contributors")
139 if not isinstance(contributors, list) or len(contributors) >= 100:
140 return None
141 try:
142 counts = [c["contributions"] for c in contributors if _is_human_contributor(c)]
143 return max(counts) / sum(counts) if counts else None
144 except Exception as exc:
145 logging.warning("[contributors] unexpected data for %s/%s: %s", owner, repo, exc)
146 return None
147
148
149_SECURITY_POLICY_QUERY = (
150 "query($owner: String!, $name: String!) {"
151 " repository(owner: $owner, name: $name) { isSecurityPolicyEnabled } }"
152)
153
154
155def has_security_contact(owner, repo, token, session=None, timeout=DEFAULT_TIMEOUT):
156 """True if a repo has private vulnerability reporting or a security policy"""
157 pvr = gh_get(f"/repos/{owner}/{repo}/private-vulnerability-reporting", token,
158 session=session, timeout=timeout, label="pvr")
159 pvr = pvr.get("enabled") if isinstance(pvr, dict) else None
160 if pvr is True:
161 return True
162 data = _gh_graphql(_SECURITY_POLICY_QUERY, {"owner": owner, "name": repo}, token,
163 session=session, timeout=timeout, label="security-policy")
164 repo_data = data.get("repository") if data else None
165 policy = repo_data.get("isSecurityPolicyEnabled") if isinstance(repo_data, dict) else None
166 if policy is True:
167 return True
168 return False if pvr is False and policy is False else None
169
170
171def _days_since(iso_str):
172 if not iso_str:
173 return None
174 try:
175 dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
176 except (ValueError, AttributeError):
177 return None
178 return (datetime.now(timezone.utc) - dt).days
179
180
181def repo_is_fork(data):
182 return bool(data and data.get("fork"))
183
184
185def repo_is_archived(data):
186 return bool(data and data.get("archived"))
187
188
189def repo_has_license(data):
190 return bool(data and data.get("license"))
191
192
193def repo_pushed_days_ago(data):
194 """Days since last push, or None if unknown."""
195 return _days_since(data.get("pushed_at")) if data else None
196
197
198def repo_age_days(data):
199 """Days since repo creation, or None if unknown."""
200 return _days_since(data.get("created_at")) if data else None