-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgithub_stats.py
281 lines (246 loc) · 9.69 KB
/
github_stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import requests
from datetime import datetime
from util import format_duration, is_less_than_2_months_old, format_iso_date, format_date_ddmmyyyy
BASE_URL = "https://api.github.com/graphql"
def fetch_user_data(username: str, token: str):
"""
Fetch user data from GitHub GraphQL API.
Args:
username (str): GitHub username.
token (str): GitHub personal access token.
Returns:
dict: JSON response from GitHub API containing user data or error message.
"""
headers = {"Authorization": f"Bearer {token}"}
query = f"""
{{
user(login: "{username}") {{
name
bio
location
createdAt
avatarUrl
followers {{
totalCount
}}
following {{
totalCount
}}
repositories(ownerAffiliations: OWNER, isFork: false){{
totalCount
}}
contributionsCollection {{
totalCommitContributions
totalPullRequestContributions
totalIssueContributions
}}
}}
}}
"""
try:
response = requests.post(BASE_URL, json={"query": query}, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"errors": str(e)}
def fetch_repo_data(username: str, token: str):
"""
Fetch repository data from GitHub GraphQL API.
Args:
username (str): GitHub username.
token (str): GitHub personal access token.
Returns:
dict: JSON response from GitHub API containing repository data or error message.
"""
headers = {"Authorization": f"Bearer {token}"}
query = f"""
{{
user(login: "{username}") {{
repositories(first: 100, ownerAffiliations: OWNER, isFork: false) {{
totalCount
edges {{
node {{
name
primaryLanguage {{
name
color
}}
}}
}}
}}
}}
}}
"""
try:
response = requests.post(BASE_URL, json={"query": query}, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"errors": str(e)}
def fetch_contribution_data(username: str, token: str):
"""
Fetch contribution data from GitHub GraphQL API.
Args:
username (str): GitHub username.
token (str): GitHub personal access token.
Returns:
dict: JSON response from GitHub API containing contribution data or error message.
"""
headers = {"Authorization": f"Bearer {token}"}
query = f"""
{{
user(login: "{username}") {{
contributionsCollection {{
restrictedContributionsCount
totalPullRequestContributions
totalIssueContributions
contributionCalendar {{
totalContributions
weeks {{
contributionDays {{
contributionCount
date
}}
}}
}}
}}
}}
}}
"""
try:
response = requests.post(BASE_URL, json={"query": query}, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"errors": str(e)}
def process_contribution_data(data: dict):
"""
Process the contribution data from GitHub API response.
Args:
data (dict): JSON response from GitHub API containing contribution data.
Returns:
dict: Processed contribution data including total contributions, highest contribution, streaks, and active days.
"""
try:
contributions_collection = data['data']['user']['contributionsCollection']
calendar = contributions_collection['contributionCalendar']
days = [day for week in calendar['weeks'] for day in week['contributionDays']]
# Safely get contribution counts with fallbacks to 0
public_contributions = calendar.get('totalContributions', 0)
private_contributions = contributions_collection.get('restrictedContributionsCount', 0)
total_contributions = public_contributions + private_contributions
# Ensure we have valid contribution counts
if not isinstance(public_contributions, (int, float)):
public_contributions = 0
if not isinstance(private_contributions, (int, float)):
private_contributions = 0
# Calculate highest contribution
try:
highest_day = max(days, key=lambda day: day['contributionCount'])
highest_contribution = highest_day['contributionCount']
highest_contribution_date = format_date_ddmmyyyy(highest_day['date'])
except (ValueError, KeyError):
highest_contribution = 0
highest_contribution_date = None
current_streak = 0
longest_streak = 0
# Calculate streaks with validation
try:
for day in days:
if day.get('contributionCount', 0) > 0:
current_streak += 1
longest_streak = max(longest_streak, current_streak)
else:
current_streak = 0
except (TypeError, KeyError):
current_streak = 0
longest_streak = 0
# Extract contribution days
weeks = calendar.get("weeks", [])
contribution_days = [day["date"] for week in weeks for day in week["contributionDays"] if day["contributionCount"] > 0]
active_days = len(set(contribution_days)) # Unique active contribution days
return {
"total_contributions": total_contributions,
"public_contributions": public_contributions,
"private_contributions": private_contributions,
"highest_contribution": highest_contribution,
"highest_contribution_date": highest_contribution_date,
"current_streak": current_streak,
"longest_streak": longest_streak,
"active_days": active_days,
"days": days
}
except (KeyError, TypeError) as e:
print(f"Error processing contribution data: {str(e)}")
return {
"total_contributions": 0,
"public_contributions": 0,
"private_contributions": 0,
"highest_contribution": 0,
"current_streak": 0,
"longest_streak": 0,
"days": []
}
def process_language_data(data: dict):
"""
Process the language data from GitHub API response.
Args:
data (dict): JSON response from GitHub API containing repository data.
Returns:
dict: Dictionary of languages with their usage counts and colors.
"""
try:
# Get repositories from the user data
repositories = data['data']['user']['repositories']['edges']
# Process language data
language_data = {}
for edge in repositories:
repo = edge['node']
if repo['primaryLanguage']:
language = repo['primaryLanguage']['name']
color = repo['primaryLanguage'].get('color', '#808080') # Default to grey if no color
if language not in language_data:
language_data[language] = {'count': 0, 'color': color}
language_data[language]['count'] += 1
return language_data
except Exception as e:
print(f"Error processing language data: {str(e)}")
return None
def process_user_data(data: dict):
"""
Process the user data from GitHub API response.
Args:
data (dict): JSON response from GitHub API containing user data.
Returns:
dict: Processed user data including name, bio, location, followers, following, repositories, and contributions.
"""
try:
user_data = data['data']['user']
# Calculate total GitHub days
created_at = user_data.get("createdAt")
formatted_date = format_iso_date(created_at)
less_than_2_months_old = is_less_than_2_months_old(created_at)
github_days = (datetime.now() - datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ")).days
joined_since = format_duration(created_at)
return {
"name": user_data.get("name", ""),
"bio": user_data.get("bio", ""),
"location": user_data.get("location", ""),
"created_at": created_at,
"avatar_url": user_data.get("avatarUrl"),
"followers": user_data.get("followers").get("totalCount", 0),
"following": user_data.get("following").get("totalCount", 0),
"repositories": user_data.get("repositories").get("totalCount", 0),
"total_commits": user_data.get("contributionsCollection").get("totalCommitContributions", 0),
"total_pullrequests": user_data.get("contributionsCollection").get("totalPullRequestContributions", 0),
"total_issues": user_data.get("contributionsCollection").get("totalIssueContributions", 0),
"formatted_date": formatted_date,
"joined_since": joined_since,
"github_days": github_days,
"less_than_2_months_old": less_than_2_months_old
}
except (KeyError, TypeError) as e:
print(f"Error processing contribution data: {str(e)}")
return {
"errors": str(e)
}