lib/utils/github.py

131 lines · 4425 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 repo_status(owner, repo, token, session=None, timeout=DEFAULT_TIMEOUT):
 71    """Return the HTTP status code for a repo, or None on transport error."""
 72    session = session or make_session()
 73    headers = {"Accept": "application/vnd.github.v3+json"}
 74    if token:
 75        headers["Authorization"] = f"token {token}"
 76    try:
 77        resp = session.get(
 78            f"https://api.github.com/repos/{owner}/{repo}",
 79            headers=headers, timeout=timeout,
 80        )
 81        return resp.status_code
 82    except Exception as exc:
 83        logging.warning("[repo-status] request error for %s/%s: %s", owner, repo, exc)
 84        return None
 85
 86
 87def commit_has_bot(commit, bot_set):
 88    """Return True if a commit was authored or co-authored by a known AI bot."""
 89    author = commit.get("commit", {}).get("author", {})
 90    email = (author.get("email") or "").lower()
 91    name = (author.get("name") or "").lower()
 92    if email in bot_set or name in bot_set:
 93        return True
 94    message = (commit.get("commit", {}).get("message") or "").lower()
 95    for line in message.splitlines():
 96        if line.strip().startswith("co-authored-by:"):
 97            if any(bot in line for bot in bot_set):
 98                return True
 99    return False
100
101
102def _days_since(iso_str):
103    if not iso_str:
104        return None
105    try:
106        dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
107    except (ValueError, AttributeError):
108        return None
109    return (datetime.now(timezone.utc) - dt).days
110
111
112def repo_is_fork(data):
113    return bool(data and data.get("fork"))
114
115
116def repo_is_archived(data):
117    return bool(data and data.get("archived"))
118
119
120def repo_has_license(data):
121    return bool(data and data.get("license"))
122
123
124def repo_pushed_days_ago(data):
125    """Days since last push, or None if unknown."""
126    return _days_since(data.get("pushed_at")) if data else None
127
128
129def repo_age_days(data):
130    """Days since repo creation, or None if unknown."""
131    return _days_since(data.get("created_at")) if data else None