-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitpulse.py
More file actions
759 lines (647 loc) · 26.1 KB
/
Copy pathgitpulse.py
File metadata and controls
759 lines (647 loc) · 26.1 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
#!/usr/bin/env python3
"""
GitPulse — Repository Activity Dashboard
Generates a beautiful HTML dashboard showing repository activity metrics:
commit frequency, contributor stats, file hotspots, time-of-day patterns,
and more. Perfect for team standups, sprint reviews, and project health checks.
Zero dependencies — pure Python 3.8+ stdlib.
Usage:
python3 gitpulse.py # current repo, HTML dashboard
python3 gitpulse.py /path/to/repo # specific repo
python3 gitpulse.py --days 30 # last 30 days only
python3 gitpulse.py --json # JSON output instead
python3 gitpulse.py --author "Alice" # filter by author
python3 gitpulse.py -o dashboard.html # custom output file
"""
import argparse
import json
import math
import os
import re
import subprocess
import sys
from collections import Counter, defaultdict
from datetime import datetime, timedelta
from pathlib import Path
__version__ = "1.0.0"
# ---------------------------------------------------------------------------
# Git Operations
# ---------------------------------------------------------------------------
def run_git(args, repo_path="."):
"""Run a git command and return stdout."""
cmd = ["git", "-C", str(repo_path)] + args
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return None
return result.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
def is_git_repo(path):
return run_git(["rev-parse", "--git-dir"], path) is not None
def get_repo_name(repo_path):
url = run_git(["remote", "get-url", "origin"], repo_path)
if url:
name = url.rstrip('/').split('/')[-1]
if name.endswith('.git'):
name = name[:-4]
return name
return Path(repo_path).resolve().name
def get_remote_url(repo_path):
url = run_git(["remote", "get-url", "origin"], repo_path)
if not url:
return None
if url.startswith("git@"):
url = url.replace(":", "/").replace("git@", "https://")
if url.endswith(".git"):
url = url[:-4]
return url
def get_default_branch(repo_path):
branch = run_git(["symbolic-ref", "--short", "HEAD"], repo_path)
return branch or "main"
def get_commit_log(repo_path, days=None, author=None, max_commits=2000):
"""Get detailed commit log."""
sep = "---GPLS---"
fmt = f"%H{sep}%an{sep}%ae{sep}%aI{sep}%s"
args = ["log", f"--format={fmt}", f"--max-count={max_commits}"]
if days:
since = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
args.append(f"--since={since}")
if author:
args.append(f"--author={author}")
output = run_git(args, repo_path)
if not output:
return []
commits = []
for line in output.split('\n'):
if sep not in line:
continue
parts = line.split(sep)
if len(parts) < 5:
continue
dt_str = parts[3]
try:
dt = datetime.fromisoformat(dt_str)
except ValueError:
dt = datetime.now()
commits.append({
"hash": parts[0][:8],
"full_hash": parts[0],
"author": parts[1],
"email": parts[2],
"datetime": dt,
"date": dt.strftime("%Y-%m-%d"),
"hour": dt.hour,
"weekday": dt.weekday(), # 0=Monday
"subject": parts[4],
})
return commits
def get_file_changes(repo_path, days=None, max_commits=2000):
"""Get files changed per commit (for hotspot analysis)."""
args = ["log", "--name-only", "--format=---COMMIT---", f"--max-count={max_commits}"]
if days:
since = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
args.append(f"--since={since}")
output = run_git(args, repo_path)
if not output:
return Counter()
file_counts = Counter()
for line in output.split('\n'):
line = line.strip()
if not line or line == "---COMMIT---":
continue
file_counts[line] += 1
return file_counts
def get_line_stats(repo_path, days=None, max_commits=500):
"""Get insertions/deletions per commit."""
args = ["log", "--shortstat", "--format=---STAT---%an", f"--max-count={max_commits}"]
if days:
since = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
args.append(f"--since={since}")
output = run_git(args, repo_path)
if not output:
return {"total_insertions": 0, "total_deletions": 0, "by_author": {}}
total_ins = 0
total_del = 0
by_author = defaultdict(lambda: {"insertions": 0, "deletions": 0})
current_author = None
for line in output.split('\n'):
if line.startswith("---STAT---"):
current_author = line[10:]
elif "file" in line and ("insertion" in line or "deletion" in line):
ins_match = re.search(r'(\d+) insertion', line)
del_match = re.search(r'(\d+) deletion', line)
ins = int(ins_match.group(1)) if ins_match else 0
dels = int(del_match.group(1)) if del_match else 0
total_ins += ins
total_del += dels
if current_author:
by_author[current_author]["insertions"] += ins
by_author[current_author]["deletions"] += dels
return {
"total_insertions": total_ins,
"total_deletions": total_del,
"by_author": dict(by_author),
}
# ---------------------------------------------------------------------------
# Analytics
# ---------------------------------------------------------------------------
def analyze_commits(commits):
"""Compute all dashboard metrics from commit data."""
if not commits:
return {}
# Basic counts
total = len(commits)
authors = Counter(c["author"] for c in commits)
dates = Counter(c["date"] for c in commits)
# Date range
sorted_dates = sorted(set(c["date"] for c in commits))
first_date = sorted_dates[0]
last_date = sorted_dates[-1]
days_span = max(1, (datetime.strptime(last_date, "%Y-%m-%d") -
datetime.strptime(first_date, "%Y-%m-%d")).days + 1)
# Commits per day (average)
avg_per_day = total / days_span
# Streaks
all_dates_set = set(sorted_dates)
current_streak = 0
max_streak = 0
streak = 0
d = datetime.now()
for i in range(days_span + 1):
check = (d - timedelta(days=i)).strftime("%Y-%m-%d")
if check in all_dates_set:
streak += 1
max_streak = max(max_streak, streak)
if i == 0 or (i == 1 and streak > 0):
current_streak = streak
else:
if i <= 1:
current_streak = streak
streak = 0
# Hour distribution (for heatmap)
hours = Counter(c["hour"] for c in commits)
hour_dist = [hours.get(h, 0) for h in range(24)]
# Weekday distribution
weekdays = Counter(c["weekday"] for c in commits)
weekday_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
weekday_dist = [(weekday_names[d], weekdays.get(d, 0)) for d in range(7)]
# Weekly commit counts (for sparkline/chart)
weekly = defaultdict(int)
for c in commits:
week = c["datetime"].strftime("%Y-W%W")
weekly[week] += 1
weekly_sorted = sorted(weekly.items())
# Daily activity (last 90 days for calendar view)
daily = {}
for d_str, count in dates.items():
daily[d_str] = count
# Most productive day/hour
peak_day = max(weekday_dist, key=lambda x: x[1])
peak_hour = max(range(24), key=lambda h: hour_dist[h])
return {
"total_commits": total,
"total_authors": len(authors),
"authors": authors.most_common(),
"first_date": first_date,
"last_date": last_date,
"days_span": days_span,
"avg_per_day": round(avg_per_day, 2),
"max_streak": max_streak,
"current_streak": current_streak,
"hour_dist": hour_dist,
"weekday_dist": weekday_dist,
"weekly": weekly_sorted,
"daily": daily,
"peak_day": peak_day[0],
"peak_hour": f"{peak_hour:02d}:00",
"busiest_date": max(dates.items(), key=lambda x: x[1]),
}
# ---------------------------------------------------------------------------
# HTML Dashboard
# ---------------------------------------------------------------------------
def generate_html(metrics, line_stats, hotspots, repo_name, remote_url=None):
"""Generate a beautiful HTML dashboard."""
# Prepare chart data
weekly_labels = json.dumps([w[0] for w in metrics["weekly"]][-26:])
weekly_data = json.dumps([w[1] for w in metrics["weekly"]][-26:])
hour_data = json.dumps(metrics["hour_dist"])
weekday_labels = json.dumps([w[0] for w in metrics["weekday_dist"]])
weekday_data = json.dumps([w[1] for w in metrics["weekday_dist"]])
# Top contributors table
contrib_rows = ""
for name, count in metrics["authors"][:10]:
pct = count * 100 / metrics["total_commits"]
lines = line_stats["by_author"].get(name, {})
ins = lines.get("insertions", 0)
dels = lines.get("deletions", 0)
contrib_rows += f"""
<tr>
<td>{_esc(name)}</td>
<td>{count}</td>
<td>{pct:.1f}%</td>
<td class="green">+{ins:,}</td>
<td class="red">-{dels:,}</td>
</tr>"""
# Hotspots
hotspot_rows = ""
for filepath, count in hotspots.most_common(15):
bar_width = min(100, count * 100 / max(1, hotspots.most_common(1)[0][1]))
hotspot_rows += f"""
<tr>
<td class="filepath">{_esc(filepath)}</td>
<td>{count}</td>
<td><div class="bar" style="width:{bar_width}%"></div></td>
</tr>"""
# Activity calendar (contribution grid)
calendar_html = _build_calendar(metrics["daily"])
# Hour heatmap
hour_heatmap = _build_hour_heatmap(metrics["hour_dist"])
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitPulse — {_esc(repo_name)}</title>
<style>
:root {{
--bg: #0d1117; --surface: #161b22; --surface2: #1c2129;
--border: #30363d; --text: #e6edf3; --muted: #8b949e;
--accent: #58a6ff; --green: #3fb950; --red: #f85149;
--orange: #d29922; --purple: #bc8cff; --pink: #f778ba;
}}
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
background: var(--bg); color: var(--text); line-height: 1.5;
}}
.dashboard {{ max-width: 1100px; margin: 0 auto; padding: 24px; }}
header {{
display: flex; align-items: center; justify-content: space-between;
padding: 24px 0; border-bottom: 1px solid var(--border); margin-bottom: 24px;
}}
header h1 {{
font-size: 1.5rem;
background: linear-gradient(135deg, var(--accent), var(--purple));
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text;
}}
header .meta {{ color: var(--muted); font-size: 0.85rem; }}
.stats-grid {{
display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: 16px; margin-bottom: 32px;
}}
.stat-card {{
background: var(--surface); border: 1px solid var(--border);
border-radius: 12px; padding: 20px;
}}
.stat-card .value {{ font-size: 2rem; font-weight: 800; }}
.stat-card .label {{ color: var(--muted); font-size: 0.8rem; margin-top: 4px; }}
.stat-card.accent .value {{ color: var(--accent); }}
.stat-card.green .value {{ color: var(--green); }}
.stat-card.orange .value {{ color: var(--orange); }}
.stat-card.purple .value {{ color: var(--purple); }}
.stat-card.pink .value {{ color: var(--pink); }}
.section {{ margin-bottom: 32px; }}
.section h2 {{
font-size: 1.1rem; font-weight: 600; margin-bottom: 16px;
color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em;
font-size: 0.85rem;
}}
.card {{
background: var(--surface); border: 1px solid var(--border);
border-radius: 12px; padding: 24px; overflow-x: auto;
}}
table {{ width: 100%; border-collapse: collapse; font-size: 0.9rem; }}
th {{ text-align: left; color: var(--muted); font-weight: 500; padding: 8px 12px; border-bottom: 1px solid var(--border); }}
td {{ padding: 8px 12px; border-bottom: 1px solid var(--border); }}
tr:last-child td {{ border-bottom: none; }}
.green {{ color: var(--green); }}
.red {{ color: var(--red); }}
.filepath {{ font-family: monospace; font-size: 0.85rem; color: var(--accent); max-width: 400px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
.bar {{ height: 8px; background: var(--accent); border-radius: 4px; min-width: 4px; }}
.two-col {{ display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }}
@media (max-width: 768px) {{ .two-col {{ grid-template-columns: 1fr; }} }}
/* Activity calendar */
.calendar {{ display: flex; gap: 3px; flex-wrap: wrap; }}
.cal-week {{ display: flex; flex-direction: column; gap: 3px; }}
.cal-day {{
width: 12px; height: 12px; border-radius: 2px;
background: var(--surface2);
}}
.cal-day.l1 {{ background: #0e4429; }}
.cal-day.l2 {{ background: #006d32; }}
.cal-day.l3 {{ background: #26a641; }}
.cal-day.l4 {{ background: #39d353; }}
/* Hour heatmap */
.heatmap {{ display: grid; grid-template-columns: repeat(24, 1fr); gap: 4px; }}
.heat-cell {{
aspect-ratio: 1; border-radius: 4px;
display: flex; align-items: center; justify-content: center;
font-size: 0.65rem; color: var(--muted); position: relative;
}}
.heat-cell.l0 {{ background: var(--surface2); }}
.heat-cell.l1 {{ background: #0e4429; }}
.heat-cell.l2 {{ background: #006d32; color: #fff; }}
.heat-cell.l3 {{ background: #26a641; color: #fff; }}
.heat-cell.l4 {{ background: #39d353; color: #000; }}
.heat-labels {{ display: grid; grid-template-columns: repeat(24, 1fr); gap: 4px; margin-top: 4px; }}
.heat-labels span {{ text-align: center; font-size: 0.65rem; color: var(--muted); }}
/* Sparkline bar chart */
.spark {{ display: flex; align-items: flex-end; gap: 2px; height: 80px; }}
.spark-bar {{
flex: 1; background: var(--accent); border-radius: 2px 2px 0 0;
min-width: 4px; transition: opacity 0.2s; opacity: 0.7;
}}
.spark-bar:hover {{ opacity: 1; }}
.footer {{
color: var(--muted); font-size: 0.8rem; text-align: center;
padding: 24px 0; border-top: 1px solid var(--border); margin-top: 24px;
}}
.footer a {{ color: var(--accent); text-decoration: none; }}
</style>
</head>
<body>
<div class="dashboard">
<header>
<div>
<h1>GitPulse — {_esc(repo_name)}</h1>
<div class="meta">{metrics['first_date']} to {metrics['last_date']} · {metrics['days_span']} days</div>
</div>
<div class="meta">Generated {datetime.now().strftime('%Y-%m-%d %H:%M')}</div>
</header>
<!-- Key Metrics -->
<div class="stats-grid">
<div class="stat-card accent">
<div class="value">{metrics['total_commits']}</div>
<div class="label">Total Commits</div>
</div>
<div class="stat-card purple">
<div class="value">{metrics['total_authors']}</div>
<div class="label">Contributors</div>
</div>
<div class="stat-card green">
<div class="value">{metrics['avg_per_day']}</div>
<div class="label">Commits / Day</div>
</div>
<div class="stat-card orange">
<div class="value">{metrics['max_streak']}</div>
<div class="label">Max Streak (days)</div>
</div>
<div class="stat-card pink">
<div class="value">{metrics['peak_hour']}</div>
<div class="label">Peak Hour</div>
</div>
<div class="stat-card">
<div class="value">{metrics['peak_day']}</div>
<div class="label">Peak Day</div>
</div>
<div class="stat-card green">
<div class="value">+{line_stats['total_insertions']:,}</div>
<div class="label">Lines Added</div>
</div>
<div class="stat-card" style="--val-color: var(--red);">
<div class="value red">-{line_stats['total_deletions']:,}</div>
<div class="label">Lines Removed</div>
</div>
</div>
<!-- Weekly Activity Chart -->
<div class="section">
<h2>Weekly Activity</h2>
<div class="card">
<div class="spark" id="weekly-chart">
{_build_sparkline(metrics['weekly'][-26:])}
</div>
</div>
</div>
<!-- Two Column: Hour Heatmap + Day Distribution -->
<div class="two-col">
<div class="section">
<h2>Activity by Hour</h2>
<div class="card">
{hour_heatmap}
</div>
</div>
<div class="section">
<h2>Activity by Day</h2>
<div class="card">
{_build_weekday_bars(metrics['weekday_dist'])}
</div>
</div>
</div>
<!-- Contribution Calendar -->
<div class="section">
<h2>Contribution Calendar</h2>
<div class="card" style="overflow-x:auto;">
{calendar_html}
</div>
</div>
<!-- Two Column: Contributors + Hotspots -->
<div class="two-col">
<div class="section">
<h2>Top Contributors</h2>
<div class="card">
<table>
<thead><tr><th>Author</th><th>Commits</th><th>Share</th><th>Added</th><th>Removed</th></tr></thead>
<tbody>{contrib_rows}</tbody>
</table>
</div>
</div>
<div class="section">
<h2>File Hotspots</h2>
<div class="card">
<table>
<thead><tr><th>File</th><th>Changes</th><th></th></tr></thead>
<tbody>{hotspot_rows}</tbody>
</table>
</div>
</div>
</div>
<div class="footer">
Generated by <a href="https://github.com/the-tangerine-agent/gitpulse">GitPulse</a> v{__version__}
· Part of the <a href="https://the-tangerine-agent.github.io/orange-digital/">Orange Digital</a> developer toolkit
</div>
</div>
</body>
</html>"""
def _esc(text):
"""HTML-escape text."""
return str(text).replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
def _build_sparkline(weekly_data):
"""Build a simple bar sparkline from weekly data."""
if not weekly_data:
return ""
max_val = max(w[1] for w in weekly_data) or 1
bars = []
for _, count in weekly_data:
height = max(4, int(count / max_val * 80))
bars.append(f'<div class="spark-bar" style="height:{height}px" title="{count} commits"></div>')
return '\n'.join(bars)
def _build_hour_heatmap(hour_dist):
"""Build hour-of-day heatmap."""
max_val = max(hour_dist) or 1
cells = []
for h, count in enumerate(hour_dist):
level = _intensity_level(count, max_val)
cells.append(f'<div class="heat-cell l{level}" title="{h:02d}:00 — {count} commits">{count if count else ""}</div>')
labels = []
for h in range(24):
label = f"{h}" if h % 3 == 0 else ""
labels.append(f'<span>{label}</span>')
return f"""
<div class="heatmap">{''.join(cells)}</div>
<div class="heat-labels">{''.join(labels)}</div>
"""
def _build_weekday_bars(weekday_dist):
"""Build horizontal bar chart for weekday distribution."""
max_val = max(w[1] for w in weekday_dist) or 1
rows = []
for name, count in weekday_dist:
width = max(4, int(count / max_val * 100))
rows.append(f"""
<div style="display:flex;align-items:center;gap:12px;margin-bottom:8px;">
<span style="width:30px;color:var(--muted);font-size:0.85rem;">{name}</span>
<div style="flex:1;height:20px;background:var(--surface2);border-radius:4px;overflow:hidden;">
<div style="width:{width}%;height:100%;background:var(--accent);border-radius:4px;"></div>
</div>
<span style="width:40px;text-align:right;font-size:0.85rem;color:var(--muted);">{count}</span>
</div>""")
return '\n'.join(rows)
def _build_calendar(daily_data):
"""Build a GitHub-style contribution calendar for the last 52 weeks."""
today = datetime.now()
start = today - timedelta(days=364)
# Get max for color scaling
max_daily = max(daily_data.values()) if daily_data else 1
weeks_html = []
current_week = []
d = start
# Pad first week
first_weekday = d.weekday()
for _ in range(first_weekday):
current_week.append('<div class="cal-day" style="visibility:hidden"></div>')
while d <= today:
d_str = d.strftime("%Y-%m-%d")
count = daily_data.get(d_str, 0)
level = _intensity_level(count, max_daily)
current_week.append(f'<div class="cal-day l{level}" title="{d_str}: {count} commits"></div>')
if d.weekday() == 6 or d == today:
weeks_html.append(f'<div class="cal-week">{"".join(current_week)}</div>')
current_week = []
d += timedelta(days=1)
return f'<div class="calendar">{"".join(weeks_html)}</div>'
def _intensity_level(count, max_val):
"""Return 0-4 intensity level."""
if count == 0:
return 0
ratio = count / max_val
if ratio <= 0.25:
return 1
elif ratio <= 0.5:
return 2
elif ratio <= 0.75:
return 3
return 4
# ---------------------------------------------------------------------------
# JSON Output
# ---------------------------------------------------------------------------
def generate_json(metrics, line_stats, hotspots, repo_name):
"""Generate JSON output."""
data = {
"generator": f"GitPulse v{__version__}",
"generated_at": datetime.now().isoformat(),
"repository": repo_name,
"summary": {
"total_commits": metrics["total_commits"],
"total_authors": metrics["total_authors"],
"date_range": f"{metrics['first_date']} to {metrics['last_date']}",
"days_span": metrics["days_span"],
"avg_commits_per_day": metrics["avg_per_day"],
"max_streak_days": metrics["max_streak"],
"peak_hour": metrics["peak_hour"],
"peak_day": metrics["peak_day"],
"lines_added": line_stats["total_insertions"],
"lines_removed": line_stats["total_deletions"],
},
"contributors": [
{"name": name, "commits": count, "percentage": round(count * 100 / metrics["total_commits"], 1)}
for name, count in metrics["authors"]
],
"hourly_distribution": metrics["hour_dist"],
"weekly_distribution": [{"day": d, "commits": c} for d, c in metrics["weekday_dist"]],
"file_hotspots": [
{"file": f, "changes": c}
for f, c in hotspots.most_common(20)
],
}
return json.dumps(data, indent=2)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="GitPulse — Repository activity dashboard",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
gitpulse.py Dashboard for current repo
gitpulse.py /path/to/repo Specific repository
gitpulse.py --days 30 Last 30 days only
gitpulse.py --json JSON output
gitpulse.py --author "Alice" Filter by author
gitpulse.py -o dashboard.html Custom output path
"""
)
parser.add_argument("repo", nargs="?", default=".",
help="Path to git repository (default: .)")
parser.add_argument("-o", "--output", help="Output file path")
parser.add_argument("--json", action="store_true", help="JSON output instead of HTML")
parser.add_argument("--days", type=int, help="Limit to last N days")
parser.add_argument("--author", help="Filter by author name (substring match)")
parser.add_argument("--max-commits", type=int, default=2000,
help="Max commits to analyze (default: 2000)")
parser.add_argument("--quiet", action="store_true", help="Suppress stats to stderr")
parser.add_argument("--version", action="version", version=f"GitPulse v{__version__}")
args = parser.parse_args()
repo_path = Path(args.repo).resolve()
if not is_git_repo(repo_path):
print(f"Error: {repo_path} is not a git repository", file=sys.stderr)
sys.exit(1)
repo_name = get_repo_name(repo_path)
remote_url = get_remote_url(repo_path)
if not args.quiet:
print(f"\n GitPulse v{__version__}", file=sys.stderr)
print(f" {'=' * 40}", file=sys.stderr)
print(f" Repository: {repo_name}", file=sys.stderr)
# Gather data
commits = get_commit_log(repo_path, args.days, args.author, args.max_commits)
if not commits:
print("No commits found.", file=sys.stderr)
sys.exit(0)
metrics = analyze_commits(commits)
line_stats = get_line_stats(repo_path, args.days, min(args.max_commits, 500))
hotspots = get_file_changes(repo_path, args.days, args.max_commits)
if not args.quiet:
print(f" Commits: {metrics['total_commits']}", file=sys.stderr)
print(f" Contributors: {metrics['total_authors']}", file=sys.stderr)
print(f" Date range: {metrics['first_date']} to {metrics['last_date']}", file=sys.stderr)
print(f" Avg/day: {metrics['avg_per_day']}", file=sys.stderr)
print(file=sys.stderr)
# Generate output
if args.json:
output = generate_json(metrics, line_stats, hotspots, repo_name)
default_ext = ".json"
else:
output = generate_html(metrics, line_stats, hotspots, repo_name, remote_url)
default_ext = ".html"
# Write
if args.output:
out_path = args.output
else:
out_path = f"gitpulse-{repo_name}{default_ext}"
Path(out_path).write_text(output)
if not args.quiet:
print(f" Dashboard: {out_path}", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())