- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitmetry.py
More file actions
Latest commit
executable file
·928 lines (867 loc) · 49.6 KB
/
Copy pathgitmetry.py
File metadata and controls
executable file
·928 lines (867 loc) · 49.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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
#!/usr/bin/env python3
"""
gitmetry.py — personal developer-efficiency report from git history.
Measures 11 dimensions across local repos (mapped to DORA / SPACE / CodeScene), grouped
as Activity (1) · First-pass quality (2–5) · Code structure (6–9) · People (10–11):
1. Throughput — commits/month cross-project + batch-size distribution & commits/active-day (SPACE Activity)
2. Rework rate — churn on recently changed code (by anyone, --rework-days) (CodeScene/MS churn)
3. Test co-change — share of code commits that also touch a test (first-pass-quality habit)
4. Corrective/value — Feature/Refactoring vs Fix vs Hotfix vs Revert (hotfix = DORA Change-Failure proxy)
5. Defect hotspots — where your Fix commits land × complexity
6. Functional changes — CCN of functions you touched + net complexity delta vs parent (lizard)
7. Complexity hotspots — change frequency × complexity (CodeScene)
8. Change coupling — files changed together (CodeScene temporal coupling)
9. Code-health trend — code complexity over time via git-archive snapshots (--health-trend)
10. Sustainability — when you commit (off-hours/weekend rhythm, SPACE well-being)
11. Ownership/bus factor — authorship share per file, churn- and recency-weighted (CodeScene knowledge map)
Plus pre-aggregated year / quarter / whole-window overviews (rollup) so figures and YoY
deltas come straight from raw counts instead of being re-derived from monthly rows.
Dependencies: git, scc (https://github.com/boyter/scc), python -m lizard (pip install --user lizard).
Everything is read-only over git (git archive/show); it never touches the working tree.
Examples:
gitmetry # last 24 months, markdown to stdout
gitmetry --since 2024-01 --until 2026-06 --out report.md
gitmetry --format json --out report.json
gitmetry --health-trend # + slow code-health trend (minutes)
"""
importargparse
importbisect
importcollections
importdatetime
importglob
importjson
importmath
importos
importre
importshutil
importstatistics
importsubprocess
importsys
importtempfile
__version__="0.1.0"
# ---------- dates ----------
defmonth_floor(d): returnd.replace(day=1)
defadd_month(ym):
y, m=map(int, ym.split("-")); m+=1
ifm==13: y+=1; m=1
returnf"{y}-{m:02d}"
defdefault_window():
today=datetime.date.today()
until=month_floor(today)
# until = first day of next month so current month is included
until= (until.replace(year=until.year+1, month=1) ifuntil.month==12
elseuntil.replace(month=until.month+1))
# since = 24 months before this month's first day
y, m=today.year, today.month
m-=24
whilem<=0: m+=12; y-=1
since=datetime.date(y, m, 1)
returnsince.strftime("%Y-%m-%d"), until.strftime("%Y-%m-%d")
# ---------- git helpers ----------
defgit(repo, *args):
p=subprocess.run(["git", "-C", repo, *args], capture_output=True,
text=True, errors="replace")
# `show` (missing blob) and `config` (unset key) fail benignly and are handled by callers;
# any other non-zero exit means a query silently returned nothing — surface it.
ifp.returncode!=0andargs[:1] notin (("show",), ("config",)):
err=p.stderr.strip().splitlines()
sys.stderr.write(f"! git {' '.join(args[:2])} failed in {os.path.basename(repo)}: "
f"{err[0] iferrelse'exit '+str(p.returncode)}\n")
returnp.stdout
defiter_commits(repo, *args):
"""Run `git log <args>` whose pretty format is a single 'C|…' sentinel line, and yield
(header, files) per commit. header = the text after 'C|' (the rest of your format, e.g.
'%ci' or '%ct|%an|%ae'). files = list of (add, del, path): ints for --numstat lines,
(None, None, path) for --name-only. Unifies the numstat-parsing loop shared by the
throughput / rework / ownership / test-co-change layers."""
header=None; files=None
forlineingit(repo, "log", *args).splitlines():
ifline.startswith("C|"):
ifheaderisnotNone: yieldheader, files
header=line[2:]; files= []
elifline.strip() andheaderisnotNone:
p=line.split("\t")
iflen(p) ==3:
files.append((int(p[0]) ifp[0].isdigit() else0,
int(p[1]) ifp[1].isdigit() else0, p[2]))
eliflen(p) ==1:
files.append((None, None, p[0]))
ifheaderisnotNone: yieldheader, files
deflist_repos(root):
repos=sorted(dfordinglob.glob(os.path.join(root, "*"))
ifos.path.isdir(os.path.join(d, ".git")))
ifos.path.isdir(os.path.join(root, ".git")): # root itself is a repo
repos.insert(0, os.path.normpath(root))
returnrepos
deffind_scc():
returnshutil.which("scc") or (os.path.expanduser("~/bin/scc")
ifos.path.exists(os.path.expanduser("~/bin/scc")) elseNone)
# ---------- personal config ----------
# Optional, never-committed defaults so each user keeps their own author/root/repo/ext
# out of this shared repo. First file found wins; explicit CLI flags still override it.
CONFIG_KEYS= ("author", "root", "main_repo", "main_ext", "paths", "code_exts", "exclude",
"rework_days", "off_hours", "big_batch", "coupling_min_shared")
deffind_config():
"""First existing personal-config path: $GITMETRY_CONFIG, ./.gitmetry.json,
then $XDG_CONFIG_HOME/gitmetry/config.json. None if nothing is found."""
xdg=os.environ.get("XDG_CONFIG_HOME") oros.path.expanduser("~/.config")
forpathin (os.environ.get("GITMETRY_CONFIG"), ".gitmetry.json",
os.path.join(xdg, "gitmetry", "config.json")):
ifpathandos.path.isfile(os.path.expanduser(path)):
returnos.path.expanduser(path)
returnNone
defload_config(path):
"""Parse a personal-defaults JSON file into argparse overrides (known keys only)."""
withopen(path, encoding="utf-8") asfh:
cfg=json.load(fh)
ifnotisinstance(cfg, dict):
raiseValueError("config must be a JSON object")
out= {k: cfg[k] forkinCONFIG_KEYSifkincfg}
if"root"inout: out["root"] =os.path.expanduser(out["root"])
returnout
# ---------- code-path filter ----------
# tests / test-doubles / generated migrations / deps / build artifacts (multi-language).
# Directory names match at path start or after a slash; test-file suffixes match the basename.
DEFAULT_EXCLUDE= (r'((?:Test|Fake|Mock)\.\w+$|[._](?:test|spec)\.\w+$|\.spec\.|\.test\.'
r'|(?i:(?:^|/)(?:tests?|migrations?|vendor|node_modules|var|tmp|build|dist)/))')
# Positive test-file detector (FooTest.php, foo.test.ts, foo.spec.js, foo_test.go, tests/…).
TEST_FILE=re.compile(r'((?:Test|Spec)\.\w+$|[._](?:test|spec)\.\w+$|\.spec\.|\.test\.'
r'|_test\.\w+$|(?i:(?:^|/)tests?/))')
defis_test_file(path):
returnbool(TEST_FILE.search(path))
defis_code(path, exts):
ext=path.rsplit(".", 1)[-1].lower() if"."inpathelse""
returnextinexts
defmain_src(path, ext):
"""A primary-language (`ext`) source file for the deep layers, excluding tests.
Covers conventions across languages: FooTest.php, foo.test.ts, foo.spec.js, foo_test.go."""
ifnotpath.endswith("."+ext): returnFalse
segs=path.lower().split("/")
if"test"insegsor"tests"insegs: returnFalse
base=segs[-1]
returnnotany(base.endswith(suf+"."+ext) forsufin ("test", ".test", ".spec", "_test"))
defexcluded(path, rx):
returnbool(rxandrx.search(path))
defpercentile(xs, q):
"""Nearest-rank percentile (q in 0..1); 0 for empty input."""
ifnotxs: return0
s=sorted(xs)
returns[min(len(s) -1, int(round(q* (len(s) -1))))]
defpct(n, d):
"""Integer percentage n/d, or 0 when the denominator is 0."""
returnround(100*n/d) ifdelse0
# ---------- 1. throughput (cross-project) ----------
defthroughput(repos, author, since, until, exts=None, exrx=None, big_batch=400):
"""exts=None → counts all files; otherwise code only (a commit counts only if it
touched at least 1 code file). exrx → regex of paths to exclude. big_batch = churn
threshold for the `big%` share. Returns (monthly, per_repo, month_sizes); month_sizes
(churn per commit, per month) is kept out of JSON but feeds the period rollup."""
mon=collections.defaultdict(lambda: {"commits": 0, "add": 0, "del": 0,
"repos": set(), "sizes": [], "days": set()})
per_repo=collections.Counter()
forrinrepos:
name=os.path.basename(r)
forci, filesiniter_commits(r, "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "--numstat",
"--pretty=format:C|%ci"):
ca=cd=0; touched=False
fora, d, pathinfiles:
ifextsisnotNoneandnotis_code(path, exts): continue
ifexcluded(path, exrx): continue
ca+=aor0; cd+=dor0; touched=True
ifextsisnotNoneandnottouched: continue# commit touched no code file
cm=ci[:7]
mon[cm]["commits"] +=1; mon[cm]["repos"].add(name); per_repo[name] +=1
mon[cm]["add"] +=ca; mon[cm]["del"] +=cd
mon[cm]["sizes"].append(ca+cd) # churn per commit → batch-size distribution
mon[cm]["days"].add(ci[:10])
monthly= {}; sizes= {}
form, vinmon.items():
ad=len(v["days"]); n=len(v["sizes"])
big=sum(1forsinv["sizes"] ifs>big_batch)
monthly[m] = {"commits": v["commits"], "add": v["add"], "del": v["del"],
"repos": len(v["repos"]),
"med": round(statistics.median(v["sizes"])) ifv["sizes"] else0,
"p90": percentile(v["sizes"], 0.9),
"big": big, "big_pct": pct(big, n),
"active_days": ad,
"cpd": round(v["commits"] /ad, 2) ifadelse0}
sizes[m] =v["sizes"]
returnmonthly, dict(per_repo), sizes
# ---------- 2. functional changes (lizard, main repo) ----------
HUNK=re.compile(r'^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@')
deffunctional_changes(repo, author, since, until, paths, ext):
try:
importlizard
exceptImportError:
returnNone
out=git(repo, "log", "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "-U0", "--pretty=format:CMT|%H|%ci", "--", *paths)
commits= []; cur=None; cfile=None
forlineinout.splitlines():
ifline.startswith("CMT|"):
_, sha, ai=line.split("|", 2)
cur= {"sha": sha, "month": ai[:7], "files": collections.defaultdict(set)}
commits.append(cur); cfile=None
elifline.startswith("+++ b/"): cfile=line[6:]
elifline.startswith("+++ /dev/null"): cfile=None
elifline.startswith("@@") andcurisnotNoneandcfile:
mt=HUNK.match(line)
ifnotmt: continue
start=int(mt.group(1)); cnt=int(mt.group(2)) ifmt.group(2) else1
forlninrange(start, start+cnt): cur["files"][cfile].add(ln)
cache= {}
deffuncs_at(sha, path):
key= (sha, path)
ifkeyincache: returncache[key]
code=git(repo, "show", f"{sha}:{path}")
res= []
ifcode.strip():
try:
r=lizard.analyze_file.analyze_source_code(path, code)
res= [(f.cyclomatic_complexity, f.start_line, f.end_line) forfinr.function_list]
exceptException: res= []
cache[key] =res; returnres
mon=collections.defaultdict(lambda: {"ccn": [], "files": set(), "commits": 0, "cx_net": 0})
seen_commit=set()
forcincommits:
m=c["month"]
ifc["sha"] notinseen_commit: mon[m]["commits"] +=1; seen_commit.add(c["sha"])
forpath, linesinc["files"].items():
ifnotmain_src(path, ext): continue
mon[m]["files"].add(path)
after=funcs_at(c["sha"], path)
forccn, s, einafter:
ifany(s<=ln<=eforlninlines): mon[m]["ccn"].append(ccn)
# file-level complexity delta vs the parent commit: did this change make the
# file more or less complex? (new file → parent show is empty → before = 0)
after_tot=sum(ccnforccn, _, _inafter)
before_tot=sum(ccnforccn, _, _infuncs_at(c["sha"] +"^", path))
mon[m]["cx_net"] +=after_tot-before_tot
res= {}
form, vinmon.items():
ccn=v["ccn"]
res[m] = {"commits": v["commits"], "files": len(v["files"]), "fn_changed": len(ccn),
"avg_ccn": round(sum(ccn) /len(ccn), 1) ifccnelse0,
"ccn_sum": sum(ccn),
"med_ccn": statistics.median(ccn) ifccnelse0,
"max_ccn": max(ccn) ifccnelse0,
"risky": sum(1forcinccnifc>15),
"severe": sum(1forcinccnifc>50),
"cx_net": v["cx_net"]}
returnres
# ---------- 3. rework rate (main repo) ----------
defrework(repo, author, since, until, threshold_days=14, exts=None, exrx=None):
# timeline = every commit (anyone) that touched each file, across full history
timeline=collections.defaultdict(list)
forts, filesiniter_commits(repo, "--no-merges", "--pretty=format:C|%ct", "--name-only"):
t=int(ts)
for_, _, pathinfiles: timeline[path].append(t)
forfintimeline: timeline[f].sort()
TH=threshold_days*86400
mon=collections.defaultdict(lambda: {"rework": 0, "total": 0})
forhdr, filesiniter_commits(repo, "-i", f"--author={author}", "--no-merges",
f"--since={since}", f"--until={until}",
"--pretty=format:C|%ct|%ci", "--numstat"):
ct, ci=hdr.split("|", 1); cur=int(ct); m=ci[:7] # %ct: window math, %ci: local month
fora, d, pathinfiles:
ifextsisnotNoneandnotis_code(path, exts): continue
ifexcluded(path, exrx): continue
ch= (aor0) + (dor0); mon[m]["total"] +=ch
tl=timeline.get(path, []); i=bisect.bisect_left(tl, cur)
ifi>0andcur-tl[i-1] <=TH: mon[m]["rework"] +=ch
return {m: {"rework_pct": pct(v["rework"], v["total"]),
"churn": v["total"], "rework_churn": v["rework"]} form, vinmon.items()}
# ---------- 4. corrective vs value-add (cross-project) ----------
# Hotfix kept separate from Fix: hotfix = production fire = cleanest DORA Change-Failure signal.
# Covers golemos convention (Feature/Refactoring/Chore/Docs) and Conventional Commits (feat/perf/...).
NORM= {"feature": "value", "feat": "value", "refactoring": "value", "refactor": "value",
"perf": "value", "fix": "fix", "hotfix": "hotfix", "revert": "fix",
"chore": "other", "docs": "other", "test": "other", "build": "other",
"ci": "other", "style": "other"}
def_prefix(subject):
"""Lowercased '<Type>' of a subject, with Conventional-Commits scope and breaking
'!' stripped: 'feat(api)!: x' -> 'feat'. Empty string if there is no ':' prefix."""
pref=subject.split(":", 1)[0].strip().lower() if":"insubjectelse""
returnre.sub(r"\(.*?\)", "", pref).rstrip("!").strip()
defclassify_commit(subject):
"""Map a commit subject to value|fix|hotfix|other by its '<Type>:' prefix."""
returnNORM.get(_prefix(subject), "other")
defis_revert(subject):
"""A revert — either git's auto-generated 'Revert \"…\"' or a 'revert:' prefix.
Reverts also fall under `fix` (NORM), so this is a subset surfaced separately."""
returnsubject.strip().startswith('Revert "') or_prefix(subject) =="revert"
defcorrective(repos, author, since, until):
mon=collections.defaultdict(lambda: collections.Counter())
forrinrepos:
out=git(r, "log", "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "--pretty=format:%ci|%s")
forlineinout.splitlines():
if"|"notinline: continue
d, s=line.split("|", 1); m=d[:7] # committer-local month from %ci
mon[m][classify_commit(s)] +=1
ifis_revert(s): mon[m]["revert"] +=1# parallel tally; already counted in `fix`
res= {}
form, cinmon.items():
tot=c["value"] +c["fix"] +c["hotfix"] +c["other"] # not `revert` (subset of fix)
corr=c["fix"] +c["hotfix"]
res[m] = {"value": c["value"], "fix": c["fix"], "hotfix": c["hotfix"],
"other": c["other"], "revert": c["revert"],
"corr_pct": pct(corr, tot),
"hotfix_pct": pct(c["hotfix"], tot),
"revert_pct": pct(c["revert"], tot)}
returnres
# ---------- 11. test co-change (cross-project) ----------
defcochange(repos, author, since, until, exts=None, exrx=None):
"""Of your commits that touch production code, the share that also touch a test file —
a habit proxy for first-pass quality (message-independent). A file counts as a test by
TEST_FILE; otherwise it's production if it's code (`exts`) and not excluded."""
mon=collections.defaultdict(lambda: {"prod": 0, "with_tests": 0})
forrinrepos:
forci, filesiniter_commits(r, "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "--name-only",
"--pretty=format:C|%ci"):
prod=tests=False
for_, _, pathinfiles:
ifis_test_file(path): tests=True
elif (extsisNoneoris_code(path, exts)) andnotexcluded(path, exrx): prod=True
ifnotprod: continue# only commits that touch production code count
m=ci[:7]
mon[m]["prod"] +=1
iftests: mon[m]["with_tests"] +=1
return {m: {"prod": v["prod"], "with_tests": v["with_tests"],
"pct": pct(v["with_tests"], v["prod"])}
form, vinmon.items()}
# ---------- 5. defect hotspots (main repo) ----------
defdefect_hotspots(repo, author, since, until, cx, ext, top=20):
out=git(repo, "log", "-i", f"--author={author}", "--no-merges", f"--since={since}",
f"--until={until}", "-E", r"--grep=^Fix(\(.*\))?!?:", r"--grep=^Hotfix(\(.*\))?!?:",
"--pretty=format:C", "--name-only")
fc=collections.Counter()
forlineinout.splitlines():
iflineandline!="C"andmain_src(line, ext):
fc[line] +=1
return [{"file": p, "fixes": n, "cx": cx.get(p, None)} forp, ninfc.most_common(top)]
# ---------- 6. complexity hotspots + code-health (scc) ----------
defscc_byfile(scc, repo, paths, ext):
out=subprocess.run([scc, "--by-file", "-f", "json", "--no-cocomo", "--include-ext", ext,
"--exclude-dir", "vendor,node_modules,var,tmp,log,tests",
*[os.path.join(repo, p) forpinpaths]],
capture_output=True, text=True).stdout
cx= {}; loc= {}
try:
forlanginjson.loads(out):
forfinlang["Files"]:
p=os.path.relpath(f["Location"], repo)
cx[p] =f["Complexity"]; loc[p] =f["Code"]
exceptException: pass
returncx, loc
defchange_hotspots(repo, author, since, until, cx, loc, ext, top=20):
out=git(repo, "log", "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "--pretty=format:C", "--name-only")
touch=collections.Counter()
forlineinout.splitlines():
iflineandline!="C"andmain_src(line, ext):
touch[line] +=1
hs= [{"file": p, "touches": t, "cx": cx.get(p, 0), "loc": loc.get(p, 0),
"score": t*cx.get(p, 0)} forp, tintouch.items()]
returnsorted(hs, key=lambdax: x["score"], reverse=True)[:top]
# ---------- 7. change coupling (temporal coupling, main repo) ----------
defchange_coupling(repo, author, since, until, ext, min_shared=5, max_files=20, top=20):
"""Pairs of primary-language files you change together within one commit (CodeScene
temporal coupling). Large commits (> max_files files) don't contribute pairs —
bulk/mechanical changes would add noise — but they do count toward per-file revs.
degree = shared / min(revs_a, revs_b) → 'when you touch the rarer one, how often
does the other come along'."""
out=git(repo, "log", "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "--pretty=format:C", "--name-only")
commits= []; cur=None
forlineinout.splitlines():
ifline=="C":
cur= []; commits.append(cur)
elifline.strip() andcurisnotNoneandmain_src(line, ext):
cur.append(line)
revs=collections.Counter(); pair=collections.Counter()
forfilesincommits:
files=sorted(set(files))
forfinfiles: revs[f] +=1
if2<=len(files) <=max_files:
foriinrange(len(files)):
forjinrange(i+1, len(files)):
pair[(files[i], files[j])] +=1
res= []
for (a, b), sharedinpair.items():
ifshared<min_shared: continue
ra, rb=revs[a], revs[b]
res.append({"a": a, "b": b, "shared": shared, "revs_a": ra, "revs_b": rb,
"degree": round(100*shared/min(ra, rb))})
returnsorted(res, key=lambdax: (x["degree"], x["shared"]), reverse=True)[:top]
# ---------- 8. sustainability / wellbeing (cross-project) ----------
defsustainability(repos, author, since, until, off_start=8, off_end=19):
"""When you commit — a proxy for work rhythm (SPACE well-being). Committer time
from %ci (commit's local TZ). off-h = outside [off_start, off_end), wknd = Sat/Sun.
Trend > absolute number."""
mon=collections.defaultdict(lambda: {"commits": 0, "off": 0, "wknd": 0, "days": set()})
all_dates=set()
forrinrepos:
out=git(r, "log", "-i", f"--author={author}", f"--since={since}",
f"--until={until}", "--no-merges", "--pretty=format:%ci")
forlineinout.splitlines():
parts=line.strip().split(" ")
iflen(parts) <2: continue
date, tm=parts[0], parts[1]
try:
hour=int(tm[:2]); wd=datetime.date.fromisoformat(date).weekday()
except (ValueError, IndexError): continue
m=date[:7]
mon[m]["commits"] +=1; mon[m]["days"].add(date); all_dates.add(date)
ifhour<off_startorhour>=off_end: mon[m]["off"] +=1
ifwd>=5: mon[m]["wknd"] +=1
longest=streak=0; prev=None
fordinsorted(all_dates):
dt=datetime.date.fromisoformat(d)
streak=streak+1if (previsnotNoneand (dt-prev).days==1) else1
longest=max(longest, streak); prev=dt
monthly= {m: {"commits": v["commits"], "active_days": len(v["days"]),
"off": v["off"], "wknd": v["wknd"],
"off_pct": pct(v["off"], v["commits"]),
"wknd_pct": pct(v["wknd"], v["commits"])}
form, vinmon.items()}
return {"monthly": monthly, "longest_streak": longest}
# ---------- 9. ownership / bus factor (main repo, full history) ----------
defownership(repo, author_rx, exts=None, exrx=None, min_churn=30, top=20, halflife_days=365):
"""Authorship share per file across the FULL repo history (the knowledge map is not
windowed). yours = churn of commits whose author matches the regex; share = yours/total.
dominant > 50 %, solo ≥ 80 % (bus-factor riziko).
Two complementary lenses on bus factor:
• churn share — who wrote the most lines ever (`your_pct`).
• recency — churn weighted by exp(-age/halflife) so a fresh rewrite outweighs old
lines (`recency_pct`), plus `last_you`: are you the most recent toucher? Bus factor
is about who knows the code *now*, not who typed the most lines years ago."""
arx=author_rxifhasattr(author_rx, "search") elsere.compile(author_rx, re.I)
files=collections.defaultdict(lambda: {"total": 0, "yours": 0, "dtot": 0.0,
"dyours": 0.0, "last_you": None})
now_ref=None; hl=halflife_days*86400
forhdr, fliniter_commits(repo, "--no-merges", "--pretty=format:C|%ct|%an|%ae", "--numstat"):
ct, an, ae=hdr.split("|", 2)
ts=int(ct) ifct.isdigit() else (now_refor0)
ifnow_refisNone: now_ref=ts# log is newest-first → first ts is the latest
mine=bool(arx.search(an) orarx.search(ae))
w=math.exp(-(now_ref-ts) /hl) ifnow_refelse1.0
fora, d, pathinfl:
ifextsisnotNoneandnotis_code(path, exts): continue
ifexcluded(path, exrx): continue
ch= (aor0) + (dor0)
f=files[path]
f["total"] +=ch; f["dtot"] +=ch*w
ifmine: f["yours"] +=ch; f["dyours"] +=ch*w
iff["last_you"] isNone: f["last_you"] =mine# first row for a file = latest touch
repo_churn=sum(f["total"] forfinfiles.values())
your_churn=sum(f["yours"] forfinfiles.values())
dtot=sum(f["dtot"] forfinfiles.values())
dyours=sum(f["dyours"] forfinfiles.values())
rows= [{"file": p, "your_pct": pct(f["yours"], f["total"]),
"your_churn": f["yours"], "total_churn": f["total"],
"recency_pct": pct(f["dyours"], f["dtot"]),
"last_you": bool(f["last_you"])}
forp, finfiles.items() iff["total"] >=min_churn]
dominant= [rforrinrowsifr["your_pct"] >50]
solo= [rforrinrowsifr["your_pct"] >=80]
return {"your_share_pct": pct(your_churn, repo_churn),
"recency_share_pct": pct(dyours, dtot),
"your_churn": your_churn, "repo_churn": repo_churn,
"files_considered": len(rows), "dominant_files": len(dominant),
"solo_files": len(solo),
"last_author_files": sum(1forrinrowsifr["last_you"]),
"top": sorted(dominant, key=lambdax: x["total_churn"], reverse=True)[:top]}
defhealth_trend(scc, repo, since, until, paths, ext):
months= []
cur=since[:7]
whilecur<=until[:7]:
months.append(cur); cur=add_month(cur)
rows= []
foryminmonths:
sha=git(repo, "rev-list", "-1", f"--before={add_month(ym)}-01", "HEAD").strip()
ifnotsha: continue
withtempfile.TemporaryDirectory() assnap:
p=subprocess.Popen(["git", "-C", repo, "archive", sha, *paths], stdout=subprocess.PIPE)
subprocess.run(["tar", "-x", "-C", snap], stdin=p.stdout); p.wait()
out=subprocess.run([scc, "-f", "json", "--no-cocomo", "--include-ext", ext,
"--exclude-dir", "tests", snap], capture_output=True, text=True).stdout
tot_cx=loc=0
try:
forlanginjson.loads(out):
tot_cx+=lang.get("Complexity", 0); loc+=lang.get("Code", 0)
exceptException: continue
rows.append({"month": ym, "total_cx": tot_cx, "loc": loc,
"cx_per_kloc": round(1000*tot_cx/loc, 1) iflocelse0})
returnrows
# ---------- period rollup (year / quarter / whole window) ----------
def_bucket(month, period):
"""Map a 'YYYY-MM' key to its rollup bucket label."""
ifperiod=="window": return"all"
ifperiod=="quarter": returnf"{month[:4]}-Q{(int(month[5:7]) -1) //3+1}"
returnmonth[:4] # year
defrollup(data, month_sizes, period="year"):
"""Pre-aggregate the monthly metric dicts into year / quarter / whole-window buckets,
re-deriving percentages from raw counts (not averaging rounded monthly %s) so the
report can quote a yearly figure / YoY delta without re-doing the arithmetic."""
th=data["throughput"]["monthly"]; rw=data["rework"]; cv=data["corrective"]
su= (data.get("sustainability") or {}).get("monthly", {})
fn=data.get("functional") or {}; cc=data.get("cochange") or {}
buckets= {}
defB(m):
returnbuckets.setdefault(_bucket(m, period), collections.defaultdict(float))
form, vinth.items():
b=B(m)
forkin ("commits", "add", "del", "big", "active_days"): b[k] +=v.get(k, 0)
b.setdefault("sizes", []).extend(month_sizes.get(m, []))
form, vinrw.items():
b=B(m); b["rework_churn"] +=v.get("rework_churn", 0); b["churn"] +=v["churn"]
form, vincv.items():
b=B(m)
forkin ("value", "fix", "hotfix", "other", "revert"): b[k] +=v.get(k, 0)
form, vinfn.items():
b=B(m)
forkin ("ccn_sum", "fn_changed", "severe", "risky", "cx_net"): b[k] +=v.get(k, 0)
form, vinsu.items():
b=B(m); b["off"] +=v.get("off", 0); b["wknd"] +=v.get("wknd", 0)
b["su_commits"] +=v["commits"]
form, vincc.items():
b=B(m); b["cc_prod"] +=v["prod"]; b["cc_tests"] +=v["with_tests"]
out= {}
fork, binbuckets.items():
sizes=b.get("sizes", []); n=b["commits"]; cls=b["value"] +b["fix"] +b["hotfix"] +b["other"]
out[k] = {"commits": int(n), "add": int(b["add"]), "del": int(b["del"]),
"med": round(statistics.median(sizes)) ifsizeselse0,
"p90": percentile(sizes, 0.9), "big_pct": pct(b["big"], n),
"active_days": int(b["active_days"]),
"rework_pct": pct(b["rework_churn"], b["churn"]),
"corr_pct": pct(b["fix"] +b["hotfix"], cls), "hotfix": int(b["hotfix"]),
"hotfix_pct": pct(b["hotfix"], cls), "revert": int(b["revert"]),
"avg_ccn": round(b["ccn_sum"] /b["fn_changed"], 1) ifb["fn_changed"] else0,
"fn_changed": int(b["fn_changed"]), "severe": int(b["severe"]),
"cx_net": int(b["cx_net"]),
"off_pct": pct(b["off"], b["su_commits"]),
"wknd_pct": pct(b["wknd"], b["su_commits"]),
"cochange_pct": pct(b["cc_tests"], b["cc_prod"])}
returnout
# ---------- render markdown ----------
defrender_md(data, meta):
L= []
L.append("# Dev efficiency report\n")
L.append(f"- Author: `{meta['author']}` | Window: **{meta['since']} → {meta['until']}** "
f"(read YoY across the monthly tables)")
L.append(f"- Repos: {meta['nrepos']} local | Main repo (deep analysis): `{meta['main']}`")
L.append(f"- Line-metric scope: **{meta['scope']}** "
f"({'code files only'ifmeta['scope']=='code-only'else'incl. docs/data'})")
L.append("- Standards: DORA (Change-Failure proxy via hotfix/fix) · SPACE (throughput, batch size) "
"· CodeScene (rework, hotspots, change coupling) · MS Research (relative churn)\n")
rl=data.get("rollup") or {}
def_overview(title, table, label, partial=None):
ifnottable: return
L.append(f"## {title}\n")
L.append("| "+label+" | commits | act.d | med | p90 | big% | rework% | corr% | "
"hotfix | rev | avg CCN | Δcx | severe | off-h% | wknd% | test% |")
L.append("|---|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|--:|")
forkinsorted(table):
r=table[k]; mark="*"ifpartialandpartial(k) else""
L.append(f"| {k}{mark} | {r['commits']} | {r['active_days']} | {r['med']} | {r['p90']} | "
f"{r['big_pct']}% | {r['rework_pct']}% | {r['corr_pct']}% | {r['hotfix']} | "
f"{r['revert']} | {r['avg_ccn']} | {r['cx_net']:+d} | {r['severe']} | "
f"{r['off_pct']}% | {r['wknd_pct']}% | {r['cochange_pct']}% |")
L.append("")
ifrl.get("window"):
w=rl["window"]
L.append(f"**Window totals:** {w['commits']} commits over {w['active_days']} active days · "
f"median batch {w['med']} (p90 {w['p90']}, big {w['big_pct']}%) · "
f"rework {w['rework_pct']}% · corrective {w['corr_pct']}% (hotfix {w['hotfix_pct']}%, "
f"{w['revert']} reverts) · avg CCN {w['avg_ccn']} (Δcx {w['cx_net']:+d}, "
f"{w['severe']} severe) · off-hours {w['off_pct']}% / weekend {w['wknd_pct']}% · "
f"test co-change {w['cochange_pct']}%\n")
since_y, until_y=meta["since"], meta["until"]
def_partial_year(y):
n=int(y); returnnot (since_y<=f"{n}-01-01"anduntil_y>=f"{n+1}-01-01")
_overview("Yearly overview", rl.get("yearly"), "year", _partial_year)
_overview("Quarterly overview", rl.get("quarterly"), "quarter")
ifrl.get("yearly"):
L.append("> Overview rows re-derive every % from raw counts (not an average of the "
"monthly %s); `*` marks a partial year. `Δcx` = net function-complexity added "
"by your changes; `test%` = commits touching code that also touch a test.\n")
th=data["throughput"]["monthly"]; per_repo=data["throughput"]["per_repo"]
L.append("## 1) Throughput (cross-project)\n")
L.append("Batch size: `med`/`p90` = median / 90th percentile of churn (add+del) per commit, "
"`big%` = share of commits > 400 lines, `cpd` = commits per active day. "
"Small batch = better (DORA/trunk-based); the median ignores AI/generated spikes, "
"unlike the `added`/`deleted` sums.\n")
L.append("| month | commits | added | deleted | med | p90 | big% | act.d | cpd | repos |")
L.append("|---|--:|--:|--:|--:|--:|--:|--:|--:|--:|")
forminsorted(th):
r=th[m]; L.append(f"| {m} | {r['commits']} | {r['add']} | {r['del']} | "
f"{r['med']} | {r['p90']} | {r['big_pct']}% | {r['active_days']} | "
f"{r['cpd']} | {r['repos']} |")
L.append("\n**Commits per repo:** "+", ".join(f"{k} ({v})"fork, vin
sorted(per_repo.items(), key=lambdax: -x[1])) +"\n")
# ----- First-pass quality (2–5) -----
L.append("## 2) Rework rate (main repo)\n")
L.append("| month | rework % | churn |")
L.append("|---|--:|--:|")
forminsorted(data["rework"]):
r=data["rework"][m]; L.append(f"| {m} | {r['rework_pct']}% | {r['churn']} |")
L.append("")
ifdata.get("cochange"):
L.append("## 3) Test co-change (cross-project)\n")
L.append("Of your commits that touch production code, the share that also touch a test "
"file — a message-independent first-pass-quality habit. `prod` = commits "
"touching code, `+tests` = those that also touched a test. Trend > absolute.\n")
L.append("| month | prod commits | +tests | test co-change % |")
L.append("|---|--:|--:|--:|")
forminsorted(data["cochange"]):
r=data["cochange"][m]
L.append(f"| {m} | {r['prod']} | {r['with_tests']} | {r['pct']}% |")
L.append("")
L.append("## 4) Corrective vs value-add (cross-project)\n")
L.append("`hotfix` (production fire) = the cleanest DORA Change-Failure signal; "
"`fix` mixes features and trivia, so treat `corr %` as indicative. "
"`revert` is a subset of `fix` surfaced separately (git's `Revert \"…\"` or a "
"`revert:` prefix) — a sharper undo signal.\n")
L.append("| month | value | fix | hotfix | revert | other | corr % | hotfix % |")
L.append("|---|--:|--:|--:|--:|--:|--:|--:|")
forminsorted(data["corrective"]):
r=data["corrective"][m]
L.append(f"| {m} | {r['value']} | {r['fix']} | {r['hotfix']} | {r['revert']} | {r['other']} | "
f"{r['corr_pct']}% | {r['hotfix_pct']}% |")
L.append("")
L.append("## 5) Defect hotspots (main repo) — files in your Fix/Hotfix commits\n")
L.append("| fixes | cx | file |")
L.append("|--:|--:|---|")
forrindata["defects"]:
L.append(f"| {r['fixes']} | {r['cx'] ifr['cx'] isnotNoneelse'—'} | `{r['file']}` |")
L.append("")
# ----- Code structure / complexity (6–9) -----
ifdata.get("functional"):
L.append("## 6) Functional changes (lizard, main repo)\n")
L.append("CCN of the functions you touched (`avg`/`med`/`max`, `>15` risky, `>50` severe). "
"`Δcx` = net function-complexity your commits added vs removed that month "
"(file totals after − before parent); negative = you simplified.\n")
L.append("| month | commits | files | fn changed | avg CCN | med | max | >15 | >50 | Δcx |")
L.append("|---|--:|--:|--:|--:|--:|--:|--:|--:|--:|")
f=data["functional"]
forminsorted(f):
r=f[m]; L.append(f"| {m} | {r['commits']} | {r['files']} | {r['fn_changed']} | "
f"{r['avg_ccn']} | {r['med_ccn']} | {r['max_ccn']} | {r['risky']} | "
f"{r['severe']} | {r['cx_net']:+d} |")
L.append("")
ifdata.get("hotspots"):
L.append("## 7) Complexity hotspots (change frequency × complexity)\n")
L.append("| score | touches | cx | loc | file |")
L.append("|--:|--:|--:|--:|---|")
forrindata["hotspots"]:
L.append(f"| {r['score']} | {r['touches']} | {r['cx']} | {r['loc']} | `{r['file']}` |")
L.append("")
ifdata.get("coupling"):
L.append("## 8) Change coupling (temporal coupling, main repo)\n")
L.append("Pairs of files you change together. `degree` = how often they go hand in hand "
"(shared / min revs). High = hidden dependency / missing abstraction.\n")
L.append("| degree | shared | revs A | revs B | file A | file B |")
L.append("|--:|--:|--:|--:|---|---|")
forrindata["coupling"]:
L.append(f"| {r['degree']}% | {r['shared']} | {r['revs_a']} | {r['revs_b']} | "
f"`{r['a']}` | `{r['b']}` |")
L.append("")
ifdata.get("health"):
L.append("## 9) Code-health trend (scc snapshots)\n")
L.append(f"| month | total cx | {meta.get('main_ext','')} loc | cx/kLOC |")
L.append("|---|--:|--:|--:|")
forrindata["health"]:
L.append(f"| {r['month']} | {r['total_cx']} | {r['loc']} | {r['cx_per_kloc']} |")
L.append("")
# ----- Sustainability & people (10–11) -----
ifdata.get("sustainability"):
s=data["sustainability"]
L.append("## 10) Sustainability / rhythm (cross-project)\n")
L.append(f"When you commit — a proxy for work rhythm (SPACE well-being). "
f"`off-h%` = outside {meta.get('off_hours', '8–19')}, `weekend%` = Sat/Sun. "
f"Trend > absolute number; committer time can shift with rebase / delayed push.\n")
L.append(f"**Longest streak of consecutive days with a commit:** {s['longest_streak']}\n")
L.append("| month | commits | active days | off-h % | weekend % |")
L.append("|---|--:|--:|--:|--:|")
forminsorted(s["monthly"]):
r=s["monthly"][m]
L.append(f"| {m} | {r['commits']} | {r['active_days']} | {r['off_pct']}% | {r['wknd_pct']}% |")
L.append("")
ifdata.get("ownership"):
o=data["ownership"]
L.append("## 11) Ownership / bus factor (main repo, full history)\n")
L.append(f"Your share of the repo's churn: **{o['your_share_pct']}%** "
f"({o['your_churn']} of {o['repo_churn']} lines), "
f"recency-weighted **{o['recency_share_pct']}%** (1y half-life). "
f"Of {o['files_considered']} tracked files (churn ≥ 30): "
f"**{o['dominant_files']}** where you are the main author (>50 %), "
f"of which **{o['solo_files']}** effectively solo (≥80 % = bus-factor risk); "
f"you are the most recent toucher of **{o['last_author_files']}**. "
f"`recency%` weights churn by age (fresh > old); `last` = you committed last. "
f"Your top files by impact (total churn):\n")
L.append("| your % | recency % | last | your churn | total churn | file |")
L.append("|--:|--:|:--:|--:|--:|---|")
forrino["top"]:
L.append(f"| {r['your_pct']}% | {r['recency_pct']}% | {'you'ifr['last_you'] else'—'} | "
f"{r['your_churn']} | {r['total_churn']} | `{r['file']}` |")
L.append("")
L.append("> ⚠️ Line metrics (added/deleted) are often skewed by generated code "
"(AI tests, docs, lock files). Most trustworthy: commit throughput, rework rate, function CCN.")
return"\n".join(L)
# ---------- analysis pipeline ----------
defrun_analysis(args):
"""Resolve targets from the parsed args, run all layers and return (data, meta).
Pure git-reading + computation — no output formatting or writing (that stays in main),
so the whole pipeline is callable/testable on its own. Bad input exits via sys.exit."""
since=args.sinceiflen(args.since) >7elseargs.since+"-01"
until=args.untiliflen(args.until) >7elseargs.until+"-01"
repos=list_repos(args.root)
ifnotrepos:
sys.exit(f"No git repository found under {args.root} (expected {args.root}/.git or {args.root}/*/.git)")
# resolve main repo: explicit --main-repo, else the only repo found
ifargs.main_repo:
main_repo=os.path.join(args.root, args.main_repo)
ifnotos.path.isdir(main_repo):
sys.exit(f"Main repo not found: {main_repo}")
eliflen(repos) ==1:
main_repo=repos[0]
args.main_repo=os.path.basename(main_repo)
else:
names=", ".join(os.path.basename(r) forrinrepos)
sys.exit(f"Multiple repos found ({names}) — pick one with --main-repo <name>")
# resolve author: explicit --author, else git config user.name of the main repo
ifnotargs.author:
args.author=git(main_repo, "config", "user.name").strip()
ifnotargs.author:
sys.exit("Could not determine author — set it with --author <name-regex>")
sys.stderr.write(f"· author (from git config): {args.author}\n")
try: # author is a regex (git --author -i and ownership); fail fast before the slow work
author_rx=re.compile(args.author, re.I)
exceptre.errorase:
sys.exit(f"Invalid --author regex {args.author!r}: {e}")
scc=find_scc()
exts=Noneifargs.include_docselseset(e.strip().lower() foreinargs.code_exts.split(",") ife.strip())
exrx=Noneifargs.no_excludeelsere.compile(args.exclude)
ext=args.main_ext.lstrip(".").lower()
try: # off-hours window "START-END" (24h) → (start, end)
off_start, off_end= (int(x) forxinstr(args.off_hours).split("-", 1))
exceptValueError:
sys.exit(f"Invalid --off-hours {args.off_hours!r}: expected START-END, e.g. 8-19")
sys.stderr.write("· throughput…\n")
th_monthly, th_per_repo, th_sizes=throughput(repos, args.author, since, until,
exts, exrx, args.big_batch)
sys.stderr.write("· rework…\n")
rw=rework(main_repo, args.author, since, until, args.rework_days, exts=exts, exrx=exrx)
sys.stderr.write("· corrective…\n")
cv=corrective(repos, args.author, since, until)
sys.stderr.write("· test co-change…\n")
co=cochange(repos, args.author, since, until, exts, exrx)
cx, loc= ({}, {})
ifscc:
sys.stderr.write("· scc complexity…\n")
cx, loc=scc_byfile(scc, main_repo, args.paths, ext)
else:
sys.stderr.write("! scc not found — hotspots without complexity\n")
df=defect_hotspots(main_repo, args.author, since, until, cx, ext)
hs=change_hotspots(main_repo, args.author, since, until, cx, loc, ext) ifsccelseNone
sys.stderr.write("· change coupling…\n")
cp=change_coupling(main_repo, args.author, since, until, ext,
min_shared=args.coupling_min_shared)
sys.stderr.write("· sustainability…\n")
su=sustainability(repos, args.author, since, until, off_start, off_end)
sys.stderr.write("· ownership / bus factor…\n")
ow=ownership(main_repo, author_rx, exts, exrx)
sys.stderr.write("· functional changes (lizard)…\n")
fn=functional_changes(main_repo, args.author, since, until, args.paths, ext)
iffnisNone: sys.stderr.write("! lizard not found — layer 2 skipped\n")
ht=None
ifargs.health_trendandscc:
sys.stderr.write("· code-health snapshots (slow)…\n")
ht=health_trend(scc, main_repo, since, until, args.paths, ext)
data= {"throughput": {"monthly": th_monthly, "per_repo": th_per_repo},
"rework": rw, "corrective": cv, "defects": df,
"hotspots": hs, "coupling": cp, "sustainability": su, "ownership": ow,
"functional": fn, "cochange": co, "health": ht}
# pre-aggregated overviews so the report can quote yearly figures / YoY without re-doing math
data["rollup"] = {"window": rollup(data, th_sizes, "window").get("all", {}),
"yearly": rollup(data, th_sizes, "year")}
ifargs.quarterly:
data["rollup"]["quarterly"] =rollup(data, th_sizes, "quarter")
meta= {"author": args.author, "since": since, "until": until,
"nrepos": len(repos), "main": args.main_repo, "main_ext": ext,
"scope": "all-files"ifextsisNoneelse"code-only",
"off_hours": f"{off_start}–{off_end}",
"exclude": Noneifargs.no_excludeelseargs.exclude}
returndata, meta
# ---------- main ----------
defmain():
ap=argparse.ArgumentParser(prog="gitmetry",
description="Personal developer-efficiency report from git history (read-only).")
ap.add_argument("--version", action="version", version=f"gitmetry {__version__}")
s0, u0=default_window()
ap.add_argument("--root", default=".",
help="directory holding the repos (each */.git); may itself be a repo")
ap.add_argument("--main-repo", default=None,
help="repo name (under --root) for deep analysis; default: the only repo found")
ap.add_argument("--author", default=None,
help="regex for git --author (-i); default: git config user.name of the main repo")
ap.add_argument("--main-ext", default="php",
help="primary language extension for deep layers 5/6/7/8/9 (php, js, ts, py, go, rb…)")
ap.add_argument("--since", default=s0, help="YYYY-MM-DD or YYYY-MM")
ap.add_argument("--until", default=u0)
ap.add_argument("--paths", nargs="+", default=["."], help="paths within the main repo to analyze")
ap.add_argument("--format", choices=["md", "json", "both"], default="md")
ap.add_argument("--out", default=None, help="output file (default: stdout)")
ap.add_argument("--health-trend", action="store_true", help="+ slow scc snapshot trend (minutes)")
ap.add_argument("--code-exts", default="php,phtml,js,mjs,cjs,ts,jsx,tsx,vue,css,scss,sass,"
"less,twig,sql,py,go,rb,sh,bash,html",
help="comma-separated extensions counted as code")
ap.add_argument("--include-docs", action="store_true",
help="also count non-code files (docs, csv, json, yaml, lock…); default: code only")
ap.add_argument("--exclude", default=DEFAULT_EXCLUDE,
help="regex of paths to exclude (tests/test-doubles/generated migrations/deps)")
ap.add_argument("--no-exclude", action="store_true",
help="do not exclude test/generated code from line metrics")
# tunable thresholds (previously hardcoded) — all overridable via config too
ap.add_argument("--rework-days", type=int, default=14,
help="rework window: churn on code touched within this many days (default 14)")
ap.add_argument("--off-hours", default="8-19",
help="working hours START-END; commits outside count as off-hours (default 8-19)")
ap.add_argument("--big-batch", type=int, default=400,
help="churn (add+del) above which a commit counts toward `big%%` (default 400)")
ap.add_argument("--coupling-min-shared", type=int, default=5,
help="min co-changes for a file pair to appear in change coupling (default 5)")
ap.add_argument("--quarterly", action="store_true",
help="also emit a quarterly overview table (in addition to yearly)")
cfg_path=find_config() # personal defaults override the static ones; CLI still wins
ifcfg_path:
try:
ap.set_defaults(**load_config(cfg_path))
except (OSError, ValueError, json.JSONDecodeError) ase:
sys.exit(f"Invalid config {cfg_path}: {e}")
args=ap.parse_args()
ifcfg_path:
sys.stderr.write(f"· config: {cfg_path}\n")
data, meta=run_analysis(args)
def_json_default(o):
ifisinstance(o, set): returnlist(o)
raiseTypeError(f"Object of type {type(o).__name__} is not JSON serializable")
md=render_md(data, meta) ifargs.formatin ("md", "both") elseNone
js=json.dumps({"meta": meta, "data": {k: vfork, vindata.items() ifvisnotNone}},
ensure_ascii=False, indent=2, default=_json_default)
def_write(path, text):
withopen(path, "w", encoding="utf-8") asfh: fh.write(text)
ifargs.out:
ifargs.format=="json": _write(args.out, js)
elifargs.format=="both":
_write(args.out, md)
_write(os.path.splitext(args.out)[0] +".json", js)
else: _write(args.out, md)
sys.stderr.write(f"✓ written: {args.out}\n")
else:
print(jsifargs.format=="json"elsemd)
if__name__=="__main__":
main()