From a336577c5599733cd15992d7f46b3561cf8af3b2 Mon Sep 17 00:00:00 2001 From: shay Date: Fri, 20 Feb 2026 14:50:52 -0500 Subject: [PATCH] feat(fetcher): enhance commit and contribution fetching using GitHub GraphQL API --- src/README.md | 35 +++++ src/config.py | 28 ++++ src/data/fetcher.py | 335 ++++++++++++++++++++++++++++++++++-------- src/data/processor.py | 132 +++++++++++------ src/generate.py | 22 ++- 5 files changed, 439 insertions(+), 113 deletions(-) create mode 100644 src/config.py diff --git a/src/README.md b/src/README.md index 9199d99..afd41c8 100644 --- a/src/README.md +++ b/src/README.md @@ -68,6 +68,41 @@ python run.py light 1. Add theme definition to `themes/themes.py` 2. Use the theme name when calling `generate_full_widget(theme="my_theme")` +## Configuration + +Customize behavior via environment variables: + +```bash +# Collaborator settings +export COLLABORATOR_MIN_COMMITS=10 # Min commits to be a collaborator (default: 10) +export COLLABORATOR_MAX_REPO_SIZE=100 # Skip repos with 100+ contributors (default: 100) +export COLLABORATOR_TOP_REPOS=5 # Check top N repos for collaborators (default: 5) + +# Commit fetching +export COMMIT_MAX_REPOS=10 # Fetch commits from top N repos (default: 10) +export COMMIT_PER_REPO=30 # Commits per repo (default: 30) + +# API settings +export API_TIMEOUT=5 # Request timeout in seconds (default: 5) + +# Run with custom settings +COLLABORATOR_MIN_COMMITS=15 python run.py username +``` + +## How Collaborators Are Detected + +The widget finds **meaningful collaborators** by: + +1. **Identifying shared repositories**: Looks at repos where the user has committed +2. **Fetching contributors**: Gets all contributors from those repos +3. **Applying thresholds**: + - Only includes contributors with 10+ commits (configurable) + - Filters out huge OSS projects (100+ contributors) + - Focuses on user's top 5 most active repos +4. **Ranking by collaboration**: Sorts by total shared commits across all repos + +This ensures collaborators are people you've actually worked with closely, not random contributors from large open-source projects. + ## Development All widgets follow the same pattern: diff --git a/src/config.py b/src/config.py new file mode 100644 index 0000000..2c246b5 --- /dev/null +++ b/src/config.py @@ -0,0 +1,28 @@ +"""Configuration for GitHub widget generator.""" + +import os + +# Collaborator settings +COLLABORATOR_MIN_COMMITS = int(os.getenv("COLLABORATOR_MIN_COMMITS", "5")) +"""Minimum commits in a shared repo to be considered a collaborator (lowered to 5 for better detection).""" + +COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150")) +"""Maximum contributors in a repo to be included (filters out huge OSS projects).""" + +COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "8")) +"""Number of user's top repos to check for collaborators (increased to find more collaborators).""" + +# Commit fetching settings +COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10")) +"""Maximum number of repos to fetch commits from.""" + +COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30")) +"""Number of commits to fetch per repository.""" + +# API settings +API_TIMEOUT = int(os.getenv("API_TIMEOUT", "5")) +"""Timeout in seconds for API requests.""" + +# Data source +DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct") +"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing.""" diff --git a/src/data/fetcher.py b/src/data/fetcher.py index a370625..ae23178 100644 --- a/src/data/fetcher.py +++ b/src/data/fetcher.py @@ -29,12 +29,16 @@ class GitHubDataSource(Protocol): """Fetch user events.""" ... - def fetch_commits(self, username: str, repos: list) -> list: - """Fetch commits from repositories.""" + def fetch_commits(self, username: str, repos: list = None) -> list: + """Fetch daily commit data from contribution calendar.""" ... - def fetch_commit_count(self, username: str, since_date: str = None) -> int: - """Fetch total commit count using search API.""" + def fetch_commit_count(self, username: str, repos: list, since_date: str = None) -> int: + """Fetch total commit count by aggregating from repos.""" + ... + + def fetch_pr_count(self, username: str) -> int: + """Fetch total PR count using search API.""" ... def fetch_repo_contributors(self, repo_name: str, min_commits: int) -> list: @@ -100,68 +104,255 @@ class DirectAPISource: ).json() return resp if isinstance(resp, list) else [] - def fetch_commits(self, username: str, repos: list, max_repos: int = COMMIT_MAX_REPOS) -> list: + def fetch_commits(self, username: str, repos: list = None) -> list: """ - Fetch recent commits directly from user's repositories. + Fetch daily commit data using GitHub's GraphQL contributionsCollection. + + Uses the contribution calendar to get accurate daily commit counts + matching what GitHub shows on the user's profile page. Args: username: GitHub username - repos: List of repository dicts - max_repos: Maximum number of repos to fetch from + repos: Not used, kept for interface compatibility Returns: - List of commits with repo context + List of daily commit data: [{"date": "YYYY-MM-DD", "count": N}, ...] """ - all_commits = [] - sorted_repos = sorted( - repos, key=lambda r: r.get("pushed_at", ""), reverse=True - )[:max_repos] + from datetime import datetime - for repo in sorted_repos: - repo_name = repo.get("full_name") - if not repo_name: - continue + try: + # Get the last year of contribution data + now = datetime.now() + one_year_ago = now.replace(year=now.year - 1) + from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ") + to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ") - 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 - ) + query = f''' + query {{ + user(login: "{username}") {{ + contributionsCollection(from: "{from_date}", to: "{to_date}") {{ + contributionCalendar {{ + weeks {{ + contributionDays {{ + date + contributionCount + }} + }} + }} + }} + }} + }} + ''' - 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 + headers = { + **self.headers, + 'Content-Type': 'application/json' + } + # GraphQL uses Bearer token + if 'Authorization' in headers and headers['Authorization'].startswith('token '): + headers['Authorization'] = headers['Authorization'].replace('token ', 'Bearer ') - return all_commits + resp = requests.post( + 'https://api.github.com/graphql', + json={'query': query}, + headers=headers, + timeout=API_TIMEOUT + ) - def fetch_commit_count(self, username: str, since_date: str = None) -> int: + if not resp.ok: + print(f" GraphQL error fetching commits: {resp.status_code}") + return [] + + data = resp.json() + if 'data' not in data or not data['data'].get('user'): + print(" No user data in GraphQL response") + return [] + + # Extract daily commit data + daily_commits = [] + weeks = data['data']['user']['contributionsCollection']['contributionCalendar']['weeks'] + + for week in weeks: + for day in week['contributionDays']: + if day['contributionCount'] > 0: # Only include days with commits + daily_commits.append({ + 'date': day['date'], + 'count': day['contributionCount'] + }) + + print(f" GraphQL API found {len(daily_commits)} days with commits") + return daily_commits + + except Exception as e: + print(f" Error fetching daily commits via GraphQL: {e}") + return [] + + def fetch_commit_count(self, username: str, repos: list, since_date: str = None) -> int: """ - Fetch total commit count using GitHub search API. + Fetch total contribution count using GitHub GraphQL API. + + Uses the contributionsCollection to get accurate contribution counts (commits, PRs, + issues, reviews) matching what GitHub shows on user profiles and what streak-stats displays. + Fetches year-by-year to get all-time total. Args: username: GitHub username - since_date: ISO date string (YYYY-MM-DD) to filter commits after this date + repos: List of repository dicts (unused, kept for interface compatibility) + since_date: ISO date string (YYYY-MM-DD) to filter contributions after this date Returns: - Total number of commits + Total number of contributions (commits + PRs + issues + reviews) + """ + from datetime import datetime + + try: + # If since_date is provided, use specific date range + if since_date: + return self._fetch_commit_count_graphql_range(username, since_date) + else: + return self._fetch_commit_count_graphql_alltime(username) + except Exception as e: + print(f" Error fetching contribution count: {e}") + return 0 + + def _fetch_commit_count_graphql_alltime(self, username: str) -> int: + """Fetch all-time contribution count using GraphQL.""" + from datetime import datetime + + # First, get account creation date + query = ''' + query($username: String!) { + user(login: $username) { + createdAt + } + } + ''' + + headers = { + **self.headers, + 'Content-Type': 'application/json' + } + # GraphQL uses Bearer token instead of 'token' + if 'Authorization' in headers and headers['Authorization'].startswith('token '): + headers['Authorization'] = headers['Authorization'].replace('token ', 'Bearer ') + + resp = requests.post( + 'https://api.github.com/graphql', + json={'query': query, 'variables': {'username': username}}, + headers=headers, + timeout=API_TIMEOUT + ) + + if not resp.ok or 'data' not in resp.json(): + print(f" GraphQL error: {resp.status_code}") + return 0 + + data = resp.json() + if not data.get('data', {}).get('user'): + return 0 + + created_at = data['data']['user']['createdAt'] + created_year = int(created_at[:4]) + current_year = datetime.now().year + + # Fetch year by year + total_contributions = 0 + print(f" Fetching contributions from {created_year} to {current_year}...") + for year in range(created_year, current_year + 1): + year_query = f''' + query {{ + user(login: "{username}") {{ + contributionsCollection(from: "{year}-01-01T00:00:00Z", to: "{year}-12-31T23:59:59Z") {{ + contributionCalendar {{ + totalContributions + }} + }} + }} + }} + ''' + + year_resp = requests.post( + 'https://api.github.com/graphql', + json={'query': year_query}, + headers=headers, + timeout=API_TIMEOUT + ) + + if year_resp.ok: + year_data = year_resp.json() + if 'data' in year_data and year_data['data'].get('user'): + year_contributions = year_data['data']['user']['contributionsCollection']['contributionCalendar']['totalContributions'] + total_contributions += year_contributions + print(f" {year}: {year_contributions:,} contributions") + else: + print(f" {year}: Error - {year_data}") + else: + print(f" {year}: HTTP {year_resp.status_code}") + + print(f" GraphQL API found {total_contributions:,} contributions (all-time)") + return total_contributions + + def _fetch_commit_count_graphql_range(self, username: str, since_date: str) -> int: + """Fetch contribution count for a specific date range using GraphQL.""" + from datetime import datetime + + # Convert since_date to proper format + from_date = f"{since_date}T00:00:00Z" + to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") + + query = f''' + query {{ + user(login: "{username}") {{ + contributionsCollection(from: "{from_date}", to: "{to_date}") {{ + contributionCalendar {{ + totalContributions + }} + }} + }} + }} + ''' + + headers = { + **self.headers, + 'Content-Type': 'application/json' + } + # GraphQL uses Bearer token + if 'Authorization' in headers and headers['Authorization'].startswith('token '): + headers['Authorization'] = headers['Authorization'].replace('token ', 'Bearer ') + + resp = requests.post( + 'https://api.github.com/graphql', + json={'query': query}, + headers=headers, + timeout=API_TIMEOUT + ) + + if resp.ok: + data = resp.json() + if 'data' in data and data['data'].get('user'): + total = data['data']['user']['contributionsCollection']['contributionCalendar']['totalContributions'] + print(f" GraphQL API found {total:,} contributions (since {since_date})") + return total + + print(f" GraphQL error: {resp.status_code if resp else 'unknown'}") + return 0 + + def fetch_pr_count(self, username: str) -> int: + """ + Fetch total PR count using GitHub search API. + + Args: + username: GitHub username + + Returns: + Total number of PRs authored by user """ try: - # Build search query - query = f"author:{username}" - if since_date: - query += f" author-date:>={since_date}" + query = f"is:pr author:{username}" resp = requests.get( - f"{self.base}/search/commits", - headers={**self.headers, "Accept": "application/vnd.github.cloak-preview+json"}, + f"{self.base}/search/issues", + headers=self.headers, params={"q": query, "per_page": 1}, timeout=API_TIMEOUT ) @@ -170,7 +361,7 @@ class DirectAPISource: data = resp.json() return data.get("total_count", 0) except Exception as e: - print(f"Warning: Failed to fetch commit count via search API: {e}") + print(f"Warning: Failed to fetch PR count via search API: {e}") return 0 @@ -242,8 +433,10 @@ def fetch_github_data( data_source: Optional data source implementation (defaults to DirectAPISource) Returns: - Dict with user, repos, events, commits, collaborators_data, and avatar_b64 + Dict with user, repos, events, commits, commit counts, collaborators_data, and avatar_b64 """ + from datetime import datetime, timedelta + # Use provided data source or default to direct API source = data_source or DirectAPISource(token) @@ -251,11 +444,24 @@ def fetch_github_data( user = source.fetch_user_data(username) repos = source.fetch_repos(username) events = source.fetch_events(username) - commits = source.fetch_commits(username, repos) + commits = source.fetch_commits(username) - # Fetch collaborators from repos where user has commits + # Fetch contribution counts (commits + PRs + issues + reviews) + print(" Fetching all-time contribution count...") + total_commits = source.fetch_commit_count(username, repos) + + # Recent contributions (last 6 months) + six_months_ago = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d") + print(" Fetching recent contribution count (last 6 months)...") + recent_commits = source.fetch_commit_count(username, repos, since_date=six_months_ago) + + # Fetch PR count + print(" Fetching PR count...") + total_prs = source.fetch_pr_count(username) + + # Fetch collaborators from user's active repos collaborators_data = _fetch_collaborators_data( - username, commits, source + username, repos, source ) # Fetch avatar @@ -268,6 +474,9 @@ def fetch_github_data( "repos": repos, "events": events, "commits": commits, + "total_commits": total_commits, + "recent_commits": recent_commits, + "total_prs": total_prs, "collaborators_data": collaborators_data, "avatar_b64": avatar_b64, } @@ -275,35 +484,37 @@ def fetch_github_data( def _fetch_collaborators_data( username: str, - commits: list, + repos: list, source: GitHubDataSource, ) -> dict: """ - Fetch collaborator data from repos where user has committed. + Fetch collaborator data from user's most active repositories. - Uses config.COLLABORATOR_MIN_COMMITS threshold (default: 10) to filter + Uses config.COLLABORATOR_MIN_COMMITS threshold (default: 5) to filter out casual contributors and focus on meaningful collaborations. Args: username: The user's GitHub username - commits: User's commits with repo context + repos: List of user's repositories 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 + # Use the user's most recently pushed repos + sorted_repos = sorted( + repos, + key=lambda r: r.get("pushed_at", ""), + reverse=True + )[:COLLABORATOR_TOP_REPOS] - # 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: + for repo in sorted_repos: + repo_name = repo.get("full_name") + if not repo_name: + continue + # Fetch contributors with at least COLLABORATOR_MIN_COMMITS contributors = source.fetch_repo_contributors(repo_name, COLLABORATOR_MIN_COMMITS) diff --git a/src/data/processor.py b/src/data/processor.py index 5236991..4b61c53 100644 --- a/src/data/processor.py +++ b/src/data/processor.py @@ -25,23 +25,35 @@ 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", []) + + # Use accurate contribution count (commits + PRs + issues + reviews) from GraphQL + commits = github_data.get("total_commits", 0) + + # Fallback to daily contribution data if aggregation didn't work + if commits == 0: + daily_contribs = github_data.get("commits", []) + if daily_contribs and isinstance(daily_contribs, list) and len(daily_contribs) > 0: + if isinstance(daily_contribs[0], dict) and "count" in daily_contribs[0]: + commits = sum(day.get("count", 0) for day in daily_contribs) + else: + commits = len(daily_contribs) + else: + commits = sum( + len(ev.get("payload", {}).get("commits", [])) + for ev in events if ev.get("type") == "PushEvent" + ) 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) - # 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" - ) + # Use accurate PR count from search API + prs = github_data.get("total_prs", 0) - prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent") + # Fallback to events if not available + if prs == 0: + prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent") scores = { "repos": min(repo_count / 30 * 100, 100), @@ -186,30 +198,64 @@ def _compute_tags(github_data: dict) -> list[TagData]: def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]: - """Aggregate events into weekly impact data.""" - direct_commits = github_data.get("commits", []) + """Aggregate daily contributions into weekly impact data using GitHub's contribution calendar.""" + daily_contributions = github_data.get("commits", []) weekly = defaultdict(lambda: {"commits": 0}) - 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] - weekly[week_start]["commits"] += 1 + # Calculate date boundaries + now = datetime.now() + current_week_start = (now - timedelta(days=now.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) + six_months_ago = now - timedelta(days=180) + + if daily_contributions and isinstance(daily_contributions, list) and len(daily_contributions) > 0: + # Use GraphQL daily contribution data (format: [{"date": "YYYY-MM-DD", "count": N}]) + if isinstance(daily_contributions[0], dict) and "date" in daily_contributions[0] and "count" in daily_contributions[0]: + for day_data in daily_contributions: + date_str = day_data.get("date", "") + count = day_data.get("count", 0) + + if date_str: + dt = datetime.fromisoformat(date_str) + + # Calculate week start (Monday) + week_start_dt = dt - timedelta(days=dt.weekday()) + week_start_str = week_start_dt.isoformat()[:10] + + # Only include last 6 months, excluding current week + if dt >= six_months_ago and week_start_dt < current_week_start: + weekly[week_start_str]["commits"] += count + else: + # Old REST API format fallback + for commit in daily_contributions: + commit_date = commit.get("commit", {}).get("author", {}).get("date", "") + if commit_date: + created = commit_date[:10] + dt = datetime.fromisoformat(created) + + # Calculate week start (Monday) + week_start_dt = dt - timedelta(days=dt.weekday()) + week_start_str = week_start_dt.isoformat()[:10] + + # Only include last 6 months, excluding current week + if dt >= six_months_ago and week_start_dt < current_week_start: + weekly[week_start_str]["commits"] += 1 else: # Fallback to events-based counting - events = github_data["events"] + events = github_data.get("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 + + # Calculate week start (Monday) + week_start_dt = dt - timedelta(days=dt.weekday()) + week_start_str = week_start_dt.isoformat()[:10] + + # Only include last 6 months, excluding current week + if dt >= six_months_ago and week_start_dt < current_week_start: + commits = len(ev.get("payload", {}).get("commits", [])) + weekly[week_start_str]["commits"] += commits weeks = [] for ws in sorted(weekly.keys()): @@ -294,10 +340,9 @@ def _compute_collaborators_from_events(github_data: dict) -> list[CollaboratorDa def compute_focus(github_data: dict) -> list[FocusCategory]: - """Classify commits into focus categories.""" + """Classify commits into focus categories based on repo languages and activity.""" repos = github_data["repos"] events = github_data["events"] - direct_commits = github_data.get("commits", []) lang_to_focus = { "Python": "Python", @@ -319,27 +364,28 @@ def compute_focus(github_data: dict) -> list[FocusCategory]: focus_counts = defaultdict(int) - if direct_commits: - # Use direct commit data with embedded language info - for commit in direct_commits: - lang = commit.get("_repo_language") + # Use events-based counting to track actual activity + 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") - focus_counts[focus] += 1 - else: - # Fallback to events-based counting - repo_langs = {} + commits = len(ev.get("payload", {}).get("commits", [])) + focus_counts[focus] += commits + + # If no events, fallback to repo count + if not focus_counts: 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 + focus_counts[focus] += 1 total = sum(focus_counts.values()) or 1 return [ diff --git a/src/generate.py b/src/generate.py index e3f635f..a05c30e 100644 --- a/src/generate.py +++ b/src/generate.py @@ -34,15 +34,21 @@ 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)") + # Log contribution counts + total_commits = github_data.get("total_commits", 0) + recent_commits = github_data.get("recent_commits", 0) + total_prs = github_data.get("total_prs", 0) + daily_commits = len(github_data.get("commits", [])) + + if total_commits > 0: + print(f" Total contributions (all-time): {total_commits:,}") + print(f" Recent contributions (6 months): {recent_commits:,}") + print(f" Total PRs (all-time): {total_prs:,}") + print(f" Daily contribution data points: {daily_commits}") else: - print(f" Found {commit_count} commits") + print(f" Warning: Could not fetch contribution count") + if daily_commits == 0: + print(f" Try running with GITHUB_PAT environment variable") print("Generating widgets...") widgets = generate_widgets_from_github(github_data, theme)