-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrexec.py
More file actions
1816 lines (1467 loc) · 84.9 KB
/
Copy pathPrexec.py
File metadata and controls
1816 lines (1467 loc) · 84.9 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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import urllib.request
import urllib.error
import json
import time
import sys
import os
import threading
from datetime import datetime, timedelta
# Check and import matplotlib
try:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.dates as mdates
from matplotlib.patches import FancyBboxPatch
import numpy as np
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
print("⚠️ matplotlib not found. Install it with: pip install matplotlib numpy")
print(" Continuing without graph generation...\n")
# -------------------------
# Safe Formatting Helper
# -------------------------
def safe_str(value, default='N/A'):
"""Safely convert value to string, handling None"""
if value is None:
return default
return str(value)
def safe_int(value, default=0):
"""Safely convert value to int, handling None"""
if value is None:
return default
try:
return int(value)
except (ValueError, TypeError):
return default
# -------------------------
# Cross-Platform Utilities
# -------------------------
def get_home_directory():
"""Get home directory cross-platform"""
return os.path.expanduser("~")
def get_desktop_path():
"""Get desktop path cross-platform"""
home = get_home_directory()
return os.path.join(home, "Desktop")
def get_documents_path():
"""Get documents path cross-platform"""
home = get_home_directory()
return os.path.join(home, "Documents")
def clear_screen():
"""Clear screen cross-platform"""
os.system('cls' if sys.platform == 'win32' else 'clear')
def get_os_name():
"""Get friendly OS name"""
if sys.platform == "win32":
return "Windows"
elif sys.platform == "darwin":
return "macOS"
else:
return "Linux"
# -------------------------
# Animation Utilities
# -------------------------
class LoadingSpinner:
"""Animated loading spinner"""
def __init__(self, message="Loading"):
self.message = message
self.running = False
self.thread = None
self.spinner_chars = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
def spin(self):
i = 0
while self.running:
sys.stdout.write(f"\r {self.spinner_chars[i % len(self.spinner_chars)]} {self.message}")
sys.stdout.flush()
time.sleep(0.1)
i += 1
def start(self):
self.running = True
self.thread = threading.Thread(target=self.spin)
self.thread.start()
def stop(self, final_message=None):
self.running = False
if self.thread:
self.thread.join()
if final_message:
sys.stdout.write(f"\r ✅ {final_message}\n")
else:
sys.stdout.write(f"\r ✅ {self.message} - Done!\n")
sys.stdout.flush()
def progress_bar(current, total, prefix="Progress", length=40):
"""Display animated progress bar"""
if total == 0:
total = 1
percent = (current / total) * 100
filled = int(length * current // total)
bar = "█" * filled + "░" * (length - filled)
sys.stdout.write(f"\r {prefix}: [{bar}] {percent:.1f}% ({current}/{total})")
sys.stdout.flush()
def show_scanning_animation(text, duration=1.0):
"""Show scanning dots animation"""
end_time = time.time() + duration
dots = 0
while time.time() < end_time:
sys.stdout.write(f"\r 🔍 {text}" + "." * dots + " ")
sys.stdout.flush()
dots = (dots + 1) % 4
time.sleep(0.3)
sys.stdout.write(f"\r ✅ {text} - Complete! \n")
sys.stdout.flush()
# -------------------------
# Header and UI
# -------------------------
def print_header():
clear_screen()
header = """
╔════════════════════════════════════════════════════════════════╗
║ ║
║ ██████╗ ██████╗ ███████╗ ██╗ ██╗ ███████╗ ██████╗ ║
║ ██╔══██╗ ██╔══██╗ ██╔════╝ ╚██╗██╔╝ ██╔════╝ ██╔════╝ ║
║ ██████╔╝ ██████╔╝ █████╗ ╚███╔╝ █████╗ ██║ ║
║ ██╔═══╝ ██╔══██╗ ██╔══╝ ██╔██╗ ██╔══╝ ██║ ║
║ ██║ ██║ ██║ ███████╗ ██╔╝ ██╗ ███████╗ ╚██████╗ ║
║ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ║
║ ║
║ !! GitHub Pull Request Analyzer & Visualizer !! ║
║ ║
╠════════════════════════════════════════════════════════════════╣
║ ║
║ Analyze │ PRsGenerate Graphs │ Export Reports ║
║ ║
╚════════════════════════════════════════════════════════════════╝
"""
print(header)
print(f" 🖥️ Running on: {get_os_name()}")
print(f" 📁 Home Directory: {get_home_directory()}")
print(f" 📊 Matplotlib: {'✅ Available' if MATPLOTLIB_AVAILABLE else '❌ Not Installed'}")
print()
def show_system_info():
"""Display system information"""
print("\n╔═══════════════════════════════════════════════════════════════════════════╗")
print("║ 📋 SYSTEM INFORMATION ║")
print("╠═════════════════════════════════════════════════════════════════════════════╣")
print(f"║ Operating System : {get_os_name():<53} ║")
print(f"║ Python Version : {sys.version.split()[0]:<53} ║")
print(f"║ Home Directory : {get_home_directory()[:53]:<53} ║")
print(f"║ Current Directory : {os.getcwd()[:53]:<53} ║")
print(f"║ Matplotlib : {'Installed ✅' if MATPLOTLIB_AVAILABLE else 'Not Installed ❌':<53} ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝\n")
def show_main_menu():
"""Display main menu"""
print("\n╔═══════════════════════════════════════════════════════════════════════════╗")
print("║ SELECT AN OPTION ║")
print("╠═════════════════════════════════════════════════════════════════════════════╣")
print("║ ║")
print("║ [1] 🔍 Quick Scan - Basic PR statistics ║")
print("║ [2] 🔬 Deep Scan - Detailed analysis with graphs ║")
print("║ [3] ℹ️ System Info - Show system information ║")
print("║ [4] 🚪 Exit - Close the application ║")
print("║ ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝")
# -------------------------
# GitHub API Utilities
# -------------------------
def get_github_token():
"""Get GitHub token from environment or .env file"""
token = os.getenv("GITHUB_TOKEN")
if not token and os.path.exists(".env"):
try:
with open(".env") as f:
for line in f:
if line.startswith("GITHUB_TOKEN="):
token = line.strip().split("=", 1)[1]
except Exception:
pass
return token
def make_api_request(url, token=None):
"""Make API request"""
req = urllib.request.Request(url)
req.add_header("User-Agent", "pr-checker-script")
if token:
req.add_header("Authorization", f"token {token}")
try:
with urllib.request.urlopen(req, timeout=30) as response:
return json.loads(response.read()), None
except urllib.error.HTTPError as e:
try:
error_body = e.read()
return None, json.loads(error_body).get("message", str(e))
except Exception:
return None, str(e)
except urllib.error.URLError as e:
return None, f"Connection error: {str(e.reason)}"
except Exception as e:
return None, str(e)
def check_rate_limit(token):
"""Check and display API rate limit"""
print("\n╔═══════════════════════════════════════════════════════════════════════════╗")
print("║ 🔄 CHECKING API RATE LIMIT ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝")
spinner = LoadingSpinner("Connecting to GitHub API")
spinner.start()
data, error = make_api_request("https://api.github.com/rate_limit", token)
time.sleep(0.5)
spinner.stop("Connected to GitHub API")
if data:
rate_data = data.get("rate", {})
remaining = safe_int(rate_data.get("remaining"), 0)
limit = safe_int(rate_data.get("limit"), 60)
reset_timestamp = rate_data.get("reset")
if reset_timestamp:
reset_time = datetime.fromtimestamp(reset_timestamp).strftime("%H:%M:%S")
else:
reset_time = "Unknown"
if limit > 0:
percent = (remaining / limit) * 100
else:
percent = 0
bar_length = 30
filled = int(bar_length * remaining // max(limit, 1))
bar = "█" * filled + "░" * (bar_length - filled)
if percent > 50:
status = "🟢 Good"
elif percent > 20:
status = "🟡 Moderate"
else:
status = "🔴 Low"
print(f"\n API Rate Limit: [{bar}] {remaining}/{limit}")
print(f" Status: {status} | Resets at: {reset_time}")
return remaining > 0
else:
print(f" ⚠️ Could not check rate limit: {safe_str(error, 'Unknown error')}")
return True
def verify_username(username, token):
"""Verify if GitHub username exists"""
print(f"\n 🔍 Verifying username '@{username}'...")
spinner = LoadingSpinner(f"Looking up @{username}")
spinner.start()
url = f"https://api.github.com/users/{username}"
data, error = make_api_request(url, token)
time.sleep(0.8)
spinner.stop()
if data:
name = safe_str(data.get('name'), 'N/A')[:45]
location = safe_str(data.get('location'), 'N/A')[:45]
public_repos = safe_int(data.get('public_repos'), 0)
followers = safe_int(data.get('followers'), 0)
created_at = safe_str(data.get('created_at'), 'N/A')[:10]
print("\n╔═════════════════════════════════════════════════════════════════════════════╗")
print("║ ✅ USER FOUND ║")
print("╠═════════════════════════════════════════════════════════════════════════════╣")
print(f"║ 👤 Name : {name:<55} ║")
print(f"║ 📍 Location : {location:<55} ║")
print(f"║ 📦 Public Repos : {public_repos:<55} ║")
print(f"║ 👥 Followers : {followers:<55} ║")
print(f"║ 📅 Joined : {created_at:<55} ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝")
return True, data
else:
print(f" ❌ User '@{username}' not found!")
return False, None
# -------------------------
# PR Fetching Engine
# -------------------------
def fetch_all_prs_animated(username, token=None):
"""Fetch ALL PRs using Search API"""
print("\n╔═══════════════════════════════════════════════════════════════════════════╗")
print("║ 🔍 STARTING PR SCAN ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝")
print("\n ┌─ PHASE 1: INITIALIZATION")
show_scanning_animation("Initializing scan engine", 0.8)
print(" └─ ✓ Phase 1 Complete\n")
print(" ┌─ PHASE 2: CONNECTING TO GITHUB")
show_scanning_animation("Establishing secure connection", 0.6)
print(" └─ ✓ Phase 2 Complete\n")
print(" ┌─ PHASE 3: FETCHING PULL REQUESTS")
page = 1
all_prs = []
url = f"https://api.github.com/search/issues?q=author:{username}+type:pr&per_page=100&page=1"
data, error = make_api_request(url, token)
if error:
print(f" │ ❌ Error: {safe_str(error, 'Unknown error')}")
return []
if not data:
print(f" │ ❌ No data received from API")
return []
total_count = safe_int(data.get("total_count"), 0)
print(f" │ 📊 Total PRs to fetch: {total_count}")
if total_count == 0:
print(" │ ⚠️ No PRs found for this user")
print(" └─ ✓ Phase 3 Complete\n")
return []
total_pages = (total_count + 99) // 100
while True:
progress_bar(page, total_pages, "Fetching PRs", 40)
url = f"https://api.github.com/search/issues?q=author:{username}+type:pr&per_page=100&page={page}"
data, error = make_api_request(url, token)
if error or not data:
break
items = data.get("items", [])
if not items:
break
all_prs.extend(items)
time.sleep(0.2)
if len(items) < 100:
break
page += 1
print(f"\n │ ✅ Successfully fetched {len(all_prs)} PRs")
print(" └─ ✓ Phase 3 Complete\n")
if len(all_prs) > 0:
print(" ┌─ PHASE 4: PROCESSING DATA")
for i in range(len(all_prs)):
progress_bar(i + 1, len(all_prs), "Processing PRs", 40)
time.sleep(0.01)
print(f"\n └─ ✓ Phase 4 Complete\n")
print("╔═════════════════════════════════════════════════════════════════════════════╗")
print(f"║ ✅ SCAN COMPLETE - {len(all_prs)} PULL REQUESTS FOUND ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝")
return all_prs
# -------------------------
# PR Type Detection Engine
# -------------------------
# PR Type Keywords
PR_TYPE_PATTERNS = {
"🐛 Bug Fix": {
"keywords": ["fix", "bug", "issue", "error", "crash", "broken", "patch", "hotfix",
"resolve", "solving", "repair", "correct", "debug", "fault", "defect"],
"title_weight": 2,
"body_weight": 1
},
"✨ Feature": {
"keywords": ["feature", "add", "new", "implement", "create", "introduce", "support",
"enable", "allow", "capability", "functionality", "enhancement"],
"title_weight": 2,
"body_weight": 1
},
"📚 Documentation": {
"keywords": ["doc", "readme", "documentation", "comment", "guide", "tutorial",
"wiki", "changelog", "license", "contributing", "api doc", "jsdoc",
"docstring", "typo in doc", "update readme"],
"title_weight": 2,
"body_weight": 1
},
"♻️ Refactor": {
"keywords": ["refactor", "restructure", "reorganize", "cleanup", "clean up",
"improve code", "code quality", "simplify", "optimize code",
"better structure", "rewrite", "modernize"],
"title_weight": 2,
"body_weight": 1
},
"📦 Dependency": {
"keywords": ["dependency", "dependencies", "package", "npm", "pip", "yarn",
"update package", "upgrade", "bump", "version bump", "security update",
"dependabot", "renovate", "greenkeeper", "snyk"],
"title_weight": 2,
"body_weight": 1
},
"🧪 Test": {
"keywords": ["test", "testing", "spec", "unit test", "integration test", "e2e",
"coverage", "jest", "pytest", "mocha", "cypress", "selenium",
"test case", "test suite", "tdd", "bdd"],
"title_weight": 2,
"body_weight": 1
},
"⚡ Performance": {
"keywords": ["performance", "optimize", "speed", "faster", "efficient", "memory",
"cache", "lazy load", "async", "parallel", "benchmark", "profiling",
"reduce load", "improve speed"],
"title_weight": 2,
"body_weight": 1
},
"🎨 Style/Lint": {
"keywords": ["style", "lint", "format", "prettier", "eslint", "formatting",
"code style", "indentation", "whitespace", "semicolon", "trailing",
"black", "flake8", "pylint", "rubocop"],
"title_weight": 2,
"body_weight": 1
},
"🌐 Translation": {
"keywords": ["translation", "translate", "i18n", "l10n", "locale", "language",
"internationalization", "localization", "multilingual", "lang"],
"title_weight": 2,
"body_weight": 1
},
"🔧 Config": {
"keywords": ["config", "configuration", "settings", "env", "environment",
"ci/cd", "workflow", "github action", "travis", "jenkins", "docker",
"kubernetes", "yaml", "json config"],
"title_weight": 2,
"body_weight": 1
},
"🔒 Security": {
"keywords": ["security", "vulnerability", "cve", "xss", "csrf", "injection",
"auth", "authentication", "authorization", "encrypt", "ssl", "https",
"sanitize", "escape", "secure"],
"title_weight": 2,
"body_weight": 1
},
"🗑️ Deprecation": {
"keywords": ["deprecate", "remove", "delete", "drop support", "end of life",
"obsolete", "legacy", "cleanup old", "remove unused"],
"title_weight": 2,
"body_weight": 1
}
}
# Tool Detection Patterns
TOOL_PATTERNS = {
"🖥️ GitHub Web": {
"patterns": [], # Default if no specific tool detected
"body_hints": ["<!-- -->", "## description", "## changes", "### checklist"],
"is_default": True
},
"💻 GitHub CLI (gh)": {
"patterns": ["created via gh cli", "gh pr create", "via github cli",
"github.com/cli/cli"],
"body_hints": []
},
"🔧 Git CLI + API": {
"patterns": [],
"body_hints": [],
"empty_body": True # Short or empty body often indicates API/CLI
},
"🤖 Dependabot": {
"patterns": ["dependabot", "dependabot[bot]", "dependabot-preview"],
"body_hints": ["bumps", "from ", " to ", "release notes", "changelog", "commits"]
},
"🔄 Renovate Bot": {
"patterns": ["renovate", "renovate[bot]", "renovatebot"],
"body_hints": ["this pr contains", "renovate", "datasource", "package update"]
},
"🛡️ Snyk Bot": {
"patterns": ["snyk", "snyk-bot", "snyk[bot]"],
"body_hints": ["snyk", "vulnerability", "security upgrade"]
},
"📦 Greenkeeper": {
"patterns": ["greenkeeper", "greenkeeper[bot]"],
"body_hints": ["greenkeeper", "update", "version"]
},
"🖼️ ImgBot": {
"patterns": ["imgbot", "imgbot[bot]"],
"body_hints": ["image", "optimize", "compression", "imgbot"]
},
"👥 All Contributors": {
"patterns": ["allcontributors", "all-contributors"],
"body_hints": ["add", "contributor", "all-contributors"]
},
"🚀 Release Bot": {
"patterns": ["release-bot", "semantic-release", "release-please"],
"body_hints": ["release", "version", "changelog"]
},
"⚙️ GitHub Actions": {
"patterns": ["github-actions", "github-actions[bot]"],
"body_hints": ["automated", "workflow", "action"]
},
"🖱️ GitHub Desktop": {
"patterns": ["github desktop"],
"body_hints": []
},
"💜 VS Code": {
"patterns": ["vscode", "vs code"],
"body_hints": ["vscode", "visual studio code"]
},
"🧠 JetBrains IDE": {
"patterns": ["intellij", "pycharm", "webstorm", "phpstorm", "idea"],
"body_hints": ["jetbrains", "intellij"]
},
"🐙 GitKraken": {
"patterns": ["gitkraken"],
"body_hints": ["gitkraken"]
},
"🌳 Sourcetree": {
"patterns": ["sourcetree"],
"body_hints": ["sourcetree"]
},
"☁️ GitHub Codespaces": {
"patterns": ["codespaces", "codespace"],
"body_hints": ["codespace", "github.dev"]
},
"🌐 GitPod": {
"patterns": ["gitpod"],
"body_hints": ["gitpod"]
}
}
def detect_pr_type(pr):
"""Detect the type/category of PR based on content analysis"""
title = safe_str(pr.get("title"), "").lower()
body = safe_str(pr.get("body"), "").lower()
scores = {}
for pr_type, config in PR_TYPE_PATTERNS.items():
score = 0
keywords = config["keywords"]
title_weight = config["title_weight"]
body_weight = config["body_weight"]
for keyword in keywords:
if keyword in title:
score += title_weight
if keyword in body:
score += body_weight
if score > 0:
scores[pr_type] = score
if scores:
return max(scores, key=scores.get)
return "📝 General"
def detect_pr_tool(pr):
"""Detect which tool was used to create the PR"""
body = safe_str(pr.get("body"), "").lower()
user_data = pr.get("user") or {}
user = safe_str(user_data.get("login"), "").lower()
# Check for bot accounts first
for tool_name, config in TOOL_PATTERNS.items():
if config.get("is_default"):
continue
patterns = config.get("patterns", [])
body_hints = config.get("body_hints", [])
# Check user login
for pattern in patterns:
if pattern in user:
return tool_name
# Check body content
for pattern in patterns:
if pattern in body:
return tool_name
for hint in body_hints:
if hint in body:
return tool_name
# Check for empty/minimal body (likely API/CLI)
if len(body.strip()) < 20:
return "🔧 Git CLI + API"
# Default to web interface
return "🖥️ GitHub Web"
def categorize_prs_animated(prs):
"""Categorize all PRs by type and tool"""
print("\n ┌─ CATEGORIZING PR TYPES & TOOLS")
type_categories = {}
tool_categories = {}
total_prs = len(prs)
for i, pr in enumerate(prs):
progress_bar(i + 1, total_prs, "Analyzing PRs", 40)
# Detect PR type
pr_type = detect_pr_type(pr)
if pr_type not in type_categories:
type_categories[pr_type] = []
type_categories[pr_type].append(pr)
# Detect tool used
tool = detect_pr_tool(pr)
if tool not in tool_categories:
tool_categories[tool] = []
tool_categories[tool].append(pr)
# Store in PR for later use
pr["_detected_type"] = pr_type
pr["_detected_tool"] = tool
time.sleep(0.005)
print(f"\n │ ✅ Categorized into {len(type_categories)} types and {len(tool_categories)} tools")
print(" └─ ✓ Categorization Complete\n")
return type_categories, tool_categories
# -------------------------
# Analytics Engine
# -------------------------
def analyze_prs_animated(prs, username):
"""Analyze PRs with animated progress"""
print("\n╔═══════════════════════════════════════════════════════════════════════════╗")
print("║ 📊 ANALYZING PR DATA ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝")
merged = pending = closed = draft = stale = 0
repo_counter = {}
yearly = {}
monthly = {}
daily = {}
detailed = []
pr_dates = []
total_prs = len(prs)
print("\n ┌─ ANALYSIS IN PROGRESS")
for i, pr in enumerate(prs):
progress_bar(i + 1, total_prs, "Analyzing", 40)
repo_url = safe_str(pr.get("repository_url"), "")
if repo_url:
parts = repo_url.split("/")
if len(parts) >= 2:
repo = parts[-2] + "/" + parts[-1]
else:
repo = "unknown/unknown"
else:
repo = "unknown/unknown"
repo_counter[repo] = repo_counter.get(repo, 0) + 1
created_at = safe_str(pr.get("created_at"), "1970-01-01T00:00:00Z")
created_year = created_at[:4]
created_month = created_at[:7]
created_day = created_at[:10]
yearly[created_year] = yearly.get(created_year, 0) + 1
monthly[created_month] = monthly.get(created_month, 0) + 1
daily[created_day] = daily.get(created_day, 0) + 1
state = safe_str(pr.get("state"), "unknown")
if pr.get("draft"):
draft += 1
# Track PR dates and states for productivity graph
try:
pr_date = datetime.strptime(created_at[:19], "%Y-%m-%dT%H:%M:%S")
pr_data = pr.get("pull_request") or {}
is_merged = pr_data.get("merged_at") is not None
pr_dates.append({
"date": pr_date,
"state": state,
"merged": is_merged
})
except:
pass
if state == "open":
pending += 1
try:
created_date = datetime.strptime(created_at[:10], "%Y-%m-%d")
if (datetime.now() - created_date).days > 180:
stale += 1
except ValueError:
pass
elif state == "closed":
pr_data = pr.get("pull_request") or {}
if pr_data.get("merged_at"):
merged += 1
else:
closed += 1
detailed.append({
"repo": repo,
"number": safe_int(pr.get("number"), 0),
"title": safe_str(pr.get("title"), "No title"),
"status": state,
"url": safe_str(pr.get("html_url"), ""),
"created_at": created_at[:10]
})
time.sleep(0.008)
print(f"\n │ ✅ Analysis complete")
print(" └─ ✓ Done\n")
total = merged + pending + closed
acceptance = round((merged / total) * 100, 2) if total > 0 else 0
if repo_counter:
top_repo = max(repo_counter, key=repo_counter.get)
else:
top_repo = "No repositories"
# Sort PR dates
pr_dates.sort(key=lambda x: x["date"])
return {
"merged": merged,
"pending": pending,
"closed": closed,
"draft": draft,
"stale": stale,
"acceptance": acceptance,
"top_repo": top_repo,
"yearly": yearly,
"monthly": monthly,
"daily": daily,
"repo_counter": repo_counter,
"total": total,
"details": detailed,
"pr_dates": pr_dates
}
# -------------------------
# Productivity Score Calculator
# -------------------------
def calculate_productivity_scores(pr_dates, acceptance_rate):
"""Calculate productivity scores over time for the profit/loss chart"""
if not pr_dates or len(pr_dates) < 2:
return [], []
scores = []
dates = []
base_score = 50 # Start at 50%
current_score = base_score
# Calculate average time between PRs
time_diffs = []
for i in range(1, len(pr_dates)):
diff = (pr_dates[i]["date"] - pr_dates[i-1]["date"]).total_seconds() / 3600 # Hours
time_diffs.append(diff)
if not time_diffs:
return [], []
avg_time_diff = sum(time_diffs) / len(time_diffs)
# First PR
dates.append(pr_dates[0]["date"])
scores.append(current_score)
for i in range(1, len(pr_dates)):
pr = pr_dates[i]
prev_pr = pr_dates[i-1]
# Time between PRs in hours
time_diff = (pr["date"] - prev_pr["date"]).total_seconds() / 3600
# Calculate score change based on multiple factors
score_change = 0
# Factor 1: Time between PRs
# If faster than average, score goes up; if slower, score goes down
if time_diff < avg_time_diff:
# Faster than average - productivity increase
speed_factor = (avg_time_diff - time_diff) / max(avg_time_diff, 1)
score_change += min(speed_factor * 15, 10)
else:
# Slower than average - productivity decrease
speed_factor = (time_diff - avg_time_diff) / max(avg_time_diff, 1)
score_change -= min(speed_factor * 10, 15)
# Factor 2: PR was merged (positive) or just closed (negative)
if pr["merged"]:
score_change += 5
elif pr["state"] == "closed":
score_change -= 3
# Factor 3: Consistency bonus (if maintaining pace)
if i >= 2:
prev_diff = (pr_dates[i-1]["date"] - pr_dates[i-2]["date"]).total_seconds() / 3600
if abs(time_diff - prev_diff) < avg_time_diff * 0.3: # Within 30% of previous pace
score_change += 2
# Apply score change with smoothing
current_score = current_score + score_change
# Keep score bounded between 0 and 100
current_score = max(5, min(95, current_score))
dates.append(pr["date"])
scores.append(current_score)
# Apply acceptance rate influence to all scores
acceptance_multiplier = acceptance_rate / 100 if acceptance_rate > 0 else 0.5
scores = [s * (0.5 + 0.5 * acceptance_multiplier) for s in scores]
return dates, scores
# -------------------------
# Matplotlib Graph Engine
# -------------------------
def generate_graphs(username, stats, type_counts, tool_counts, save_path):
"""Generate matplotlib graphs and save them"""
if not MATPLOTLIB_AVAILABLE:
print(" ⚠️ Cannot generate graphs - matplotlib not installed")
return None
print("\n╔═══════════════════════════════════════════════════════════════════════════╗")
print("║ 📈 GENERATING GRAPHS ║")
print("╚═════════════════════════════════════════════════════════════════════════════╝\n")
try:
plt.style.use('dark_background')
except:
pass
fig = plt.figure(figsize=(24, 18), facecolor='#1a1a2e')
fig.suptitle(f"GitHub PR Analysis Report for @{username}", fontsize=22, fontweight='bold',
y=0.98, color='white')
# Graph 1: Productivity/Brain Power Chart (Profit-Loss Style)
print(" ┌─ Creating Graph 1/6: Productivity Chart (Profit-Loss Style)...")
ax1 = fig.add_subplot(2, 3, 1, facecolor='#16213e')
pr_dates = stats.get("pr_dates", [])
dates, scores = calculate_productivity_scores(pr_dates, stats["acceptance"])
if dates and scores:
# Create gradient fill effect
for i in range(len(dates) - 1):
color = '#00ff88' if scores[i+1] >= scores[i] else '#ff4444'
ax1.fill_between([dates[i], dates[i+1]], [50, 50], [scores[i], scores[i+1]],
alpha=0.3, color=color)
ax1.plot([dates[i], dates[i+1]], [scores[i], scores[i+1]],
color=color, linewidth=2)
# Add markers at each point
for i, (d, s) in enumerate(zip(dates, scores)):
color = '#00ff88' if s >= 50 else '#ff4444'
ax1.scatter([d], [s], color=color, s=30, zorder=5)
# Add baseline
ax1.axhline(y=50, color='white', linestyle='--', alpha=0.5, linewidth=1)
ax1.fill_between(dates, 0, 50, alpha=0.1, color='#ff4444')
ax1.fill_between(dates, 50, 100, alpha=0.1, color='#00ff88')
ax1.set_ylim(0, 100)
ax1.set_ylabel('Productivity Score', fontsize=10, color='white')
ax1.set_xlabel('Time', fontsize=10, color='white')
ax1.tick_params(colors='white')
# Add annotations
ax1.text(0.02, 0.95, '📈 HIGH PRODUCTIVITY', transform=ax1.transAxes,
fontsize=8, color='#00ff88', verticalalignment='top')
ax1.text(0.02, 0.05, '📉 LOW PRODUCTIVITY', transform=ax1.transAxes,
fontsize=8, color='#ff4444', verticalalignment='bottom')
else:
ax1.text(0.5, 0.5, 'Insufficient Data', ha='center', va='center',
fontsize=14, color='white')
ax1.set_title('🧠 Brain Power / Productivity Index', fontweight='bold', fontsize=12, color='white')
ax1.grid(True, alpha=0.2)
print(" │ ✅ Graph 1 created")
# Graph 2: PR Types Distribution (Horizontal Bar)
print(" ├─ Creating Graph 2/6: PR Types Distribution...")
ax2 = fig.add_subplot(2, 3, 2, facecolor='#16213e')
if type_counts:
types = list(type_counts.keys())
counts = list(type_counts.values())
colors = plt.cm.Set3([i/max(len(types), 1) for i in range(len(types))])
bars = ax2.barh(types, counts, color=colors, edgecolor='white', linewidth=0.5)
ax2.set_xlabel('Number of PRs', fontsize=10, color='white')
ax2.tick_params(colors='white')
for bar, count in zip(bars, counts):
width = bar.get_width()
ax2.annotate(f'{count}', xy=(width, bar.get_y() + bar.get_height()/2),
xytext=(3, 0), textcoords="offset points", ha='left', va='center',
fontsize=9, color='white')
ax2.set_title('📋 PR Types Distribution', fontweight='bold', fontsize=12, color='white')
print(" │ ✅ Graph 2 created")
# Graph 3: Tools Used (Pie Chart)
print(" ├─ Creating Graph 3/6: Tools Used...")
ax3 = fig.add_subplot(2, 3, 3, facecolor='#16213e')
if tool_counts:
tools = list(tool_counts.keys())
counts = list(tool_counts.values())
colors = plt.cm.Pastel1([i/max(len(tools), 1) for i in range(len(tools))])
wedges, texts, autotexts = ax3.pie(counts, labels=tools, colors=colors,
autopct='%1.1f%%', startangle=90,
textprops={'fontsize': 8, 'color': 'white'})
for autotext in autotexts:
autotext.set_color('black')
autotext.set_fontsize(8)
ax3.set_title('🛠️ Tools Used to Create PRs', fontweight='bold', fontsize=12, color='white')
print(" │ ✅ Graph 3 created")
# Graph 4: Monthly Trend with Area Fill
print(" ├─ Creating Graph 4/6: Monthly Trend Analysis...")
ax4 = fig.add_subplot(2, 3, 4, facecolor='#16213e')
if stats['monthly']:
months = sorted(stats['monthly'].keys())[-24:]
counts = [stats['monthly'][m] for m in months]
ax4.fill_between(range(len(months)), counts, alpha=0.4, color='#00d4ff')
ax4.plot(range(len(months)), counts, color='#00d4ff', linewidth=2, marker='o', markersize=4)
ax4.set_xlabel('Month', fontsize=10, color='white')
ax4.set_ylabel('PRs', fontsize=10, color='white')
ax4.tick_params(colors='white')
ax4.set_xticks(range(0, len(months), 4))
ax4.set_xticklabels([months[i][2:] for i in range(0, len(months), 4)], rotation=45)
ax4.grid(True, alpha=0.2)
ax4.set_title('📅 Monthly PR Trend', fontweight='bold', fontsize=12, color='white')
print(" │ ✅ Graph 4 created")