-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
777 lines (674 loc) Β· 28.6 KB
/
main.py
File metadata and controls
777 lines (674 loc) Β· 28.6 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
import requests
from dotenv import load_dotenv
from datetime import datetime, timedelta
from typing import Dict, List, Optional
import json
import os
from collections import defaultdict
import time
class GitHubActivityFetcher:
def __init__(self, token: str):
"""
Initialize the GitHub Activity Fetcher.
Args:
token: GitHub personal access token with appropriate permissions
"""
self.token = token
self.api_url = "https://api.github.com/graphql"
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
def test_connection(self) -> Dict:
"""
Test the connection and token validity.
Returns:
User information if successful
"""
query = """
query {
viewer {
login
name
email
}
}
"""
response = requests.post(
self.api_url,
headers=self.headers,
json={"query": query}
)
if response.status_code != 200:
raise Exception(f"API request failed: {response.status_code} - {response.text}")
data = response.json()
if "errors" in data:
raise Exception(f"GraphQL errors: {data['errors']}")
return data["data"]["viewer"]
def _make_graphql_request(self, query: str, variables: Dict, max_retries: int = 3) -> Dict:
"""
Make a GraphQL request with retry logic for timeouts.
Args:
query: GraphQL query string
variables: Query variables
max_retries: Maximum number of retry attempts
Returns:
Response data
"""
for attempt in range(max_retries):
try:
response = requests.post(
self.api_url,
headers=self.headers,
json={"query": query, "variables": variables},
timeout=30 # 30 second timeout
)
if response.status_code == 504: # Gateway Timeout
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 2 # Exponential backoff
print(f" Request timed out. Retrying in {wait_time} seconds...")
time.sleep(wait_time)
continue
else:
raise Exception("GitHub API timeout after multiple retries")
if response.status_code != 200:
# Check if it's an HTML error page
if response.headers.get('content-type', '').startswith('text/html'):
raise Exception(f"API request failed with status {response.status_code}: Gateway/Server Error")
raise Exception(f"API request failed: {response.status_code} - {response.text[:500]}")
data = response.json()
if "errors" in data:
raise Exception(f"GraphQL errors: {data['errors']}")
return data
except requests.exceptions.Timeout:
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 2
print(f" Request timed out. Retrying in {wait_time} seconds...")
time.sleep(wait_time)
continue
else:
raise Exception("Request timeout after multiple retries")
except requests.exceptions.ConnectionError:
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 2
print(f" Connection error. Retrying in {wait_time} seconds...")
time.sleep(wait_time)
continue
else:
raise Exception("Connection error after multiple retries")
def fetch_daily_activity(self, username: str, date: str) -> Dict:
"""
Fetch all GitHub activity for a user on a specific date.
Args:
username: GitHub username
date: Date in YYYY-MM-DD format
Returns:
Dictionary containing all activity data
"""
# Parse date and create date range for the day
target_date = datetime.strptime(date, "%Y-%m-%d")
start_date = target_date.strftime("%Y-%m-%dT00:00:00Z")
end_date = (target_date + timedelta(days=1)).strftime("%Y-%m-%dT00:00:00Z")
print(f"Fetching activity for {username} on {date}...")
# Try full query first, if it fails, use simplified version
try:
return self._fetch_full_activity(username, start_date, end_date, date)
except Exception as e:
if "timeout" in str(e).lower() or "504" in str(e):
print(" Full query timed out. Trying simplified query...")
return self._fetch_simplified_activity(username, start_date, end_date, date)
else:
raise e
def _fetch_full_activity(self, username: str, start_date: str, end_date: str, date: str) -> Dict:
"""
Fetch full activity data with all details.
"""
# First, get basic user info and contribution summary
query = """
query($username: String!, $from: DateTime!, $to: DateTime!) {
user(login: $username) {
login
name
email
contributionsCollection(from: $from, to: $to) {
totalCommitContributions
totalPullRequestContributions
totalPullRequestReviewContributions
totalIssueContributions
# Commit contributions by repository
commitContributionsByRepository(maxRepositories: 100) {
repository {
nameWithOwner
url
}
contributions(first: 100) {
totalCount
nodes {
commitCount
occurredAt
}
}
}
# Pull request contributions
pullRequestContributions(first: 100) {
totalCount
nodes {
occurredAt
pullRequest {
title
url
number
state
createdAt
repository {
nameWithOwner
}
}
}
}
# Pull request review contributions
pullRequestReviewContributions(first: 100) {
totalCount
nodes {
occurredAt
pullRequestReview {
state
createdAt
bodyText
}
pullRequest {
title
url
number
state
author {
login
}
repository {
nameWithOwner
}
}
}
}
# Issue contributions
issueContributions(first: 100) {
totalCount
nodes {
occurredAt
issue {
title
url
number
state
repository {
nameWithOwner
}
}
}
}
}
}
}
"""
variables = {
"username": username,
"from": start_date,
"to": end_date
}
data = self._make_graphql_request(query, variables)
variables = {
"username": username,
"from": start_date,
"to": end_date
}
data = self._make_graphql_request(query, variables)
if not data.get("data") or not data["data"].get("user"):
raise Exception(f"User '{username}' not found")
# Process with simplified data structure
user_data = data["data"]["user"]
contributions = user_data.get("contributionsCollection", {})
activity = {
"date": date,
"user": {
"login": user_data.get("login", "Unknown"),
"name": user_data.get("name", user_data.get("login", "Unknown")),
"email": user_data.get("email", "")
},
"summary": {
"total_commits": contributions.get("totalCommitContributions", 0),
"total_prs_authored": contributions.get("totalPullRequestContributions", 0),
"total_prs_reviewed": contributions.get("totalPullRequestReviewContributions", 0),
"total_issues": contributions.get("totalIssueContributions", 0)
},
"authored_prs": [],
"reviewed_prs": [],
"commits_by_repo": {},
"issues": []
}
# Process simplified PR data
pr_contribs = contributions.get("pullRequestContributions", {}).get("nodes", [])
for pr_contrib in pr_contribs:
pr = pr_contrib.get("pullRequest", {})
if pr:
activity["authored_prs"].append({
"title": pr.get("title", ""),
"url": f"https://github.com/{pr.get('repository', {}).get('nameWithOwner', '')}/pull/{pr.get('number', '')}",
"number": pr.get("number", 0),
"repository": pr.get("repository", {}).get("nameWithOwner", ""),
"state": pr.get("state", ""),
"created_at": "",
"occurred_at": ""
})
# Process simplified review data
review_contribs = contributions.get("pullRequestReviewContributions", {}).get("nodes", [])
for review_contrib in review_contribs:
pr = review_contrib.get("pullRequest", {})
review = review_contrib.get("pullRequestReview", {})
if pr and review:
activity["reviewed_prs"].append({
"pr_title": pr.get("title", ""),
"pr_url": f"https://github.com/{pr.get('repository', {}).get('nameWithOwner', '')}/pull/{pr.get('number', '')}",
"pr_number": pr.get("number", 0),
"pr_author": "Unknown",
"repository": pr.get("repository", {}).get("nameWithOwner", ""),
"review_state": review.get("state", ""),
"review_body": "",
"occurred_at": ""
})
# Process simplified issue data
issue_contribs = contributions.get("issueContributions", {}).get("nodes", [])
for issue_contrib in issue_contribs:
issue = issue_contrib.get("issue", {})
if issue:
activity["issues"].append({
"title": issue.get("title", ""),
"url": f"https://github.com/{issue.get('repository', {}).get('nameWithOwner', '')}/issues/{issue.get('number', '')}",
"number": issue.get("number", 0),
"repository": issue.get("repository", {}).get("nameWithOwner", ""),
"state": "",
"occurred_at": ""
})
print(" Note: Using simplified data due to API limitations")
return activity
def _fetch_simplified_activity(self, username: str, start_date: str, end_date: str, date: str) -> Dict:
"""
Fetch simplified activity data with fewer details to avoid timeouts.
"""
# Simplified query with just the essentials
query = """
query($username: String!, $from: DateTime!, $to: DateTime!) {
user(login: $username) {
login
name
email
contributionsCollection(from: $from, to: $to) {
totalCommitContributions
totalPullRequestContributions
totalPullRequestReviewContributions
totalIssueContributions
# Pull request contributions (simplified)
pullRequestContributions(first: 50) {
nodes {
pullRequest {
title
number
state
repository {
nameWithOwner
}
}
}
}
# Pull request review contributions (simplified)
pullRequestReviewContributions(first: 50) {
nodes {
pullRequestReview {
state
}
pullRequest {
title
number
repository {
nameWithOwner
}
}
}
}
# Issue contributions (simplified)
issueContributions(first: 50) {
nodes {
issue {
title
number
repository {
nameWithOwner
}
}
}
}
}
}
}
"""
if not data.get("data") or not data["data"].get("user"):
raise Exception(f"User '{username}' not found")
return self._process_activity_data(data["data"]["user"], date)
def _process_activity_data(self, user_data: Dict, date: str) -> Dict:
"""
Process and organize the raw activity data.
Args:
user_data: Raw user data from GraphQL query
date: Target date
Returns:
Organized activity dictionary
"""
contributions = user_data.get("contributionsCollection", {})
activity = {
"date": date,
"user": {
"login": user_data.get("login", "Unknown"),
"name": user_data.get("name", user_data.get("login", "Unknown")),
"email": user_data.get("email", "")
},
"summary": {
"total_commits": contributions.get("totalCommitContributions", 0),
"total_prs_authored": contributions.get("totalPullRequestContributions", 0),
"total_prs_reviewed": contributions.get("totalPullRequestReviewContributions", 0),
"total_issues": contributions.get("totalIssueContributions", 0)
},
"authored_prs": [],
"reviewed_prs": [],
"commits_by_repo": {},
"issues": []
}
# Process authored PRs
pr_contribs = contributions.get("pullRequestContributions", {}).get("nodes", [])
for pr_contrib in pr_contribs:
pr = pr_contrib.get("pullRequest", {})
if pr:
activity["authored_prs"].append({
"title": pr.get("title", ""),
"url": pr.get("url", ""),
"number": pr.get("number", 0),
"repository": pr.get("repository", {}).get("nameWithOwner", ""),
"state": pr.get("state", ""),
"created_at": pr.get("createdAt", ""),
"occurred_at": pr_contrib.get("occurredAt", "")
})
# Process reviewed PRs
review_contribs = contributions.get("pullRequestReviewContributions", {}).get("nodes", [])
for review_contrib in review_contribs:
pr = review_contrib.get("pullRequest", {})
review = review_contrib.get("pullRequestReview", {})
if pr and review:
activity["reviewed_prs"].append({
"pr_title": pr.get("title", ""),
"pr_url": pr.get("url", ""),
"pr_number": pr.get("number", 0),
"pr_author": pr.get("author", {}).get("login", "Unknown") if pr.get("author") else "Unknown",
"repository": pr.get("repository", {}).get("nameWithOwner", ""),
"review_state": review.get("state", ""),
"review_body": (review.get("bodyText", "") or "")[:100],
"occurred_at": review_contrib.get("occurredAt", "")
})
# Process commits by repository
repo_commits = contributions.get("commitContributionsByRepository", [])
for repo_commit in repo_commits:
repo = repo_commit.get("repository", {})
repo_name = repo.get("nameWithOwner", "")
contrib_nodes = repo_commit.get("contributions", {}).get("nodes", [])
total_commits = sum(
node.get("commitCount", 0)
for node in contrib_nodes
)
if total_commits > 0 and repo_name:
activity["commits_by_repo"][repo_name] = {
"count": total_commits,
"url": repo.get("url", "")
}
# Process issues
issue_contribs = contributions.get("issueContributions", {}).get("nodes", [])
for issue_contrib in issue_contribs:
issue = issue_contrib.get("issue", {})
if issue:
activity["issues"].append({
"title": issue.get("title", ""),
"url": issue.get("url", ""),
"number": issue.get("number", 0),
"repository": issue.get("repository", {}).get("nameWithOwner", ""),
"state": issue.get("state", ""),
"occurred_at": issue_contrib.get("occurredAt", "")
})
return activity
def fetch_recent_commits(self, username: str, date: str, repo_owner: str, repo_name: str) -> List[Dict]:
"""
Fetch commits for a specific repository on a given date.
Args:
username: GitHub username
date: Date in YYYY-MM-DD format
repo_owner: Repository owner
repo_name: Repository name
Returns:
List of commits
"""
target_date = datetime.strptime(date, "%Y-%m-%d")
since = target_date.strftime("%Y-%m-%dT00:00:00Z")
until = (target_date + timedelta(days=1)).strftime("%Y-%m-%dT00:00:00Z")
query = """
query($owner: String!, $name: String!, $since: GitTimestamp!, $until: GitTimestamp!) {
repository(owner: $owner, name: $name) {
defaultBranchRef {
target {
... on Commit {
history(first: 100, since: $since, until: $until) {
nodes {
oid
message
committedDate
additions
deletions
changedFilesIfAvailable
url
author {
name
email
user {
login
}
}
}
}
}
}
}
}
}
"""
variables = {
"owner": repo_owner,
"name": repo_name,
"since": since,
"until": until
}
response = requests.post(
self.api_url,
headers=self.headers,
json={"query": query, "variables": variables}
)
if response.status_code != 200:
return []
data = response.json()
if "errors" in data or not data.get("data"):
return []
commits = []
repo_data = data["data"].get("repository", {})
if repo_data and repo_data.get("defaultBranchRef"):
target = repo_data["defaultBranchRef"].get("target", {})
history = target.get("history", {})
nodes = history.get("nodes", [])
for commit in nodes:
author_user = commit.get("author", {}).get("user", {})
if author_user and author_user.get("login") == username:
commits.append({
"sha": commit.get("oid", "")[:7],
"message": commit.get("message", "").split('\n')[0],
"url": commit.get("url", ""),
"additions": commit.get("additions", 0),
"deletions": commit.get("deletions", 0),
"changed_files": commit.get("changedFilesIfAvailable", 0),
"committed_at": commit.get("committedDate", "")
})
return commits
def print_activity_summary(self, activity: Dict):
"""
Print a formatted summary of the daily activity.
Args:
activity: Activity dictionary from fetch_daily_activity
"""
print(f"\n{'='*60}")
print(f"GitHub Activity Report for {activity['user']['name']} ({activity['user']['login']})")
print(f"Date: {activity['date']}")
print(f"{'='*60}\n")
# Summary
print("π SUMMARY")
print(f" β’ Total Commits: {activity['summary']['total_commits']}")
print(f" β’ PRs Authored: {activity['summary']['total_prs_authored']}")
print(f" β’ PRs Reviewed: {activity['summary']['total_prs_reviewed']}")
print(f" β’ Issues Created/Updated: {activity['summary']['total_issues']}")
print()
# Authored PRs
if activity['authored_prs']:
print("βοΈ AUTHORED PULL REQUESTS")
for pr in activity['authored_prs']:
print(f" β’ [{pr['repository']}#{pr['number']}] {pr['title']}")
print(f" Status: {pr['state']} | URL: {pr['url']}")
print()
# Reviewed PRs
if activity['reviewed_prs']:
print("π REVIEWED PULL REQUESTS")
for review in activity['reviewed_prs']:
print(f" β’ [{review['repository']}#{review['pr_number']}] {review['pr_title']}")
print(f" Author: {review['pr_author']} | Review: {review['review_state']}")
if review['review_body']:
print(f" Comment: {review['review_body']}...")
print()
# Commits by repository
if activity['commits_by_repo']:
print("π» COMMITS BY REPOSITORY")
for repo, info in activity['commits_by_repo'].items():
count = info['count'] if isinstance(info, dict) else info
print(f" β’ {repo}: {count} commit{'s' if count > 1 else ''}")
print()
# Issues
if activity['issues']:
print("π ISSUES CREATED/UPDATED")
for issue in activity['issues']:
print(f" β’ [{issue['repository']}#{issue['number']}] {issue['title']}")
print(f" Status: {issue['state']} | URL: {issue['url']}")
print()
# If no activity
if not any([
activity['summary']['total_commits'],
activity['summary']['total_prs_authored'],
activity['summary']['total_prs_reviewed'],
activity['summary']['total_issues']
]):
print("No activity found for this date.")
def print_compact_summary(self, activity: Dict):
"""
Print a compact grouped summary of activity.
Groups PRs and issues by repository, with reviewed PRs at the bottom.
Args:
activity: Activity dictionary from fetch_daily_activity
"""
print(f"\n{'='*60}")
print("COMPACT ACTIVITY SUMMARY")
print(f"Date: {activity['date']}")
print(f"{'='*60}\n")
# Group authored PRs and issues by repository
repos_with_activity = defaultdict(lambda: {"prs": [], "issues": []})
# Add authored PRs
for pr in activity['authored_prs']:
repo = pr['repository']
if repo:
repos_with_activity[repo]["prs"].append(f"#{pr['number']}")
# Add issues
for issue in activity['issues']:
repo = issue['repository']
if repo:
repos_with_activity[repo]["issues"].append(f"#{issue['number']}")
# Print PRs and Issues grouped by repository
if repos_with_activity:
print("PRs AUTHORED / WORKED ON & ISSUES:")
for repo in sorted(repos_with_activity.keys()):
items = repos_with_activity[repo]
all_items = []
# Add PR numbers
all_items.extend(items["prs"])
# Add issue numbers with (issue) marker
all_items.extend([f"{num}(issue)" for num in items["issues"]])
if all_items:
print(f"{repo} {' '.join(all_items)}")
print()
# Group reviewed PRs by repository
reviewed_by_repo = defaultdict(list)
for review in activity['reviewed_prs']:
repo = review['repository']
if repo:
reviewed_by_repo[repo].append(f"#{review['pr_number']}")
# Print reviewed PRs
if reviewed_by_repo:
print("REVIEWED PRs:")
for repo in sorted(reviewed_by_repo.keys()):
pr_numbers = ' '.join(reviewed_by_repo[repo])
print(f"{repo} {pr_numbers}")
print()
# If no activity
if not repos_with_activity and not reviewed_by_repo:
print("No PR or Issue activity found for this date.")
print()
# Example usage
if __name__ == "__main__":
load_dotenv()
TOKEN = os.getenv("GITHUB_TOKEN")
USERNAME = os.getenv("GITHUB_USERNAME") # Replace with the GitHub username to track
DATE = datetime.now().strftime("%Y-%m-%d") # Today - Format: YYYY-MM-DD
try:
# Initialize fetcher
fetcher = GitHubActivityFetcher(TOKEN)
# Test connection first
print("Testing connection...")
viewer = fetcher.test_connection()
print(f"β
Connected as: {viewer['login']}")
print()
# Fetch daily activity
activity = fetcher.fetch_daily_activity(USERNAME, DATE)
# Print the new compact summary
fetcher.print_compact_summary(activity)
# Print the detailed summary
fetcher.print_activity_summary(activity)
# Save to JSON
filename = f"github_activity_{USERNAME}_{DATE}.json"
with open(filename, "w") as f:
json.dump(activity, f, indent=2)
print(f"\nβ
Activity data saved to {filename}")
# Optional: Fetch detailed commits for specific repos
if activity['commits_by_repo']:
print("\nπ Fetching detailed commits...")
for repo_name in list(activity['commits_by_repo'].keys())[:3]: # Limit to first 3 repos
parts = repo_name.split('/')
if len(parts) == 2:
owner, name = parts
commits = fetcher.fetch_recent_commits(USERNAME, DATE, owner, name)
if commits:
print(f"\nCommits in {repo_name}:")
for commit in commits:
print(f" β’ {commit['sha']}: {commit['message']}")
print(f" +{commit['additions']} -{commit['deletions']} files: {commit['changed_files']}")
except Exception as e:
print(f"β Error: {e}")
print("\nTroubleshooting tips:")
print("1. Make sure your token has the correct permissions (repo, read:user)")
print("2. Verify the username is correct")
print("3. Check that the date format is YYYY-MM-DD")
print("4. Ensure your token is not expired")