mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(fetcher): enhance commit and contribution fetching using GitHub GraphQL API
This commit is contained in:
@@ -68,6 +68,41 @@ python run.py <username> light
|
|||||||
1. Add theme definition to `themes/themes.py`
|
1. Add theme definition to `themes/themes.py`
|
||||||
2. Use the theme name when calling `generate_full_widget(theme="my_theme")`
|
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
|
## Development
|
||||||
|
|
||||||
All widgets follow the same pattern:
|
All widgets follow the same pattern:
|
||||||
|
|||||||
@@ -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."""
|
||||||
+271
-60
@@ -29,12 +29,16 @@ class GitHubDataSource(Protocol):
|
|||||||
"""Fetch user events."""
|
"""Fetch user events."""
|
||||||
...
|
...
|
||||||
|
|
||||||
def fetch_commits(self, username: str, repos: list) -> list:
|
def fetch_commits(self, username: str, repos: list = None) -> list:
|
||||||
"""Fetch commits from repositories."""
|
"""Fetch daily commit data from contribution calendar."""
|
||||||
...
|
...
|
||||||
|
|
||||||
def fetch_commit_count(self, username: str, since_date: str = None) -> int:
|
def fetch_commit_count(self, username: str, repos: list, since_date: str = None) -> int:
|
||||||
"""Fetch total commit count using search API."""
|
"""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:
|
def fetch_repo_contributors(self, repo_name: str, min_commits: int) -> list:
|
||||||
@@ -100,68 +104,255 @@ class DirectAPISource:
|
|||||||
).json()
|
).json()
|
||||||
return resp if isinstance(resp, list) else []
|
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:
|
Args:
|
||||||
username: GitHub username
|
username: GitHub username
|
||||||
repos: List of repository dicts
|
repos: Not used, kept for interface compatibility
|
||||||
max_repos: Maximum number of repos to fetch from
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List of commits with repo context
|
List of daily commit data: [{"date": "YYYY-MM-DD", "count": N}, ...]
|
||||||
"""
|
"""
|
||||||
all_commits = []
|
from datetime import datetime
|
||||||
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:
|
try:
|
||||||
commits_resp = requests.get(
|
# Get the last year of contribution data
|
||||||
f"{self.base}/repos/{repo_name}/commits",
|
now = datetime.now()
|
||||||
headers=self.headers,
|
one_year_ago = now.replace(year=now.year - 1)
|
||||||
params={"author": username, "per_page": COMMIT_PER_REPO},
|
from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
query = f'''
|
||||||
|
query {{
|
||||||
|
user(login: "{username}") {{
|
||||||
|
contributionsCollection(from: "{from_date}", to: "{to_date}") {{
|
||||||
|
contributionCalendar {{
|
||||||
|
weeks {{
|
||||||
|
contributionDays {{
|
||||||
|
date
|
||||||
|
contributionCount
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
'''
|
||||||
|
|
||||||
|
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
|
timeout=API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if commits_resp.ok:
|
if not resp.ok:
|
||||||
commits = commits_resp.json()
|
print(f" GraphQL error fetching commits: {resp.status_code}")
|
||||||
for commit in commits:
|
return []
|
||||||
commit["_repo_name"] = repo_name
|
|
||||||
commit["_repo_language"] = repo.get("language")
|
data = resp.json()
|
||||||
all_commits.extend(commits)
|
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:
|
except Exception as e:
|
||||||
print(f"Warning: Failed to fetch commits from {repo_name}: {e}")
|
print(f" Error fetching daily commits via GraphQL: {e}")
|
||||||
continue
|
return []
|
||||||
|
|
||||||
return all_commits
|
def fetch_commit_count(self, username: str, repos: list, since_date: str = None) -> int:
|
||||||
|
|
||||||
def fetch_commit_count(self, username: str, 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:
|
Args:
|
||||||
username: GitHub username
|
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:
|
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:
|
try:
|
||||||
# Build search query
|
query = f"is:pr author:{username}"
|
||||||
query = f"author:{username}"
|
|
||||||
if since_date:
|
|
||||||
query += f" author-date:>={since_date}"
|
|
||||||
|
|
||||||
resp = requests.get(
|
resp = requests.get(
|
||||||
f"{self.base}/search/commits",
|
f"{self.base}/search/issues",
|
||||||
headers={**self.headers, "Accept": "application/vnd.github.cloak-preview+json"},
|
headers=self.headers,
|
||||||
params={"q": query, "per_page": 1},
|
params={"q": query, "per_page": 1},
|
||||||
timeout=API_TIMEOUT
|
timeout=API_TIMEOUT
|
||||||
)
|
)
|
||||||
@@ -170,7 +361,7 @@ class DirectAPISource:
|
|||||||
data = resp.json()
|
data = resp.json()
|
||||||
return data.get("total_count", 0)
|
return data.get("total_count", 0)
|
||||||
except Exception as e:
|
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
|
return 0
|
||||||
|
|
||||||
@@ -242,8 +433,10 @@ def fetch_github_data(
|
|||||||
data_source: Optional data source implementation (defaults to DirectAPISource)
|
data_source: Optional data source implementation (defaults to DirectAPISource)
|
||||||
|
|
||||||
Returns:
|
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
|
# Use provided data source or default to direct API
|
||||||
source = data_source or DirectAPISource(token)
|
source = data_source or DirectAPISource(token)
|
||||||
|
|
||||||
@@ -251,11 +444,24 @@ def fetch_github_data(
|
|||||||
user = source.fetch_user_data(username)
|
user = source.fetch_user_data(username)
|
||||||
repos = source.fetch_repos(username)
|
repos = source.fetch_repos(username)
|
||||||
events = source.fetch_events(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(
|
collaborators_data = _fetch_collaborators_data(
|
||||||
username, commits, source
|
username, repos, source
|
||||||
)
|
)
|
||||||
|
|
||||||
# Fetch avatar
|
# Fetch avatar
|
||||||
@@ -268,6 +474,9 @@ def fetch_github_data(
|
|||||||
"repos": repos,
|
"repos": repos,
|
||||||
"events": events,
|
"events": events,
|
||||||
"commits": commits,
|
"commits": commits,
|
||||||
|
"total_commits": total_commits,
|
||||||
|
"recent_commits": recent_commits,
|
||||||
|
"total_prs": total_prs,
|
||||||
"collaborators_data": collaborators_data,
|
"collaborators_data": collaborators_data,
|
||||||
"avatar_b64": avatar_b64,
|
"avatar_b64": avatar_b64,
|
||||||
}
|
}
|
||||||
@@ -275,35 +484,37 @@ def fetch_github_data(
|
|||||||
|
|
||||||
def _fetch_collaborators_data(
|
def _fetch_collaborators_data(
|
||||||
username: str,
|
username: str,
|
||||||
commits: list,
|
repos: list,
|
||||||
source: GitHubDataSource,
|
source: GitHubDataSource,
|
||||||
) -> dict:
|
) -> 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.
|
out casual contributors and focus on meaningful collaborations.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
username: The user's GitHub username
|
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
|
source: Data source to fetch from
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Dict mapping repo names to their contributors
|
Dict mapping repo names to their contributors
|
||||||
"""
|
"""
|
||||||
# Find repos where user has commits
|
# Use the user's most recently pushed repos
|
||||||
user_repos = {}
|
sorted_repos = sorted(
|
||||||
for commit in commits:
|
repos,
|
||||||
repo_name = commit.get("_repo_name")
|
key=lambda r: r.get("pushed_at", ""),
|
||||||
if repo_name:
|
reverse=True
|
||||||
user_repos[repo_name] = user_repos.get(repo_name, 0) + 1
|
)[:COLLABORATOR_TOP_REPOS]
|
||||||
|
|
||||||
# Fetch contributors from user's top repos
|
|
||||||
collaborators_by_repo = {}
|
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
|
# Fetch contributors with at least COLLABORATOR_MIN_COMMITS
|
||||||
contributors = source.fetch_repo_contributors(repo_name, COLLABORATOR_MIN_COMMITS)
|
contributors = source.fetch_repo_contributors(repo_name, COLLABORATOR_MIN_COMMITS)
|
||||||
|
|
||||||
|
|||||||
+74
-28
@@ -25,22 +25,34 @@ def compute_grade(github_data: dict) -> GradeData:
|
|||||||
user = github_data["user"]
|
user = github_data["user"]
|
||||||
repos = github_data["repos"]
|
repos = github_data["repos"]
|
||||||
events = github_data["events"]
|
events = github_data["events"]
|
||||||
direct_commits = github_data.get("commits", [])
|
|
||||||
|
|
||||||
repo_count = min(len(repos), 50)
|
# Use accurate contribution count (commits + PRs + issues + reviews) from GraphQL
|
||||||
stars = sum(r.get("stargazers_count", 0) for r in repos)
|
commits = github_data.get("total_commits", 0)
|
||||||
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
|
# Fallback to daily contribution data if aggregation didn't work
|
||||||
if direct_commits:
|
if commits == 0:
|
||||||
commits = len(direct_commits)
|
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:
|
else:
|
||||||
commits = sum(
|
commits = sum(
|
||||||
len(ev.get("payload", {}).get("commits", []))
|
len(ev.get("payload", {}).get("commits", []))
|
||||||
for ev in events if ev.get("type") == "PushEvent"
|
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 accurate PR count from search API
|
||||||
|
prs = github_data.get("total_prs", 0)
|
||||||
|
|
||||||
|
# Fallback to events if not available
|
||||||
|
if prs == 0:
|
||||||
prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent")
|
prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent")
|
||||||
|
|
||||||
scores = {
|
scores = {
|
||||||
@@ -186,30 +198,64 @@ def _compute_tags(github_data: dict) -> list[TagData]:
|
|||||||
|
|
||||||
|
|
||||||
def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]:
|
def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]:
|
||||||
"""Aggregate events into weekly impact data."""
|
"""Aggregate daily contributions into weekly impact data using GitHub's contribution calendar."""
|
||||||
direct_commits = github_data.get("commits", [])
|
daily_contributions = github_data.get("commits", [])
|
||||||
weekly = defaultdict(lambda: {"commits": 0})
|
weekly = defaultdict(lambda: {"commits": 0})
|
||||||
|
|
||||||
if direct_commits:
|
# Calculate date boundaries
|
||||||
# Use direct commit data
|
now = datetime.now()
|
||||||
for commit in direct_commits:
|
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", "")
|
commit_date = commit.get("commit", {}).get("author", {}).get("date", "")
|
||||||
if commit_date:
|
if commit_date:
|
||||||
created = commit_date[:10]
|
created = commit_date[:10]
|
||||||
dt = datetime.fromisoformat(created)
|
dt = datetime.fromisoformat(created)
|
||||||
week_start = (dt - timedelta(days=dt.weekday())).isoformat()[:10]
|
|
||||||
weekly[week_start]["commits"] += 1
|
# 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:
|
else:
|
||||||
# Fallback to events-based counting
|
# Fallback to events-based counting
|
||||||
events = github_data["events"]
|
events = github_data.get("events", [])
|
||||||
for ev in events:
|
for ev in events:
|
||||||
if ev.get("type") == "PushEvent":
|
if ev.get("type") == "PushEvent":
|
||||||
created = ev.get("created_at", "")[:10]
|
created = ev.get("created_at", "")[:10]
|
||||||
if created:
|
if created:
|
||||||
dt = datetime.fromisoformat(created)
|
dt = datetime.fromisoformat(created)
|
||||||
week_start = (dt - timedelta(days=dt.weekday())).isoformat()[:10]
|
|
||||||
|
# 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", []))
|
commits = len(ev.get("payload", {}).get("commits", []))
|
||||||
weekly[week_start]["commits"] += commits
|
weekly[week_start_str]["commits"] += commits
|
||||||
|
|
||||||
weeks = []
|
weeks = []
|
||||||
for ws in sorted(weekly.keys()):
|
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]:
|
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"]
|
repos = github_data["repos"]
|
||||||
events = github_data["events"]
|
events = github_data["events"]
|
||||||
direct_commits = github_data.get("commits", [])
|
|
||||||
|
|
||||||
lang_to_focus = {
|
lang_to_focus = {
|
||||||
"Python": "Python",
|
"Python": "Python",
|
||||||
@@ -319,14 +364,7 @@ def compute_focus(github_data: dict) -> list[FocusCategory]:
|
|||||||
|
|
||||||
focus_counts = defaultdict(int)
|
focus_counts = defaultdict(int)
|
||||||
|
|
||||||
if direct_commits:
|
# Use events-based counting to track actual activity
|
||||||
# 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")
|
|
||||||
focus_counts[focus] += 1
|
|
||||||
else:
|
|
||||||
# Fallback to events-based counting
|
|
||||||
repo_langs = {}
|
repo_langs = {}
|
||||||
for r in repos:
|
for r in repos:
|
||||||
lang = r.get("language")
|
lang = r.get("language")
|
||||||
@@ -341,6 +379,14 @@ def compute_focus(github_data: dict) -> list[FocusCategory]:
|
|||||||
commits = len(ev.get("payload", {}).get("commits", []))
|
commits = len(ev.get("payload", {}).get("commits", []))
|
||||||
focus_counts[focus] += 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:
|
||||||
|
focus = lang_to_focus.get(lang, "Other")
|
||||||
|
focus_counts[focus] += 1
|
||||||
|
|
||||||
total = sum(focus_counts.values()) or 1
|
total = sum(focus_counts.values()) or 1
|
||||||
return [
|
return [
|
||||||
FocusCategory(
|
FocusCategory(
|
||||||
|
|||||||
+14
-8
@@ -34,15 +34,21 @@ def generate_full_widget(
|
|||||||
print(f"Fetching GitHub data for {username}...")
|
print(f"Fetching GitHub data for {username}...")
|
||||||
github_data = fetch_github_data(username, token)
|
github_data = fetch_github_data(username, token)
|
||||||
|
|
||||||
# Log commit count for debugging
|
# Log contribution counts
|
||||||
commit_count = len(github_data.get("commits", []))
|
total_commits = github_data.get("total_commits", 0)
|
||||||
if commit_count == 0:
|
recent_commits = github_data.get("recent_commits", 0)
|
||||||
print(f" Warning: No commits found. This may be due to:")
|
total_prs = github_data.get("total_prs", 0)
|
||||||
print(f" - No recent PushEvents in last 100 GitHub events")
|
daily_commits = len(github_data.get("commits", []))
|
||||||
print(f" - All commits are from merged PRs")
|
|
||||||
print(f" - GitHub API rate limiting (try with GITHUB_TOKEN)")
|
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:
|
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...")
|
print("Generating widgets...")
|
||||||
widgets = generate_widgets_from_github(github_data, theme)
|
widgets = generate_widgets_from_github(github_data, theme)
|
||||||
|
|||||||
Reference in New Issue
Block a user