-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitstats.py
More file actions
1775 lines (1379 loc) · 44.8 KB
/
Copy pathgitstats.py
File metadata and controls
1775 lines (1379 loc) · 44.8 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
"""
gitstats.py
Compute Diff Delta stats for Git repos.
Supports:
- whole repo score
- one commit score
- date ranges
- monthly breakdown
- monthly breakdown by author
- direct-subfolder repo recursion
- aggregate stats across repos
- recursive monthly breakdown by author
- full-range aggregate by user
- full-range aggregate total row
- filter summary
- excluded filetypes
- HTML report with charts
- JSON output
Usage:
python gitstats.py .\repo
python gitstats.py .\repo --commit HEAD
python gitstats.py .\repo --from "2025-06-01 00:00:00" --to "2025-11-30 23:59:59"
python gitstats.py .\repo --by-month-user
python gitstats.py --recurse C:\Projects --by-month-user
python gitstats.py --recurse C:\Projects --by-month-user --html-report .\gitstats_report.html
python gitstats.py --recurse C:\Projects --exclude-ext .csv --exclude-ext .xml
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import html
import io
import json
import math
import re
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable
try:
import matplotlib.pyplot as plt
except ImportError:
plt = None
BASE_SCORE = {
"add": 0.80,
"delete": 1.00,
"update": 1.00,
"move": 0.35,
"copy_paste": 0.25,
"find_replace": 0.60,
}
LANGUAGE_WEIGHT = {
".py": 1.00,
".go": 1.00,
".rs": 1.00,
".c": 1.05,
".h": 1.00,
".cpp": 1.05,
".hpp": 1.00,
".cs": 1.00,
".java": 1.00,
".js": 0.95,
".ts": 0.95,
".html": 0.60,
".css": 0.55,
".json": 0.45,
".yaml": 0.45,
".yml": 0.45,
".md": 0.35,
".txt": 0.25,
}
GENERATED_OR_NOISY_PATHS = [
"dist/",
"build/",
"target/",
"node_modules/",
"__pycache__/",
".min.js",
".pb.go",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
]
COMPILED_EXTENSIONS = {
".exe",
".dll",
".so",
".dylib",
".class",
".pyc",
".o",
".obj",
".bin",
}
DEFAULT_EXCLUDED_EXTENSIONS = {
".csv",
}
EXCLUDED_EXTENSIONS: set[str] = set(DEFAULT_EXCLUDED_EXTENSIONS)
FILTER_LABELS = {
"scored": "Scored lines",
"compiled_file": "Compiled/binary file lines",
"generated_or_noisy_path": "Generated/noisy path lines",
"excluded_filetype": "Excluded filetype lines",
"blank_line": "Blank lines",
"comment_line": "Comment lines",
"delimiter_only_line": "Delimiter-only lines",
}
@dataclass
class LineEvent:
commit: str
commit_time: int
file: str
operation: str
line: str
CommitInfo = tuple[str, int, str]
# commit_hash, commit_time_epoch, author_name
def normalise_extension(value: str) -> str:
value = value.strip().lower()
if not value:
return value
if not value.startswith("."):
value = "." + value
return value
def run_git(repo: Path, args: list[str]) -> str:
cmd = ["git", "-C", str(repo), *args]
proc = subprocess.run(
cmd,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise RuntimeError(proc.stderr.strip())
return proc.stdout
def validate_repo(repo: Path) -> None:
if not repo.exists():
raise ValueError(f"repo does not exist: {repo}")
if not repo.is_dir():
raise ValueError(f"repo path is not a directory: {repo}")
result = run_git(repo, ["rev-parse", "--is-inside-work-tree"]).strip()
if result != "true":
raise ValueError(f"not a git repo: {repo}")
def find_direct_git_repos(root: Path) -> list[Path]:
if not root.exists():
raise ValueError(f"recurse path does not exist: {root}")
if not root.is_dir():
raise ValueError(f"recurse path is not a directory: {root}")
repos: list[Path] = []
for child in sorted(root.iterdir()):
if not child.is_dir():
continue
try:
validate_repo(child)
repos.append(child.resolve())
except Exception:
continue
return repos
def get_commits(
repo: Path,
since: str | None,
until: str | None,
max_count: int | None,
) -> list[CommitInfo]:
args = ["log", "--format=%H%x00%ct%x00%an"]
if since:
args.append(f"--since={since}")
if until:
args.append(f"--until={until}")
if max_count:
args.append(f"--max-count={max_count}")
output = run_git(repo, args)
commits: list[CommitInfo] = []
for line in output.splitlines():
if not line.strip():
continue
commit, timestamp, author = line.split("\x00", 2)
commits.append((commit, int(timestamp), author))
return commits
def get_one_commit(repo: Path, commit: str) -> CommitInfo:
output = run_git(
repo,
["show", "-s", "--format=%H%x00%ct%x00%an", commit],
).strip()
commit_hash, timestamp, author = output.split("\x00", 2)
return commit_hash, int(timestamp), author
def parse_patch(repo: Path, commit: str, commit_time: int) -> list[LineEvent]:
patch = run_git(
repo,
[
"show",
"--format=",
"--find-renames",
"--find-copies",
"--unified=0",
"--no-ext-diff",
commit,
],
)
events: list[LineEvent] = []
current_file: str | None = None
for raw in patch.splitlines():
line = raw.rstrip("\n")
if line.startswith("+++ b/"):
current_file = line[6:]
continue
if line.startswith("+++ /dev/null"):
current_file = None
continue
if not current_file:
continue
if line.startswith("+++ ") or line.startswith("--- "):
continue
if line.startswith("@@"):
continue
if line.startswith("+") and not line.startswith("+++"):
events.append(
LineEvent(
commit=commit,
commit_time=commit_time,
file=current_file,
operation="add",
line=line[1:],
)
)
elif line.startswith("-") and not line.startswith("---"):
events.append(
LineEvent(
commit=commit,
commit_time=commit_time,
file=current_file,
operation="delete",
line=line[1:],
)
)
return infer_updates(events)
def infer_updates(events: list[LineEvent]) -> list[LineEvent]:
by_file: dict[str, list[LineEvent]] = {}
for event in events:
by_file.setdefault(event.file, []).append(event)
inferred: list[LineEvent] = []
for file_events in by_file.values():
adds = [e for e in file_events if e.operation == "add"]
deletes = [e for e in file_events if e.operation == "delete"]
update_pairs = min(len(adds), len(deletes))
add_ids = {id(e) for e in adds[:update_pairs]}
del_ids = {id(e) for e in deletes[:update_pairs]}
for event in file_events:
if id(event) in add_ids or id(event) in del_ids:
event.operation = "update"
inferred.append(event)
return inferred
def file_branch_filter_reason(event: LineEvent) -> str:
path = event.file.lower()
suffix = Path(path).suffix.lower()
if suffix in COMPILED_EXTENSIONS:
return "compiled_file"
if suffix in EXCLUDED_EXTENSIONS:
return "excluded_filetype"
if any(marker in path for marker in GENERATED_OR_NOISY_PATHS):
return "generated_or_noisy_path"
return "scored"
def file_branch_filter(event: LineEvent) -> float:
return 0.0 if file_branch_filter_reason(event) != "scored" else 1.0
def context_filter_reason(event: LineEvent) -> str:
text = event.line.strip()
if not text:
return "blank_line"
comment_prefixes = ("#", "//", "--", "/*", "*", "*/")
if text.startswith(comment_prefixes):
return "comment_line"
delimiter_only = {
"{",
"}",
"};",
");",
"(",
")",
"[",
"]",
",",
";",
}
if text in delimiter_only:
return "delimiter_only_line"
return "scored"
def context_filter(event: LineEvent) -> float:
return 0.0 if context_filter_reason(event) != "scored" else 1.0
def filter_summary(events: list[LineEvent]) -> dict[str, int]:
summary = {key: 0 for key in FILTER_LABELS}
for event in events:
file_reason = file_branch_filter_reason(event)
if file_reason != "scored":
summary[file_reason] += 1
continue
context_reason = context_filter_reason(event)
if context_reason != "scored":
summary[context_reason] += 1
continue
summary["scored"] += 1
return summary
def duplication_groups(events: Iterable[LineEvent]) -> dict[str, int]:
counts: dict[str, int] = {}
for event in events:
key = duplicate_key(event)
counts[key] = counts.get(key, 0) + 1
return counts
def duplicate_key(event: LineEvent) -> str:
normalised = re.sub(r"\s+", " ", event.line.strip())
payload = f"{event.operation}:{normalised}"
return hashlib.sha1(payload.encode("utf-8", errors="replace")).hexdigest()
def duplication_filter(event: LineEvent, groups: dict[str, int]) -> float:
size = groups.get(duplicate_key(event), 1)
if size <= 1:
return 1.0
return 1.0 / size
def base_score(event: LineEvent) -> float:
return BASE_SCORE.get(event.operation, 0.50)
def time_scalar(event: LineEvent, newest_commit_time: int) -> float:
age_seconds = max(0, newest_commit_time - event.commit_time)
age_days = age_seconds / 86_400
return 0.5 + 0.7 * (1.0 - math.exp(-age_days / 60.0))
def context_scalar(event: LineEvent) -> float:
suffix = Path(event.file).suffix.lower()
language_weight = LANGUAGE_WEIGHT.get(suffix, 0.75)
invocation_bonus = 1.08 if looks_like_invocation(event.line) else 1.00
return language_weight * invocation_bonus
def looks_like_invocation(line: str) -> bool:
text = line.strip()
if not text:
return False
if re.search(r"\b(if|for|while|switch|catch)\s*\(", text):
return False
return bool(re.search(r"\w+\s*\(", text))
def score_event(
event: LineEvent,
groups: dict[str, int],
newest_commit_time: int,
) -> dict:
phi = file_branch_filter(event)
theta = context_filter(event)
dup = duplication_filter(event, groups)
beta = base_score(event)
tau = time_scalar(event, newest_commit_time)
sigma = context_scalar(event)
score = phi * theta * dup * beta * tau * sigma
return {
"commit": event.commit[:12],
"file": event.file,
"operation": event.operation,
"line": event.line,
"phi": round(phi, 4),
"theta": round(theta, 4),
"dup": round(dup, 4),
"beta": round(beta, 4),
"tau": round(tau, 4),
"sigma": round(sigma, 4),
"score": round(score, 6),
}
def compute(repo: Path, commits: list[CommitInfo]) -> dict:
all_events: list[LineEvent] = []
for commit, commit_time, _author in commits:
all_events.extend(parse_patch(repo, commit, commit_time))
if not all_events:
return {
"diff_delta": 0.0,
"commits": len(commits),
"events": 0,
"scored_events": 0,
"filter_summary": {key: 0 for key in FILTER_LABELS},
"by_commit": {},
"by_file": {},
"rows": [],
}
newest_commit_time = max(event.commit_time for event in all_events)
filters = filter_summary(all_events)
groups = duplication_groups(all_events)
rows = [score_event(event, groups, newest_commit_time) for event in all_events]
total = sum(row["score"] for row in rows)
by_commit: dict[str, float] = {}
by_file: dict[str, float] = {}
for row in rows:
by_commit[row["commit"]] = by_commit.get(row["commit"], 0.0) + row["score"]
by_file[row["file"]] = by_file.get(row["file"], 0.0) + row["score"]
return {
"diff_delta": round(total, 6),
"commits": len(commits),
"events": len(rows),
"scored_events": sum(1 for row in rows if row["score"] > 0),
"filter_summary": filters,
"by_commit": {
k: round(v, 6)
for k, v in sorted(by_commit.items(), key=lambda item: item[1], reverse=True)
},
"by_file": {
k: round(v, 6)
for k, v in sorted(by_file.items(), key=lambda item: item[1], reverse=True)
},
"rows": rows,
}
def month_key(timestamp: int) -> str:
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
return f"{dt.year:04d}-{dt.month:02d}"
def compute_by_month(repo: Path, commits: list[CommitInfo]) -> dict:
groups: dict[str, list[CommitInfo]] = {}
for commit, commit_time, author in commits:
month = month_key(commit_time)
groups.setdefault(month, []).append((commit, commit_time, author))
result = {}
for month in sorted(groups):
stats = compute(repo, groups[month])
result[month] = {
"diff_delta": stats["diff_delta"],
"commits": stats["commits"],
"events": stats["events"],
"scored_events": stats["scored_events"],
"filter_summary": stats["filter_summary"],
"top_files": dict(list(stats["by_file"].items())[:10]),
"top_commits": dict(list(stats["by_commit"].items())[:10]),
}
return result
def compute_by_month_user(repo: Path, commits: list[CommitInfo]) -> dict:
groups: dict[str, dict[str, list[CommitInfo]]] = {}
for commit, commit_time, author in commits:
month = month_key(commit_time)
groups.setdefault(month, {})
groups[month].setdefault(author, [])
groups[month][author].append((commit, commit_time, author))
result = {}
for month in sorted(groups):
result[month] = {}
for author in sorted(groups[month]):
stats = compute(repo, groups[month][author])
result[month][author] = {
"diff_delta": stats["diff_delta"],
"commits": stats["commits"],
"events": stats["events"],
"scored_events": stats["scored_events"],
"filter_summary": stats["filter_summary"],
"top_files": dict(list(stats["by_file"].items())[:10]),
"top_commits": dict(list(stats["by_commit"].items())[:10]),
}
return result
def merge_filter_summaries(summaries: list[dict[str, int]]) -> dict[str, int]:
merged = {key: 0 for key in FILTER_LABELS}
for summary in summaries:
for key in FILTER_LABELS:
merged[key] += summary.get(key, 0)
return merged
def merge_score_maps(maps: list[dict[str, float]]) -> dict[str, float]:
merged: dict[str, float] = {}
for score_map in maps:
for key, value in score_map.items():
merged[key] = merged.get(key, 0.0) + value
return {
k: round(v, 6)
for k, v in sorted(merged.items(), key=lambda item: item[1], reverse=True)
}
def namespace_result(repo_name: str, result: dict) -> dict:
namespaced = dict(result)
namespaced["by_file"] = {
f"{repo_name}/{path}": score
for path, score in result["by_file"].items()
}
namespaced["by_commit"] = {
f"{repo_name}:{commit}": score
for commit, score in result["by_commit"].items()
}
return namespaced
def aggregate_results(results: list[dict]) -> dict:
return {
"diff_delta": round(sum(r["diff_delta"] for r in results), 6),
"repos": len(results),
"commits": sum(r["commits"] for r in results),
"events": sum(r["events"] for r in results),
"scored_events": sum(r["scored_events"] for r in results),
"filter_summary": merge_filter_summaries(
[r["filter_summary"] for r in results]
),
"by_commit": merge_score_maps([r["by_commit"] for r in results]),
"by_file": merge_score_maps([r["by_file"] for r in results]),
"rows": [],
}
def merge_month_user_results(repo_month_user_results: dict[str, dict]) -> dict:
aggregate: dict[str, dict[str, dict]] = {}
for repo_name, monthly_user in repo_month_user_results.items():
for month, authors in monthly_user.items():
aggregate.setdefault(month, {})
for author, stats in authors.items():
aggregate[month].setdefault(
author,
{
"diff_delta": 0.0,
"commits": 0,
"events": 0,
"scored_events": 0,
"filter_summary": {key: 0 for key in FILTER_LABELS},
"top_files": {},
"top_commits": {},
},
)
target = aggregate[month][author]
target["diff_delta"] += stats["diff_delta"]
target["commits"] += stats["commits"]
target["events"] += stats["events"]
target["scored_events"] += stats["scored_events"]
target["filter_summary"] = merge_filter_summaries(
[
target["filter_summary"],
stats["filter_summary"],
]
)
namespaced_files = {
f"{repo_name}/{path}": score
for path, score in stats["top_files"].items()
}
namespaced_commits = {
f"{repo_name}:{commit}": score
for commit, score in stats["top_commits"].items()
}
target["top_files"] = merge_score_maps(
[
target["top_files"],
namespaced_files,
]
)
target["top_commits"] = merge_score_maps(
[
target["top_commits"],
namespaced_commits,
]
)
for month in aggregate:
for author in aggregate[month]:
aggregate[month][author]["diff_delta"] = round(
aggregate[month][author]["diff_delta"],
6,
)
aggregate[month][author]["top_files"] = dict(
list(aggregate[month][author]["top_files"].items())[:10]
)
aggregate[month][author]["top_commits"] = dict(
list(aggregate[month][author]["top_commits"].items())[:10]
)
return {
month: aggregate[month]
for month in sorted(aggregate)
}
def collapse_month_user_to_user_totals(monthly_user: dict) -> dict:
totals: dict[str, dict] = {}
for _month, authors in monthly_user.items():
for author, stats in authors.items():
totals.setdefault(
author,
{
"commits": 0,
"events": 0,
"scored_events": 0,
"diff_delta": 0.0,
"filter_summary": {key: 0 for key in FILTER_LABELS},
},
)
target = totals[author]
target["commits"] += stats["commits"]
target["events"] += stats["events"]
target["scored_events"] += stats["scored_events"]
target["diff_delta"] += stats["diff_delta"]
target["filter_summary"] = merge_filter_summaries(
[
target["filter_summary"],
stats["filter_summary"],
]
)
for author in totals:
totals[author]["diff_delta"] = round(totals[author]["diff_delta"], 6)
return {
author: totals[author]
for author in sorted(
totals,
key=lambda name: totals[name]["diff_delta"],
reverse=True,
)
}
def collapse_month_user_to_total(monthly_user: dict) -> dict:
total = {
"commits": 0,
"events": 0,
"scored_events": 0,
"diff_delta": 0.0,
"filter_summary": {key: 0 for key in FILTER_LABELS},
}
for _month, authors in monthly_user.items():
for _author, stats in authors.items():
total["commits"] += stats["commits"]
total["events"] += stats["events"]
total["scored_events"] += stats["scored_events"]
total["diff_delta"] += stats["diff_delta"]
total["filter_summary"] = merge_filter_summaries(
[
total["filter_summary"],
stats["filter_summary"],
]
)
total["diff_delta"] = round(total["diff_delta"], 6)
return total
def print_filter_summary(summary: dict[str, int]) -> None:
print()
print("Filter summary:")
print("-" * 44)
total = sum(summary.values())
for key, label in FILTER_LABELS.items():
count = summary.get(key, 0)
percent = (count / total * 100) if total else 0.0
print(f" {label:<30} {count:>8} {percent:>6.2f}%")
def print_active_exclusions() -> None:
if not EXCLUDED_EXTENSIONS:
return
print()
print("Excluded filetypes:")
print("-" * 44)
for ext in sorted(EXCLUDED_EXTENSIONS):
print(f" {ext}")
def print_total_user_report(user_totals: dict) -> None:
print()
print("Aggregate by user for full range:")
print(
f"{'Author':<28} "
f"{'Commits':>8} "
f"{'Events':>8} "
f"{'Scored':>8} "
f"{'Diff Delta':>12}"
)
print("-" * 74)
for author, stats in user_totals.items():
print(
f"{author[:28]:<28} "
f"{stats['commits']:>8} "
f"{stats['events']:>8} "
f"{stats['scored_events']:>8} "
f"{stats['diff_delta']:>12.6f}"
)
def print_total_range_report(total: dict) -> None:
print()
print("Aggregate for full range:")
print(
f"{'Commits':>8} "
f"{'Events':>8} "
f"{'Scored':>8} "
f"{'Diff Delta':>12}"
)
print("-" * 44)
print(
f"{total['commits']:>8} "
f"{total['events']:>8} "
f"{total['scored_events']:>8} "
f"{total['diff_delta']:>12.6f}"
)
def print_text_report(result: dict) -> None:
if "repos" in result:
print(f"Repos: {result['repos']}")
print(f"Diff Delta: {result['diff_delta']}")
print(f"Commits: {result['commits']}")
print(f"Events: {result['events']}")
print(f"Scored: {result['scored_events']}")
print()
print("Top commits:")
for commit, score in list(result["by_commit"].items())[:10]:
print(f" {commit:<32} {score}")
print()
print("Top files:")
for file, score in list(result["by_file"].items())[:15]:
print(f" {score:<10} {file}")
print_filter_summary(result["filter_summary"])
print_active_exclusions()
def print_monthly_report(monthly: dict) -> None:
print(f"{'Month':<10} {'Commits':>8} {'Events':>8} {'Scored':>8} {'Diff Delta':>12}")
print("-" * 52)
for month, stats in monthly.items():
print(
f"{month:<10} "
f"{stats['commits']:>8} "
f"{stats['events']:>8} "
f"{stats['scored_events']:>8} "
f"{stats['diff_delta']:>12.6f}"
)
merged = merge_filter_summaries(
[stats["filter_summary"] for stats in monthly.values()]
)
print_filter_summary(merged)
print_active_exclusions()
def print_month_user_report(monthly_user: dict) -> None:
print(
f"{'Month':<10} "
f"{'Author':<28} "
f"{'Commits':>8} "
f"{'Events':>8} "
f"{'Scored':>8} "
f"{'Diff Delta':>12}"
)
print("-" * 82)
for month, authors in monthly_user.items():
for author, stats in sorted(
authors.items(),
key=lambda item: item[1]["diff_delta"],
reverse=True,
):
print(
f"{month:<10} "
f"{author[:28]:<28} "
f"{stats['commits']:>8} "
f"{stats['events']:>8} "
f"{stats['scored_events']:>8} "
f"{stats['diff_delta']:>12.6f}"
)
summaries = []
for authors in monthly_user.values():
for stats in authors.values():
summaries.append(stats["filter_summary"])
merged = merge_filter_summaries(summaries)
print_filter_summary(merged)
print_active_exclusions()
def print_recurse_report(repo_results: dict[str, dict], aggregate: dict) -> None:
print("Repos:")
print(f"{'Repo':<32} {'Commits':>8} {'Events':>8} {'Scored':>8} {'Diff Delta':>12}")
print("-" * 76)
for repo_name, result in sorted(
repo_results.items(),
key=lambda item: item[1]["diff_delta"],
reverse=True,
):
print(
f"{repo_name[:32]:<32} "
f"{result['commits']:>8} "
f"{result['events']:>8} "
f"{result['scored_events']:>8} "
f"{result['diff_delta']:>12.6f}"
)
print()
print("Aggregate:")
print_text_report(aggregate)
def print_recurse_month_user_report(
repo_month_user_results: dict[str, dict],
aggregate_month_user: dict,
) -> None:
print("Repos:")
print(