From dc6de9c2a954b202f1da83a83e7594c807c0983f Mon Sep 17 00:00:00 2001 From: shay Date: Wed, 18 Feb 2026 13:56:34 -0500 Subject: [PATCH] feat(fetcher): add fetcher to get and process the github data --- src/data/fetcher.py | 295 +++++++++++++++++++++++++++++++++++++----- src/data/processor.py | 123 ++++++++++++++---- src/generate.py | 12 +- 3 files changed, 374 insertions(+), 56 deletions(-) diff --git a/src/data/fetcher.py b/src/data/fetcher.py index 7f074e7..b842c30 100644 --- a/src/data/fetcher.py +++ b/src/data/fetcher.py @@ -2,50 +2,283 @@ import requests import base64 -from typing import Optional +from typing import Optional, Protocol + +from ..config import ( + COLLABORATOR_MIN_COMMITS, + COLLABORATOR_MAX_REPO_SIZE, + COLLABORATOR_TOP_REPOS, + COMMIT_MAX_REPOS, + COMMIT_PER_REPO, + API_TIMEOUT, +) -def fetch_github_data(username: str, token: Optional[str] = None) -> dict: - """ - Fetches all relevant GitHub data for a user. - Returns a dict with user profile, repos, events, and avatar. - """ - headers = {"Accept": "application/vnd.github.v3+json"} - if token: - headers["Authorization"] = f"token {token}" +class GitHubDataSource(Protocol): + """Protocol for GitHub data sources - allows swapping implementations.""" - base = "https://api.github.com" + def fetch_user_data(self, username: str) -> dict: + """Fetch user profile data.""" + ... - # User profile - user = requests.get(f"{base}/users/{username}", headers=headers).json() + def fetch_repos(self, username: str) -> list: + """Fetch user repositories.""" + ... - # Repos (up to 100) - repos = requests.get( - f"{base}/users/{username}/repos", - headers=headers, - params={"per_page": 100, "sort": "pushed", "type": "owner"}, - ).json() + def fetch_events(self, username: str) -> list: + """Fetch user events.""" + ... - # Events (recent activity) - events = requests.get( - f"{base}/users/{username}/events", - headers=headers, - params={"per_page": 100}, - ).json() + def fetch_commits(self, username: str, repos: list) -> list: + """Fetch commits from repositories.""" + ... - # Avatar as base64 - avatar_b64 = "" - if user.get("avatar_url"): + def fetch_repo_contributors(self, repo_name: str, min_commits: int) -> list: + """Fetch contributors for a specific repository.""" + ... + + def fetch_avatar(self, avatar_url: str) -> str: + """Fetch and encode avatar as base64.""" + ... + + +class DirectAPISource: + """Direct GitHub API implementation - for immediate requests.""" + + def __init__(self, token: Optional[str] = None): + self.token = token + self.headers = {"Accept": "application/vnd.github.v3+json"} + if token: + self.headers["Authorization"] = f"token {token}" + self.base = "https://api.github.com" + + def fetch_user_data(self, username: str) -> dict: + """Fetch user profile data.""" + return requests.get( + f"{self.base}/users/{username}", + headers=self.headers + ).json() + + def fetch_repos(self, username: str) -> list: + """Fetch user repositories (owned + contributed to).""" + # Fetch owned repos + owned = requests.get( + f"{self.base}/users/{username}/repos", + headers=self.headers, + params={"per_page": 100, "sort": "pushed", "type": "owner"}, + ).json() + + # Fetch all repos (includes collabs, orgs) + all_repos = requests.get( + f"{self.base}/users/{username}/repos", + headers=self.headers, + params={"per_page": 100, "sort": "pushed", "type": "all"}, + ).json() + + # Combine and deduplicate + repos = owned if isinstance(owned, list) else [] + all_repos = all_repos if isinstance(all_repos, list) else [] + + seen = {r["id"] for r in repos} + for repo in all_repos: + if repo["id"] not in seen: + repos.append(repo) + seen.add(repo["id"]) + + return repos + + def fetch_events(self, username: str) -> list: + """Fetch user events.""" + resp = requests.get( + f"{self.base}/users/{username}/events", + headers=self.headers, + params={"per_page": 100}, + ).json() + return resp if isinstance(resp, list) else [] + + def fetch_commits(self, username: str, repos: list, max_repos: int = COMMIT_MAX_REPOS) -> list: + """ + Fetch recent commits directly from user's repositories. + + Args: + username: GitHub username + repos: List of repository dicts + max_repos: Maximum number of repos to fetch from + + Returns: + List of commits with repo context + """ + all_commits = [] + sorted_repos = sorted( + repos, key=lambda r: r.get("pushed_at", ""), reverse=True + )[:max_repos] + + for repo in sorted_repos: + repo_name = repo.get("full_name") + if not repo_name: + continue + + try: + commits_resp = requests.get( + f"{self.base}/repos/{repo_name}/commits", + headers=self.headers, + params={"author": username, "per_page": COMMIT_PER_REPO}, + timeout=API_TIMEOUT + ) + + if commits_resp.ok: + commits = commits_resp.json() + for commit in commits: + commit["_repo_name"] = repo_name + commit["_repo_language"] = repo.get("language") + all_commits.extend(commits) + except Exception as e: + print(f"Warning: Failed to fetch commits from {repo_name}: {e}") + continue + + return all_commits + + def fetch_repo_contributors(self, repo_name: str, min_commits: int = 1) -> list: + """ + Fetch contributors for a specific repository. + + Args: + repo_name: Full repository name (owner/repo) + min_commits: Minimum commits to include contributor + + Returns: + List of contributor dicts with login, contributions, avatar_url + """ try: - resp = requests.get(user["avatar_url"] + "&s=64", timeout=5) + resp = requests.get( + f"{self.base}/repos/{repo_name}/contributors", + headers=self.headers, + params={"per_page": 100}, + timeout=API_TIMEOUT + ) + if resp.ok: - avatar_b64 = base64.b64encode(resp.content).decode("ascii") + contributors = resp.json() + # Filter by minimum commits + return [ + c for c in contributors + if c.get("contributions", 0) >= min_commits + ] + except Exception as e: + print(f"Warning: Failed to fetch contributors from {repo_name}: {e}") + + return [] + + def fetch_avatar(self, avatar_url: str) -> str: + """Fetch and encode avatar as base64.""" + try: + resp = requests.get(avatar_url + "&s=64", timeout=API_TIMEOUT) + if resp.ok: + return base64.b64encode(resp.content).decode("ascii") except Exception: pass + return "" + + +# TODO: Future implementation for queue-based batching +# class QueuedAPISource: +# """Queue-based GitHub API implementation - for batched processing.""" +# def __init__(self, queue_client, cache_client): +# self.queue = queue_client +# self.cache = cache_client +# +# def fetch_user_data(self, username: str) -> dict: +# # Check cache first, enqueue if miss +# ... + + +def fetch_github_data( + username: str, + token: Optional[str] = None, + data_source: Optional[GitHubDataSource] = None +) -> dict: + """ + Fetches all relevant GitHub data for a user. + + Args: + username: GitHub username + token: Optional GitHub API token + data_source: Optional data source implementation (defaults to DirectAPISource) + + Returns: + Dict with user, repos, events, commits, collaborators_data, and avatar_b64 + """ + # Use provided data source or default to direct API + source = data_source or DirectAPISource(token) + + # Fetch all data through the data source abstraction + user = source.fetch_user_data(username) + repos = source.fetch_repos(username) + events = source.fetch_events(username) + commits = source.fetch_commits(username, repos) + + # Fetch collaborators from repos where user has commits + collaborators_data = _fetch_collaborators_data( + username, commits, source + ) + + # Fetch avatar + avatar_b64 = "" + if user.get("avatar_url"): + avatar_b64 = source.fetch_avatar(user["avatar_url"]) return { "user": user, - "repos": repos if isinstance(repos, list) else [], - "events": events if isinstance(events, list) else [], + "repos": repos, + "events": events, + "commits": commits, + "collaborators_data": collaborators_data, "avatar_b64": avatar_b64, } + + +def _fetch_collaborators_data( + username: str, + commits: list, + source: GitHubDataSource, +) -> dict: + """ + Fetch collaborator data from repos where user has committed. + + Uses config.COLLABORATOR_MIN_COMMITS threshold (default: 10) to filter + out casual contributors and focus on meaningful collaborations. + + Args: + username: The user's GitHub username + commits: User's commits with repo context + source: Data source to fetch from + + Returns: + Dict mapping repo names to their contributors + """ + # Find repos where user has commits + user_repos = {} + for commit in commits: + repo_name = commit.get("_repo_name") + if repo_name: + user_repos[repo_name] = user_repos.get(repo_name, 0) + 1 + + # Fetch contributors from user's top repos + collaborators_by_repo = {} + sorted_repos = sorted(user_repos.items(), key=lambda x: -x[1])[:COLLABORATOR_TOP_REPOS] + + for repo_name, user_commit_count in sorted_repos: + # Fetch contributors with at least COLLABORATOR_MIN_COMMITS + contributors = source.fetch_repo_contributors(repo_name, COLLABORATOR_MIN_COMMITS) + + # Filter out the user themselves + contributors = [ + c for c in contributors + if c.get("login", "").lower() != username.lower() + ] + + # Skip repos with too many contributors (huge OSS projects) + if len(contributors) < COLLABORATOR_MAX_REPO_SIZE: + collaborators_by_repo[repo_name] = contributors + + return collaborators_by_repo diff --git a/src/data/processor.py b/src/data/processor.py index c3f668f..5236991 100644 --- a/src/data/processor.py +++ b/src/data/processor.py @@ -25,15 +25,22 @@ def compute_grade(github_data: dict) -> GradeData: user = github_data["user"] repos = github_data["repos"] events = github_data["events"] + direct_commits = github_data.get("commits", []) repo_count = min(len(repos), 50) stars = sum(r.get("stargazers_count", 0) for r in repos) forks = sum(r.get("forks_count", 0) for r in repos) followers = user.get("followers", 0) - commits = sum( - len(ev.get("payload", {}).get("commits", [])) - for ev in events if ev.get("type") == "PushEvent" - ) + + # Use direct commit count if available, otherwise fall back to events + if direct_commits: + commits = len(direct_commits) + else: + commits = sum( + len(ev.get("payload", {}).get("commits", [])) + for ev in events if ev.get("type") == "PushEvent" + ) + prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent") scores = { @@ -180,17 +187,29 @@ def _compute_tags(github_data: dict) -> list[TagData]: def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]: """Aggregate events into weekly impact data.""" - events = github_data["events"] + direct_commits = github_data.get("commits", []) weekly = defaultdict(lambda: {"commits": 0}) - for ev in events: - if ev.get("type") == "PushEvent": - created = ev.get("created_at", "")[:10] - if created: + if direct_commits: + # Use direct commit data + for commit in direct_commits: + commit_date = commit.get("commit", {}).get("author", {}).get("date", "") + if commit_date: + created = commit_date[:10] dt = datetime.fromisoformat(created) week_start = (dt - timedelta(days=dt.weekday())).isoformat()[:10] - commits = len(ev.get("payload", {}).get("commits", [])) - weekly[week_start]["commits"] += commits + weekly[week_start]["commits"] += 1 + else: + # Fallback to events-based counting + events = github_data["events"] + for ev in events: + if ev.get("type") == "PushEvent": + created = ev.get("created_at", "")[:10] + if created: + dt = datetime.fromisoformat(created) + week_start = (dt - timedelta(days=dt.weekday())).isoformat()[:10] + commits = len(ev.get("payload", {}).get("commits", [])) + weekly[week_start]["commits"] += commits weeks = [] for ws in sorted(weekly.keys()): @@ -201,7 +220,53 @@ def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]: def compute_collaborators(github_data: dict) -> list[CollaboratorData]: - """Find top collaborators from events.""" + """ + Find top collaborators - people who committed to the same repos as the user. + + Uses actual commit/contributor data to find meaningful collaborations. + Filters out huge OSS projects by requiring 10+ commits threshold. + """ + collaborators_data = github_data.get("collaborators_data", {}) + + if not collaborators_data: + # Fallback to events-based if no collaborator data + return _compute_collaborators_from_events(github_data) + + # Aggregate collaborators across all shared repos + collab_stats = defaultdict(lambda: { + "repos": set(), + "commits": 0, + "avatar_url": "" + }) + + for repo_name, contributors in collaborators_data.items(): + for contributor in contributors: + login = contributor.get("login", "") + if login: + collab_stats[login]["repos"].add(repo_name) + collab_stats[login]["commits"] += contributor.get("contributions", 0) + if not collab_stats[login]["avatar_url"]: + collab_stats[login]["avatar_url"] = contributor.get("avatar_url", "") + + # Sort by total commits and take top 4 + collabs = [] + for username, stats in sorted( + collab_stats.items(), key=lambda x: -x[1]["commits"] + )[:4]: # Show exactly 4 collaborators + collabs.append( + CollaboratorData( + username=username, + shared_repos=len(stats["repos"]), + shared_commits=stats["commits"], + avatar_b64="", # Will be fetched if needed + ) + ) + + return collabs + + +def _compute_collaborators_from_events(github_data: dict) -> list[CollaboratorData]: + """Fallback: compute collaborators from events (less accurate).""" events = github_data["events"] me = github_data["user"].get("login", "").lower() collab_stats = defaultdict(lambda: {"repos": set(), "commits": 0}) @@ -216,7 +281,7 @@ def compute_collaborators(github_data: dict) -> list[CollaboratorData]: collabs = [] for username, stats in sorted( collab_stats.items(), key=lambda x: -x[1]["commits"] - )[:5]: + )[:4]: # Match the main function: top 4 collabs.append( CollaboratorData( username=username, @@ -232,6 +297,7 @@ def compute_focus(github_data: dict) -> list[FocusCategory]: """Classify commits into focus categories.""" repos = github_data["repos"] events = github_data["events"] + direct_commits = github_data.get("commits", []) lang_to_focus = { "Python": "Python", @@ -252,19 +318,28 @@ def compute_focus(github_data: dict) -> list[FocusCategory]: } focus_counts = defaultdict(int) - repo_langs = {} - for r in repos: - lang = r.get("language") - if lang: - repo_langs[r["full_name"]] = lang - for ev in events: - if ev.get("type") == "PushEvent": - repo_name = ev.get("repo", {}).get("name", "") - lang = repo_langs.get(repo_name) + if direct_commits: + # Use direct commit data with embedded language info + for commit in direct_commits: + lang = commit.get("_repo_language") focus = lang_to_focus.get(lang, "Other") - commits = len(ev.get("payload", {}).get("commits", [])) - focus_counts[focus] += commits + focus_counts[focus] += 1 + else: + # Fallback to events-based counting + repo_langs = {} + for r in repos: + lang = r.get("language") + if lang: + repo_langs[r["full_name"]] = lang + + for ev in events: + if ev.get("type") == "PushEvent": + repo_name = ev.get("repo", {}).get("name", "") + lang = repo_langs.get(repo_name) + focus = lang_to_focus.get(lang, "Other") + commits = len(ev.get("payload", {}).get("commits", [])) + focus_counts[focus] += commits total = sum(focus_counts.values()) or 1 return [ diff --git a/src/generate.py b/src/generate.py index 98f2cc5..e3f635f 100644 --- a/src/generate.py +++ b/src/generate.py @@ -34,6 +34,16 @@ def generate_full_widget( print(f"Fetching GitHub data for {username}...") github_data = fetch_github_data(username, token) + # Log commit count for debugging + commit_count = len(github_data.get("commits", [])) + if commit_count == 0: + print(f" Warning: No commits found. This may be due to:") + print(f" - No recent PushEvents in last 100 GitHub events") + print(f" - All commits are from merged PRs") + print(f" - GitHub API rate limiting (try with GITHUB_TOKEN)") + else: + print(f" Found {commit_count} commits") + print("Generating widgets...") widgets = generate_widgets_from_github(github_data, theme) @@ -68,7 +78,7 @@ def generate_full_widget( def main(): """CLI entry point.""" username = sys.argv[1] if len(sys.argv) > 1 else "shaymanor" - token = os.environ.get("GITHUB_TOKEN") + token = os.environ.get("GITHUB_PAT") theme = sys.argv[2] if len(sys.argv) > 2 else "dark" if username: