-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_tracker.py
More file actions
641 lines (577 loc) · 27 KB
/
Copy pathgithub_tracker.py
File metadata and controls
641 lines (577 loc) · 27 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
import os
import sys
import json
import csv
import argparse
import datetime
import concurrent.futures
import requests
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeRemainingColumn
from rich.panel import Panel
from rich.columns import Columns
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
console = Console()
DEFAULT_CACHE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".github_tracker_cache.json")
DEFAULT_REPOS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "repos.txt")
class GitHubClient:
"""Client for GitHub REST API with rate limit tracking and token authentication."""
BASE_URL = "https://api.github.com"
def __init__(self, token=None):
self.session = requests.Session()
self.token = token or os.environ.get("GITHUB_TOKEN")
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Antigravity-GitHub-Tracker/1.0"
}
if self.token:
headers["Authorization"] = f"token {self.token}"
self.session.headers.update(headers)
self.rate_limit_remaining = None
self.rate_limit_reset = None
def _update_rate_limit(self, response):
remaining = response.headers.get("X-RateLimit-Remaining")
reset_time = response.headers.get("X-RateLimit-Reset")
if remaining is not None:
self.rate_limit_remaining = int(remaining)
if reset_time is not None:
self.rate_limit_reset = datetime.datetime.fromtimestamp(int(reset_time))
def get(self, endpoint, params=None):
url = f"{self.BASE_URL}{endpoint}" if not endpoint.startswith("http") else endpoint
try:
res = self.session.get(url, params=params, timeout=10)
self._update_rate_limit(res)
if res.status_code == 200:
return res.json(), res.headers
elif res.status_code == 404:
return None, res.headers
elif res.status_code in [401, 403]:
msg = res.json().get("message", "Forbidden or Rate limit exceeded")
return {"_error": f"HTTP {res.status_code}: {msg}"}, res.headers
else:
return None, res.headers
except Exception as e:
return {"_error": str(e)}, {}
def load_repos_from_file(filepath):
"""Loads a list of repositories from a file (one owner/repo per line)."""
repos = []
if not os.path.exists(filepath):
return repos
try:
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
# Support github.com/owner/repo or owner/repo format
if "github.com/" in line:
line = line.split("github.com/")[-1].strip("/")
if "/" in line:
repos.append(line)
except Exception as e:
console.print(f"[dim yellow]Warning: Could not read repos file {filepath}: {e}[/dim yellow]")
return repos
def get_repo_metrics(client, repo_full_name):
"""Gathers comprehensive development metrics for a single GitHub repository."""
data, _ = client.get(f"/repos/{repo_full_name}")
if not data or "_error" in data:
err = data.get("_error", "Repository not found (404)") if data else "Repository not found"
return {
"name": repo_full_name,
"error": err,
"success": False
}
# 1. Basic Stats
stars = data.get("stargazers_count", 0)
forks = data.get("forks_count", 0)
watchers = data.get("subscribers_count", data.get("watchers_count", 0))
total_issues_and_prs = data.get("open_issues_count", 0)
language = data.get("language") or "N/A"
license_name = data.get("license", {}).get("spdx_id") if data.get("license") else "None"
description = data.get("description") or "No description"
default_branch = data.get("default_branch", "main")
updated_at = data.get("pushed_at") or data.get("updated_at")
# 2. Open PRs Count (GitHub includes PRs in open_issues_count)
open_prs_count = 0
prs_data, prs_headers = client.get(f"/repos/{repo_full_name}/pulls", params={"state": "open", "per_page": 1})
if prs_data and not isinstance(prs_data, dict):
link_header = prs_headers.get("Link", "")
if 'rel="last"' in link_header:
try:
# Link header contains page numbers: <...page=12>; rel="last"
last_url = [part for part in link_header.split(",") if 'rel="last"' in part][0]
page_num = last_url.split("page=")[1].split("&")[0].split(">")[0]
open_prs_count = int(page_num)
except Exception:
open_prs_count = len(prs_data)
else:
open_prs_count = len(prs_data)
open_issues_only = max(0, total_issues_and_prs - open_prs_count)
# 3. Latest Commit info
latest_commit_msg = "N/A"
latest_commit_author = "N/A"
latest_commit_date = "N/A"
recent_commits_count = 0
commits_data, _ = client.get(f"/repos/{repo_full_name}/commits", params={"per_page": 10})
if commits_data and isinstance(commits_data, list) and len(commits_data) > 0:
c = commits_data[0].get("commit", {})
latest_commit_msg = c.get("message", "").split("\n")[0][:60]
latest_commit_author = c.get("author", {}).get("name", "Unknown")
raw_date = c.get("author", {}).get("date")
if raw_date:
try:
dt = datetime.datetime.fromisoformat(raw_date.replace("Z", "+00:00"))
latest_commit_date = dt.strftime("%Y-%m-%d")
except Exception:
latest_commit_date = raw_date[:10]
recent_commits_count = len(commits_data)
# 4. Latest Release Info
latest_release_tag = "None"
latest_release_date = "N/A"
release_data, _ = client.get(f"/repos/{repo_full_name}/releases/latest")
if release_data and isinstance(release_data, dict) and "_error" not in release_data:
latest_release_tag = release_data.get("tag_name", "None")
rel_date = release_data.get("published_at")
if rel_date:
latest_release_date = rel_date[:10]
return {
"name": repo_full_name,
"description": description,
"stars": stars,
"forks": forks,
"watchers": watchers,
"language": language,
"license": license_name,
"open_prs": open_prs_count,
"open_issues": open_issues_only,
"total_issues_and_prs": total_issues_and_prs,
"latest_commit_msg": latest_commit_msg,
"latest_commit_author": latest_commit_author,
"latest_commit_date": latest_commit_date,
"recent_commits": recent_commits_count,
"latest_release": latest_release_tag,
"latest_release_date": latest_release_date,
"default_branch": default_branch,
"updated_at": updated_at[:10] if updated_at else "N/A",
"success": True
}
def get_repo_details(client, repo_full_name):
"""Fetches in-depth development activity (commits, PRs, issues, releases) for detail mode."""
base_metrics = get_repo_metrics(client, repo_full_name)
if not base_metrics.get("success"):
return base_metrics
# 1. Fetch top 5 commits
commits, _ = client.get(f"/repos/{repo_full_name}/commits", params={"per_page": 5})
commit_list = []
if isinstance(commits, list):
for item in commits:
c = item.get("commit", {})
sha = item.get("sha", "")[:7]
author = c.get("author", {}).get("name", "Unknown")
msg = c.get("message", "").split("\n")[0]
date = (c.get("author", {}).get("date") or "")[:10]
commit_list.append({"sha": sha, "author": author, "message": msg, "date": date})
# 2. Fetch top 5 recent Pull Requests
prs, _ = client.get(f"/repos/{repo_full_name}/pulls", params={"state": "all", "per_page": 5})
pr_list = []
if isinstance(prs, list):
for item in prs:
pr_num = item.get("number")
title = item.get("title", "")
state = item.get("state", "open")
if item.get("draft"):
state = "draft"
if item.get("merged_at"):
state = "merged"
author = item.get("user", {}).get("login", "Unknown")
created_at = (item.get("created_at") or "")[:10]
pr_list.append({"number": pr_num, "title": title, "state": state, "author": author, "date": created_at})
# 3. Fetch top 5 recent Issues
issues, _ = client.get(f"/repos/{repo_full_name}/issues", params={"state": "open", "per_page": 5})
issue_list = []
if isinstance(issues, list):
for item in issues:
if "pull_request" in item:
continue # Skip PRs returned in issues endpoint
num = item.get("number")
title = item.get("title", "")
state = item.get("state", "open")
author = item.get("user", {}).get("login", "Unknown")
date = (item.get("created_at") or "")[:10]
issue_list.append({"number": num, "title": title, "state": state, "author": author, "date": date})
# 4. Fetch releases
releases, _ = client.get(f"/repos/{repo_full_name}/releases", params={"per_page": 5})
release_list = []
if isinstance(releases, list):
for item in releases:
tag = item.get("tag_name", "")
name = item.get("name") or tag
date = (item.get("published_at") or "")[:10]
author = item.get("author", {}).get("login", "Unknown")
body = (item.get("body") or "").split("\n")[0][:100]
release_list.append({"tag": tag, "name": name, "date": date, "author": author, "body": body})
# 5. Language Breakdown
languages, _ = client.get(f"/repos/{repo_full_name}/languages")
lang_dist = {}
if isinstance(languages, dict):
total_b = sum(languages.values())
if total_b > 0:
lang_dist = {k: f"{(v / total_b * 100):.1f}%" for k, v in sorted(languages.items(), key=lambda x: -x[1])[:5]}
base_metrics["detail_commits"] = commit_list
base_metrics["detail_prs"] = pr_list
base_metrics["detail_issues"] = issue_list
base_metrics["detail_releases"] = release_list
base_metrics["languages"] = lang_dist
return base_metrics
def fetch_all_repos_data(client, repos_list):
"""Concurrently fetches development metrics for all specified repositories."""
results = []
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TimeRemainingColumn(),
console=console
) as progress:
task = progress.add_task("[cyan]Fetching GitHub project metrics...", total=len(repos_list))
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future_to_repo = {executor.submit(get_repo_metrics, client, repo): repo for repo in repos_list}
for future in concurrent.futures.as_completed(future_to_repo):
data = future.result()
results.append(data)
progress.update(task, advance=1)
return results
def load_cache(cache_file):
if not os.path.exists(cache_file):
return None
try:
with open(cache_file, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def save_cache(cache_file, repos_data):
try:
cache_payload = {
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"total": len(repos_data),
"repos": repos_data
}
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(cache_payload, f, indent=2)
except Exception as e:
console.print(f"[dim yellow]Warning: Could not save cache ({e})[/dim yellow]")
def render_overview_table(data_list, sort_by="stars"):
"""Renders high-level KPI cards and multi-project analytics table."""
valid_data = [d for d in data_list if d.get("success", False)]
errors = [d for d in data_list if not d.get("success", False)]
# 1. Summary KPI Cards
total_repos = len(valid_data)
total_stars = sum(d.get("stars", 0) for d in valid_data)
total_prs = sum(d.get("open_prs", 0) for d in valid_data)
total_issues = sum(d.get("open_issues", 0) for d in valid_data)
active_releases = sum(1 for d in valid_data if d.get("latest_release") != "None")
kpi_cards = [
Panel(f"[bold cyan]{total_repos}[/bold cyan]\n[dim]Projects[/dim]", border_style="cyan", title="Monitored"),
Panel(f"[bold yellow]{total_stars:,}[/bold yellow]\n[dim]Total Stars[/dim]", border_style="yellow", title="Popularity"),
Panel(f"[bold green]{total_prs:,}[/bold green]\n[dim]Open PRs[/dim]", border_style="green", title="Active PRs"),
Panel(f"[bold magenta]{total_issues:,}[/bold magenta]\n[dim]Open Issues[/dim]", border_style="magenta", title="Issues"),
Panel(f"[bold blue]{active_releases}[/bold blue]\n[dim]Tagged Releases[/dim]", border_style="blue", title="Releases")
]
console.print(Columns(kpi_cards, equal=True))
console.print()
# 2. Main Analytics Table
table = Table(
title=f"GitHub Repository Analytics Dashboard (Sorted by {sort_by.title()})",
header_style="bold cyan",
border_style="dim",
expand=True
)
table.add_column("Repository", style="bold white", no_wrap=True)
table.add_column("Language", style="dim cyan")
table.add_column("Stars", justify="right", style="yellow")
table.add_column("Forks", justify="right", style="dim")
table.add_column("Open PRs", justify="right", style="green")
table.add_column("Open Issues", justify="right", style="magenta")
table.add_column("Latest Commit", style="white")
table.add_column("Latest Release", style="bold blue")
# Sort
def get_sort_key(item):
if sort_by == "stars":
return item.get("stars", 0)
elif sort_by == "forks":
return item.get("forks", 0)
elif sort_by == "prs":
return item.get("open_prs", 0)
elif sort_by == "issues":
return item.get("open_issues", 0)
elif sort_by == "name":
return item.get("name", "").lower()
return item.get("stars", 0)
reverse_order = sort_by != "name"
sorted_items = sorted(valid_data, key=get_sort_key, reverse=reverse_order)
for item in sorted_items:
commit_info = f"{item['latest_commit_date']} ([dim]{item['latest_commit_author']}[/dim])" if item['latest_commit_date'] != "N/A" else "No commits"
rel_info = item['latest_release'] if item['latest_release'] != "None" else "[dim]None[/dim]"
if item['latest_release_date'] != "N/A":
rel_info += f" [dim]({item['latest_release_date']})[/dim]"
table.add_row(
item["name"],
item["language"],
f"{item['stars']:,}",
f"{item['forks']:,}",
f"{item['open_prs']:,}",
f"{item['open_issues']:,}",
commit_info,
rel_info
)
console.print(table)
if errors:
console.print("\n[bold red]Failed to fetch some repositories:[/bold red]")
for err in errors:
console.print(f" [red]*[/red] {err['name']}: [dim red]{err.get('error', 'Error')}[/dim red]")
def render_project_detail(detail_data):
"""Renders comprehensive activity breakdown for a single project."""
if not detail_data.get("success"):
console.print(f"[bold red]Error loading {detail_data.get('name')}:[/bold red] {detail_data.get('error')}")
return
name = detail_data["name"]
desc = detail_data.get("description", "No description")
lang = detail_data.get("language", "N/A")
license_id = detail_data.get("license", "None")
header = (
f"[bold white]{name}[/bold white] - [dim]{desc}[/dim]\n"
f"[yellow]Stars: {detail_data['stars']:,}[/yellow] | "
f"[dim]Forks: {detail_data['forks']:,}[/dim] | "
f"[cyan]Language:[/cyan] {lang} | "
f"[dim]License:[/dim] {license_id} | "
f"[green]Open PRs:[/green] {detail_data['open_prs']} | "
f"[magenta]Open Issues:[/magenta] {detail_data['open_issues']}"
)
console.print(Panel(header, border_style="cyan", title="Project Command Center"))
console.print()
# Language breakdown
if detail_data.get("languages"):
lang_str = " ".join([f"[bold cyan]{k}:[/bold cyan] {v}" for k, v in detail_data["languages"].items()])
console.print(Panel(lang_str, border_style="dim", title="Language Breakdown"))
console.print()
# Latest Commits Table
commits = detail_data.get("detail_commits", [])
if commits:
c_table = Table(title="Recent Commits", border_style="dim", expand=True)
c_table.add_column("SHA", style="bold yellow", width=10)
c_table.add_column("Message", style="white")
c_table.add_column("Author", style="dim", width=20)
c_table.add_column("Date", style="dim cyan", width=12)
for c in commits:
c_table.add_row(c["sha"], c["message"], c["author"], c["date"])
console.print(c_table)
console.print()
# Recent Pull Requests Table
prs = detail_data.get("detail_prs", [])
if prs:
pr_table = Table(title="Recent Pull Requests", border_style="dim", expand=True)
pr_table.add_column("#", style="bold green", width=8)
pr_table.add_column("Title", style="white")
pr_table.add_column("State", width=10)
pr_table.add_column("Author", style="dim", width=18)
pr_table.add_column("Date", style="dim cyan", width=12)
for pr in prs:
state_color = "green" if pr["state"] == "open" else ("magenta" if pr["state"] == "merged" else "dim")
pr_table.add_row(
f"#{pr['number']}",
pr["title"],
f"[{state_color}]{pr['state'].upper()}[/{state_color}]",
pr["author"],
pr["date"]
)
console.print(pr_table)
console.print()
# Recent Issues Table
issues = detail_data.get("detail_issues", [])
if issues:
issue_table = Table(title="Recent Open Issues", border_style="dim", expand=True)
issue_table.add_column("#", style="bold magenta", width=8)
issue_table.add_column("Title", style="white")
issue_table.add_column("Author", style="dim", width=18)
issue_table.add_column("Date", style="dim cyan", width=12)
for iss in issues:
issue_table.add_row(f"#{iss['number']}", iss["title"], iss["author"], iss["date"])
console.print(issue_table)
console.print()
# Releases
releases = detail_data.get("detail_releases", [])
if releases:
rel_table = Table(title="Recent Releases", border_style="dim", expand=True)
rel_table.add_column("Tag", style="bold blue", width=15)
rel_table.add_column("Name", style="white")
rel_table.add_column("Published Date", style="dim cyan", width=15)
rel_table.add_column("Author", style="dim", width=18)
for rel in releases:
rel_table.add_row(rel["tag"], rel["name"], rel["date"], rel["author"])
console.print(rel_table)
def export_metrics(data_list, filepath):
"""Exports metrics to JSON, CSV, or Markdown file."""
valid_data = [d for d in data_list if d.get("success", False)]
ext = os.path.splitext(filepath)[1].lower()
if ext == ".json":
with open(filepath, "w", encoding="utf-8") as f:
json.dump(valid_data, f, indent=2)
elif ext == ".csv":
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Repository", "Language", "Stars", "Forks", "Open PRs", "Open Issues", "Latest Commit Date", "Latest Commit Author", "Latest Release", "Release Date"])
for d in valid_data:
writer.writerow([
d["name"], d["language"], d["stars"], d["forks"],
d["open_prs"], d["open_issues"], d["latest_commit_date"],
d["latest_commit_author"], d["latest_release"], d["latest_release_date"]
])
elif ext in [".md", ".txt"]:
with open(filepath, "w", encoding="utf-8") as f:
f.write("# GitHub Multi-Repository Analytics Report\n\n")
f.write(f"Generated at: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("| Repository | Language | Stars | Forks | Open PRs | Open Issues | Latest Commit | Latest Release |\n")
f.write("|---|---|---|---|---|---|---|---|\n")
for d in valid_data:
commit_str = f"{d['latest_commit_date']} ({d['latest_commit_author']})"
release_str = f"{d['latest_release']} ({d['latest_release_date']})" if d['latest_release'] != "None" else "None"
f.write(f"| {d['name']} | {d['language']} | {d['stars']:,} | {d['forks']:,} | {d['open_prs']:,} | {d['open_issues']:,} | {commit_str} | {release_str} |\n")
else:
console.print(f"[bold red]Unsupported export format: {ext}. Supported: .json, .csv, .md, .txt[/bold red]")
return False
console.print(f"[bold green]Successfully exported {len(valid_data)} repository metrics to:[/bold green] {filepath}")
return True
def main():
parser = argparse.ArgumentParser(
description="GitHub Multi-Repository Analytics Command Center (Commits, Issues, PRs, Releases, and Velocity)"
)
parser.add_argument(
"-r", "--repos",
nargs="*",
default=[],
help="One or more GitHub repositories in 'owner/repo' format (e.g. -r pallets/flask tiangolo/fastapi)"
)
parser.add_argument(
"-f", "--file",
default=DEFAULT_REPOS_FILE,
help=f"File containing repository list, one per line (default: {DEFAULT_REPOS_FILE})"
)
parser.add_argument(
"-s", "--sort",
choices=["stars", "forks", "prs", "issues", "name"],
default="stars",
help="Sort repositories by metric (default: stars)"
)
parser.add_argument(
"-d", "--detail",
metavar="OWNER/REPO",
help="Display deep-dive analytics (recent commits, PRs, issues, releases, languages) for a single project"
)
parser.add_argument(
"--token",
help="GitHub Personal Access Token (defaults to GITHUB_TOKEN environment variable)"
)
parser.add_argument(
"--refresh",
action="store_true",
help="Bypass cache and force fresh fetch from GitHub API"
)
parser.add_argument(
"--no-cache",
action="store_true",
help="Run live without reading or writing local cache"
)
parser.add_argument(
"--clear-cache",
action="store_true",
help="Delete local cache file and exit"
)
parser.add_argument(
"-e", "--export",
metavar="FILEPATH",
help="Export summary report to file (.csv, .json, .md, .txt)"
)
parser.add_argument(
"--cache-file",
default=DEFAULT_CACHE_FILE,
help=f"Custom cache file path (default: {DEFAULT_CACHE_FILE})"
)
args = parser.parse_args()
# Clear cache action
if args.clear_cache:
if os.path.exists(args.cache_file):
try:
os.remove(args.cache_file)
console.print(f"[bold green]Successfully removed cache file:[/bold green] {args.cache_file}")
except Exception as e:
console.print(f"[bold red]Failed to delete cache file:[/bold red] {e}")
else:
console.print(f"[dim yellow]No cache file found at:[/dim yellow] {args.cache_file}")
return
client = GitHubClient(token=args.token)
# 1. Detail Mode for a specific repository
if args.detail:
repo_target = args.detail.strip()
if "github.com/" in repo_target:
repo_target = repo_target.split("github.com/")[-1].strip("/")
console.print(f"[bold blue]Gathering detailed activity for:[/bold blue] {repo_target} ...\n")
detail_data = get_repo_details(client, repo_target)
render_project_detail(detail_data)
if client.rate_limit_remaining is not None:
console.print(f"\n[dim]GitHub API Rate Limit Remaining: {client.rate_limit_remaining} requests[/dim]")
return
# 2. Multi-Repository Overview Mode
repos_to_scan = []
if args.repos:
for r in args.repos:
r_clean = r.strip()
if "github.com/" in r_clean:
r_clean = r_clean.split("github.com/")[-1].strip("/")
if "/" in r_clean:
repos_to_scan.append(r_clean)
else:
repos_to_scan = load_repos_from_file(args.file)
if not repos_to_scan:
console.print(f"[bold red]No repositories found to monitor![/bold red]")
console.print(f"Specify repositories via [cyan]--repos owner/repo[/cyan] or add them to [cyan]{args.file}[/cyan].")
return
console.print(f"[bold blue]Monitoring {len(repos_to_scan)} GitHub Projects[/bold blue] (Source: {'CLI args' if args.repos else args.file})\n")
repos_data = None
# Check cache
if not args.refresh and not args.no_cache:
cache = load_cache(args.cache_file)
if cache:
cached_repos = {r["name"].lower(): r for r in cache.get("repos", []) if r.get("success")}
# Check if all requested repos exist in cache
if all(r.lower() in cached_repos for r in repos_to_scan):
repos_data = [cached_repos[r.lower()] for r in repos_to_scan]
timestamp = cache.get("timestamp", "Unknown time")
console.print(
f"[bold green][CACHE] Loaded {len(repos_data)} project(s) from cache[/bold green] "
f"[dim](fetched: {timestamp})[/dim]\n"
f"[dim italic]Tip: Run with --refresh to query live GitHub data.[/dim italic]\n"
)
if repos_data is None:
repos_data = fetch_all_repos_data(client, repos_to_scan)
if not args.no_cache and repos_data:
save_cache(args.cache_file, repos_data)
console.print(f"[dim green]Saved metrics to cache: {args.cache_file}[/dim green]\n")
# Render Table & Dashboard
render_overview_table(repos_data, sort_by=args.sort)
# Export if requested
if args.export:
export_metrics(repos_data, args.export)
# Print Rate Limit status
if client.rate_limit_remaining is not None:
style = "dim" if client.rate_limit_remaining > 20 else "bold yellow"
console.print(f"\n[{style}]GitHub API Quota: {client.rate_limit_remaining} requests remaining[/{style}]")
if client.rate_limit_remaining < 10 and client.rate_limit_reset:
console.print(f"[bold red]Warning: Rate limit nearly exhausted! Resets at {client.rate_limit_reset}[/bold red]")
if __name__ == "__main__":
main()