|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import re |
| 4 | +import requests |
| 5 | +from datetime import datetime, timedelta |
| 6 | + |
| 7 | +def get_github_data(username, token): |
| 8 | + """Fetch GitHub data using both REST and GraphQL APIs""" |
| 9 | + headers = {"Authorization": f"token {token}"} |
| 10 | + |
| 11 | + # 1. Fetch REST API data (Repos, Stars, Followers) |
| 12 | + rest_url = f"https://api.github.com/users/{username}" |
| 13 | + user_data = requests.get(rest_url, headers=headers).json() |
| 14 | + |
| 15 | + # 2. Fetch GraphQL API data (Contribution Calendar) |
| 16 | + graphql_url = "https://api.github.com/graphql" |
| 17 | + query = """ |
| 18 | + query($login: String!) { |
| 19 | + user(login: $login) { |
| 20 | + contributionsCollection { |
| 21 | + contributionCalendar { |
| 22 | + totalContributions |
| 23 | + weeks { |
| 24 | + contributionDays { |
| 25 | + contributionCount |
| 26 | + date |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + repositories(first: 100, ownerAffiliations: OWNER) { |
| 32 | + nodes { |
| 33 | + stargazerCount |
| 34 | + languages(first: 5, orderBy: {field: SIZE, direction: DESC}) { |
| 35 | + edges { |
| 36 | + size |
| 37 | + node { |
| 38 | + name |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + """ |
| 47 | + variables = {"login": username} |
| 48 | + response = requests.post(graphql_url, json={"query": query, "variables": variables}, headers=headers) |
| 49 | + gql_data = response.json() |
| 50 | + |
| 51 | + if 'errors' in gql_data: |
| 52 | + print(f"GraphQL Errors: {gql_data['errors']}") |
| 53 | + return None |
| 54 | + |
| 55 | + user_gql = gql_data['data']['user'] |
| 56 | + calendar = user_gql['contributionsCollection']['contributionCalendar'] |
| 57 | + |
| 58 | + # Calculate Streak |
| 59 | + all_days = [] |
| 60 | + for week in calendar['weeks']: |
| 61 | + for day in week['contributionDays']: |
| 62 | + all_days.append(day) |
| 63 | + |
| 64 | + all_days.sort(key=lambda x: x['date'], reverse=True) |
| 65 | + |
| 66 | + current_streak = 0 |
| 67 | + today = datetime.now().strftime('%Y-%m-%d') |
| 68 | + yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') |
| 69 | + |
| 70 | + # Start checking from today or yesterday |
| 71 | + start_index = 0 |
| 72 | + if all_days[0]['date'] != today and all_days[0]['date'] != yesterday: |
| 73 | + current_streak = 0 |
| 74 | + else: |
| 75 | + for day in all_days: |
| 76 | + if day['contributionCount'] > 0: |
| 77 | + current_streak += 1 |
| 78 | + else: |
| 79 | + # If we hit a 0 and it's not today's pending count, we stop |
| 80 | + if day['date'] != today: |
| 81 | + break |
| 82 | + |
| 83 | + # Calculate Total Stars |
| 84 | + total_stars = sum(repo['stargazerCount'] for repo in user_gql['repositories']['nodes']) |
| 85 | + |
| 86 | + # Language Stats |
| 87 | + lang_stats = {} |
| 88 | + for repo in user_gql['repositories']['nodes']: |
| 89 | + for lang_edge in repo['languages']['edges']: |
| 90 | + name = lang_edge['node']['name'] |
| 91 | + size = lang_edge['size'] |
| 92 | + lang_stats[name] = lang_stats.get(name, 0) + size |
| 93 | + |
| 94 | + top_languages = sorted(lang_stats.items(), key=lambda x: x[1], reverse=True)[:5] |
| 95 | + |
| 96 | + return { |
| 97 | + 'total_repos': user_data.get('public_repos', 0), |
| 98 | + 'followers': user_data.get('followers', 0), |
| 99 | + 'total_stars': total_stars, |
| 100 | + 'total_contributions': calendar['totalContributions'], |
| 101 | + 'current_streak': current_streak, |
| 102 | + 'top_languages': [l[0] for l in top_languages], |
| 103 | + 'last_updated': datetime.now().strftime('%B %d, %Y') |
| 104 | + } |
| 105 | + |
| 106 | +def format_stats(stats): |
| 107 | + langs = " ".join([f"" for l in stats['top_languages']]) |
| 108 | + |
| 109 | + return f"""### π My GitHub Real-time Stats |
| 110 | +
|
| 111 | +<div align="center"> |
| 112 | +
|
| 113 | +| π₯ **Contribution Streak** | π **Total Contributions** | β **Total Stars** | |
| 114 | +|:---:|:---:|:---:| |
| 115 | +| **{stats['current_streak']} Days** | **{stats['total_contributions']}** | **{stats['total_stars']}** | |
| 116 | +
|
| 117 | +| π Metric | π’ Count | |
| 118 | +|:---|:---:| |
| 119 | +| π¦ **Public Repositories** | {stats['total_repos']} | |
| 120 | +| π₯ **Followers** | {stats['followers']} | |
| 121 | +
|
| 122 | +#### π οΈ Top Technologies |
| 123 | +{langs} |
| 124 | +
|
| 125 | +<sub>Last automated update: {stats['last_updated']} β’ Built with β‘ by Javad</sub> |
| 126 | +</div>""" |
| 127 | + |
| 128 | +def update_readme(stats_content): |
| 129 | + with open('README.md', 'r', encoding='utf-8') as f: |
| 130 | + content = f.read() |
| 131 | + |
| 132 | + # Precise regex to replace the section |
| 133 | + pattern = r'### π GitHub Stats.*?(?=\n---|\Z)' |
| 134 | + new_content = re.sub(pattern, stats_content, content, flags=re.DOTALL) |
| 135 | + |
| 136 | + with os.fdopen(os.open('README.md', os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o644), 'w', encoding='utf-8') as f: |
| 137 | + f.write(new_content) |
| 138 | + |
| 139 | +if __name__ == "__main__": |
| 140 | + TOKEN = os.environ.get('GITHUB_TOKEN') |
| 141 | + USER = os.environ.get('USERNAME', 'javaadde') |
| 142 | + |
| 143 | + if TOKEN: |
| 144 | + data = get_github_data(USER, TOKEN) |
| 145 | + if data: |
| 146 | + update_readme(format_stats(data)) |
| 147 | + print("π Stats updated successfully!") |
| 148 | + else: |
| 149 | + print("β Failed to fetch data.") |
| 150 | + else: |
| 151 | + print("β οΈ No GITHUB_TOKEN found.") |
0 commit comments