git-xray-tool 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- git_xray/__init__.py +3 -0
- git_xray/__main__.py +5 -0
- git_xray/analysis.py +367 -0
- git_xray/cli.py +90 -0
- git_xray/render.py +312 -0
- git_xray_tool-0.1.0.dist-info/METADATA +160 -0
- git_xray_tool-0.1.0.dist-info/RECORD +10 -0
- git_xray_tool-0.1.0.dist-info/WHEEL +4 -0
- git_xray_tool-0.1.0.dist-info/entry_points.txt +2 -0
- git_xray_tool-0.1.0.dist-info/licenses/LICENSE +21 -0
git_xray/__init__.py
ADDED
git_xray/__main__.py
ADDED
git_xray/analysis.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Mine `git log` into hotspots, ownership, coupling and staleness metrics.
|
|
2
|
+
|
|
3
|
+
Pure Python, zero third-party dependencies. The only external process is `git`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import fnmatch
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import time
|
|
14
|
+
from collections import Counter, defaultdict
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from itertools import combinations
|
|
17
|
+
|
|
18
|
+
# Commits touching more files than this are usually mass reformatting,
|
|
19
|
+
# vendoring or license-header sweeps; they only add noise to coupling.
|
|
20
|
+
MAX_FILES_FOR_COUPLING = 30
|
|
21
|
+
|
|
22
|
+
DEFAULT_EXCLUDES = [
|
|
23
|
+
"*.lock", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock",
|
|
24
|
+
"Cargo.lock", "go.sum", "composer.lock", "Gemfile.lock", "uv.lock",
|
|
25
|
+
"*.min.js", "*.min.css", "*.map", "*.svg", "*.snap",
|
|
26
|
+
"vendor/*", "node_modules/*", "dist/*", "build/*", "third_party/*",
|
|
27
|
+
"CHANGELOG*", "CHANGES*", "HISTORY*", "NEWS*", "RELEASE_NOTES*",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
BOT_MARKERS = ("[bot]", "dependabot", "renovate", "github-actions", "pre-commit-ci")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def is_bot(author: str) -> bool:
|
|
34
|
+
a = author.lower()
|
|
35
|
+
return any(m in a for m in BOT_MARKERS)
|
|
36
|
+
|
|
37
|
+
COMMIT_MARK = "\x1e"
|
|
38
|
+
FIELD_SEP = "\x1f"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class GitError(RuntimeError):
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def run_git(args: list[str], cwd: str) -> str:
|
|
46
|
+
if not os.path.isdir(cwd):
|
|
47
|
+
raise GitError(f"no such directory: {cwd}")
|
|
48
|
+
try:
|
|
49
|
+
proc = subprocess.run(["git", *args], cwd=cwd, capture_output=True, check=False)
|
|
50
|
+
except FileNotFoundError as exc: # pragma: no cover
|
|
51
|
+
raise GitError("git executable not found on PATH") from exc
|
|
52
|
+
if proc.returncode != 0:
|
|
53
|
+
raise GitError(proc.stderr.decode("utf-8", "replace").strip() or "git failed")
|
|
54
|
+
return proc.stdout.decode("utf-8", "replace")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class Commit:
|
|
59
|
+
sha: str
|
|
60
|
+
author: str
|
|
61
|
+
timestamp: int
|
|
62
|
+
changes: list[tuple[str, int, int]] # (path, added, deleted)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class FileStats:
|
|
67
|
+
path: str
|
|
68
|
+
commits: int = 0
|
|
69
|
+
added: int = 0
|
|
70
|
+
deleted: int = 0
|
|
71
|
+
first_seen: int = 0
|
|
72
|
+
last_seen: int = 0
|
|
73
|
+
authors: Counter = field(default_factory=Counter) # author -> lines changed
|
|
74
|
+
loc: int = 0
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def churn(self) -> int:
|
|
78
|
+
return self.added + self.deleted
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def main_author(self) -> tuple[str, float]:
|
|
82
|
+
if not self.authors:
|
|
83
|
+
return ("?", 0.0)
|
|
84
|
+
total = sum(self.authors.values()) or 1
|
|
85
|
+
name, lines = self.authors.most_common(1)[0]
|
|
86
|
+
return name, lines / total
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
_BRACE_RENAME = re.compile(r"^(.*)\{(.*) => (.*)\}(.*)$")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def parse_numstat_path(raw: str) -> tuple[str | None, str]:
|
|
93
|
+
"""Return (old_path, new_path) from a numstat path column.
|
|
94
|
+
|
|
95
|
+
git prints renames as ``old => new`` or ``dir/{old => new}/rest``.
|
|
96
|
+
"""
|
|
97
|
+
m = _BRACE_RENAME.match(raw)
|
|
98
|
+
if m:
|
|
99
|
+
pre, old, new, post = m.groups()
|
|
100
|
+
old_p = re.sub("/+", "/", pre + old + post)
|
|
101
|
+
new_p = re.sub("/+", "/", pre + new + post)
|
|
102
|
+
return old_p, new_p
|
|
103
|
+
if " => " in raw:
|
|
104
|
+
old, new = raw.split(" => ", 1)
|
|
105
|
+
return old, new
|
|
106
|
+
return None, raw
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def read_log(repo: str, since: str | None = None, paths: list[str] | None = None,
|
|
110
|
+
rev: str = "HEAD") -> list[Commit]:
|
|
111
|
+
"""Read history newest-first, normalising renamed paths to their latest name."""
|
|
112
|
+
fmt = f"{COMMIT_MARK}%H{FIELD_SEP}%aN{FIELD_SEP}%at"
|
|
113
|
+
args = ["-c", "core.quotepath=off", "log", rev, "--no-merges", "--numstat", "-M",
|
|
114
|
+
f"--format={fmt}"]
|
|
115
|
+
if since:
|
|
116
|
+
args.append(f"--since={since}")
|
|
117
|
+
if paths:
|
|
118
|
+
args += ["--", *paths]
|
|
119
|
+
out = run_git(args, repo)
|
|
120
|
+
|
|
121
|
+
commits: list[Commit] = []
|
|
122
|
+
renames: dict[str, str] = {} # historical path -> current path
|
|
123
|
+
|
|
124
|
+
def resolve(p: str) -> str:
|
|
125
|
+
seen = set()
|
|
126
|
+
while p in renames and p not in seen:
|
|
127
|
+
seen.add(p)
|
|
128
|
+
p = renames[p]
|
|
129
|
+
return p
|
|
130
|
+
|
|
131
|
+
for block in out.split(COMMIT_MARK):
|
|
132
|
+
block = block.strip("\n")
|
|
133
|
+
if not block:
|
|
134
|
+
continue
|
|
135
|
+
lines = block.split("\n")
|
|
136
|
+
try:
|
|
137
|
+
sha, author, ts = lines[0].split(FIELD_SEP)
|
|
138
|
+
except ValueError:
|
|
139
|
+
continue
|
|
140
|
+
changes = []
|
|
141
|
+
for line in lines[1:]:
|
|
142
|
+
parts = line.split("\t", 2)
|
|
143
|
+
if len(parts) != 3:
|
|
144
|
+
continue
|
|
145
|
+
a, d, raw = parts
|
|
146
|
+
old, new = parse_numstat_path(raw)
|
|
147
|
+
current = resolve(new)
|
|
148
|
+
if old and old != new:
|
|
149
|
+
# Newest-first: older commits mentioning `old` are this same file.
|
|
150
|
+
renames.setdefault(old, current)
|
|
151
|
+
added = int(a) if a.isdigit() else 0 # "-" for binary files
|
|
152
|
+
deleted = int(d) if d.isdigit() else 0
|
|
153
|
+
changes.append((current, added, deleted))
|
|
154
|
+
commits.append(Commit(sha, author, int(ts), changes))
|
|
155
|
+
return commits
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def tracked_files(repo: str, rev: str = "HEAD") -> set[str]:
|
|
159
|
+
out = run_git(["ls-tree", "-r", "--name-only", "-z", rev], repo)
|
|
160
|
+
return {p for p in out.split("\0") if p}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def count_loc(repo_root: str, path: str) -> int:
|
|
164
|
+
try:
|
|
165
|
+
with open(os.path.join(repo_root, path), "rb") as fh:
|
|
166
|
+
data = fh.read(4_000_000)
|
|
167
|
+
except OSError:
|
|
168
|
+
return 0
|
|
169
|
+
if b"\0" in data[:8192]:
|
|
170
|
+
return 0 # binary
|
|
171
|
+
return sum(1 for line in data.splitlines() if line.strip())
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def is_excluded(path: str, patterns: list[str]) -> bool:
|
|
175
|
+
for pat in patterns:
|
|
176
|
+
if pat.endswith("/*"):
|
|
177
|
+
d = pat[:-1]
|
|
178
|
+
if path.startswith(d) or f"/{d}" in f"/{path}":
|
|
179
|
+
return True
|
|
180
|
+
elif fnmatch.fnmatch(path, pat) or fnmatch.fnmatch(os.path.basename(path), pat):
|
|
181
|
+
return True
|
|
182
|
+
return False
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def bus_factor(author_lines: Counter, threshold: float = 0.5) -> int:
|
|
186
|
+
"""Smallest number of authors who together wrote more than `threshold` of the changes."""
|
|
187
|
+
total = sum(author_lines.values())
|
|
188
|
+
if total == 0:
|
|
189
|
+
return 0
|
|
190
|
+
acc = n = 0
|
|
191
|
+
for _, lines in author_lines.most_common():
|
|
192
|
+
acc += lines
|
|
193
|
+
n += 1
|
|
194
|
+
if acc / total > threshold:
|
|
195
|
+
break
|
|
196
|
+
return n
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def directory_of(path: str, depth: int) -> str:
|
|
200
|
+
parts = path.split("/")[:-1]
|
|
201
|
+
return "/".join(parts[:depth]) if parts else "."
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass
|
|
205
|
+
class Report:
|
|
206
|
+
repo: str
|
|
207
|
+
commits: int
|
|
208
|
+
authors: int
|
|
209
|
+
first_ts: int
|
|
210
|
+
last_ts: int
|
|
211
|
+
files: int
|
|
212
|
+
hotspots: list[dict]
|
|
213
|
+
ownership: list[dict]
|
|
214
|
+
coupling: list[dict]
|
|
215
|
+
stale: list[dict]
|
|
216
|
+
orphaned: list[dict]
|
|
217
|
+
contributors: list[dict]
|
|
218
|
+
|
|
219
|
+
def to_dict(self) -> dict:
|
|
220
|
+
return {
|
|
221
|
+
"repo": self.repo,
|
|
222
|
+
"summary": {
|
|
223
|
+
"commits": self.commits, "authors": self.authors, "files": self.files,
|
|
224
|
+
"first_commit": self.first_ts, "last_commit": self.last_ts,
|
|
225
|
+
},
|
|
226
|
+
"hotspots": self.hotspots,
|
|
227
|
+
"ownership": self.ownership,
|
|
228
|
+
"coupling": self.coupling,
|
|
229
|
+
"stale": self.stale,
|
|
230
|
+
"orphaned": self.orphaned,
|
|
231
|
+
"contributors": self.contributors,
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def analyze(repo: str = ".", since: str | None = None, paths: list[str] | None = None,
|
|
236
|
+
excludes: list[str] | None = None, use_default_excludes: bool = True,
|
|
237
|
+
top: int = 10, depth: int = 1, min_coupling: int = 5,
|
|
238
|
+
stale_days: int = 365, include_bots: bool = False,
|
|
239
|
+
now: float | None = None) -> Report:
|
|
240
|
+
root = run_git(["rev-parse", "--show-toplevel"], repo).strip()
|
|
241
|
+
try:
|
|
242
|
+
run_git(["rev-parse", "--verify", "-q", "HEAD"], root)
|
|
243
|
+
except GitError:
|
|
244
|
+
raise GitError("repository has no commits yet") from None
|
|
245
|
+
patterns = (DEFAULT_EXCLUDES if use_default_excludes else []) + list(excludes or [])
|
|
246
|
+
now = time.time() if now is None else now
|
|
247
|
+
|
|
248
|
+
commits = read_log(root, since=since, paths=paths)
|
|
249
|
+
if not include_bots:
|
|
250
|
+
commits = [c for c in commits if not is_bot(c.author)]
|
|
251
|
+
alive = {p for p in tracked_files(root) if not is_excluded(p, patterns)}
|
|
252
|
+
|
|
253
|
+
files: dict[str, FileStats] = {}
|
|
254
|
+
contributor_commits: Counter = Counter()
|
|
255
|
+
contributor_lines: Counter = Counter()
|
|
256
|
+
pair_counts: Counter = Counter()
|
|
257
|
+
|
|
258
|
+
author_last: dict[str, int] = {}
|
|
259
|
+
for c in commits:
|
|
260
|
+
contributor_commits[c.author] += 1
|
|
261
|
+
author_last[c.author] = max(author_last.get(c.author, 0), c.timestamp)
|
|
262
|
+
touched = set()
|
|
263
|
+
for path, added, deleted in c.changes:
|
|
264
|
+
if path not in alive:
|
|
265
|
+
continue
|
|
266
|
+
fs = files.get(path)
|
|
267
|
+
if fs is None:
|
|
268
|
+
fs = files[path] = FileStats(path, first_seen=c.timestamp, last_seen=c.timestamp)
|
|
269
|
+
if path not in touched:
|
|
270
|
+
fs.commits += 1
|
|
271
|
+
fs.added += added
|
|
272
|
+
fs.deleted += deleted
|
|
273
|
+
fs.first_seen = min(fs.first_seen, c.timestamp)
|
|
274
|
+
fs.last_seen = max(fs.last_seen, c.timestamp)
|
|
275
|
+
fs.authors[c.author] += max(added + deleted, 1)
|
|
276
|
+
contributor_lines[c.author] += added + deleted
|
|
277
|
+
touched.add(path)
|
|
278
|
+
if 2 <= len(touched) <= MAX_FILES_FOR_COUPLING:
|
|
279
|
+
for a, b in combinations(sorted(touched), 2):
|
|
280
|
+
pair_counts[(a, b)] += 1
|
|
281
|
+
|
|
282
|
+
for fs in files.values():
|
|
283
|
+
fs.loc = count_loc(root, fs.path)
|
|
284
|
+
|
|
285
|
+
# Hotspots: change frequency x (log) size, both normalised to the repo max.
|
|
286
|
+
max_commits = max((f.commits for f in files.values()), default=1) or 1
|
|
287
|
+
max_loc = max((f.loc for f in files.values()), default=1) or 1
|
|
288
|
+
scored = []
|
|
289
|
+
for f in files.values():
|
|
290
|
+
if f.loc == 0:
|
|
291
|
+
continue
|
|
292
|
+
score = (f.commits / max_commits) * (math.log1p(f.loc) / math.log1p(max_loc))
|
|
293
|
+
author, share = f.main_author
|
|
294
|
+
scored.append({
|
|
295
|
+
"path": f.path, "score": round(score, 4), "commits": f.commits,
|
|
296
|
+
"loc": f.loc, "churn": f.churn, "authors": len(f.authors),
|
|
297
|
+
"main_author": author, "main_author_share": round(share, 3),
|
|
298
|
+
"last_change": f.last_seen,
|
|
299
|
+
})
|
|
300
|
+
scored.sort(key=lambda r: (-r["score"], -r["commits"], r["path"]))
|
|
301
|
+
|
|
302
|
+
# Ownership / bus factor per directory.
|
|
303
|
+
dir_authors: dict[str, Counter] = defaultdict(Counter)
|
|
304
|
+
dir_files: Counter = Counter()
|
|
305
|
+
dir_loc: Counter = Counter()
|
|
306
|
+
for f in files.values():
|
|
307
|
+
d = directory_of(f.path, depth)
|
|
308
|
+
dir_authors[d].update(f.authors)
|
|
309
|
+
dir_files[d] += 1
|
|
310
|
+
dir_loc[d] += f.loc
|
|
311
|
+
ownership = []
|
|
312
|
+
for d, authors in dir_authors.items():
|
|
313
|
+
total = sum(authors.values()) or 1
|
|
314
|
+
main, lines = authors.most_common(1)[0]
|
|
315
|
+
ownership.append({
|
|
316
|
+
"directory": d, "files": dir_files[d], "loc": dir_loc[d],
|
|
317
|
+
"bus_factor": bus_factor(authors), "authors": len(authors),
|
|
318
|
+
"main_author": main, "main_author_share": round(lines / total, 3),
|
|
319
|
+
})
|
|
320
|
+
ownership.sort(key=lambda r: (r["bus_factor"], -r["loc"], r["directory"]))
|
|
321
|
+
|
|
322
|
+
# Temporal coupling: files that keep changing in the same commits.
|
|
323
|
+
coupling = []
|
|
324
|
+
for (a, b), shared in pair_counts.items():
|
|
325
|
+
if shared < min_coupling:
|
|
326
|
+
continue
|
|
327
|
+
degree = shared / ((files[a].commits + files[b].commits) / 2)
|
|
328
|
+
coupling.append({"a": a, "b": b, "shared_commits": shared,
|
|
329
|
+
"degree": round(min(degree, 1.0), 3)})
|
|
330
|
+
coupling.sort(key=lambda r: (-r["degree"], -r["shared_commits"], r["a"], r["b"]))
|
|
331
|
+
|
|
332
|
+
# Stale code: sizeable files nobody has touched in a long time.
|
|
333
|
+
cutoff = now - stale_days * 86400
|
|
334
|
+
stale = [
|
|
335
|
+
{"path": f.path, "loc": f.loc, "last_change": f.last_seen,
|
|
336
|
+
"days": int((now - f.last_seen) // 86400), "main_author": f.main_author[0]}
|
|
337
|
+
for f in files.values() if f.last_seen < cutoff and f.loc > 0
|
|
338
|
+
]
|
|
339
|
+
stale.sort(key=lambda r: (-r["loc"], -r["days"], r["path"]))
|
|
340
|
+
|
|
341
|
+
# Orphaned code: the person who wrote most of it is no longer active.
|
|
342
|
+
orphaned = []
|
|
343
|
+
for f in files.values():
|
|
344
|
+
if f.loc == 0:
|
|
345
|
+
continue
|
|
346
|
+
author, share = f.main_author
|
|
347
|
+
last = author_last.get(author, 0)
|
|
348
|
+
if share >= 0.5 and last < cutoff:
|
|
349
|
+
orphaned.append({
|
|
350
|
+
"path": f.path, "loc": f.loc, "main_author": author,
|
|
351
|
+
"main_author_share": round(share, 3), "author_last_seen": last,
|
|
352
|
+
"author_inactive_days": int((now - last) // 86400),
|
|
353
|
+
})
|
|
354
|
+
orphaned.sort(key=lambda r: (-r["loc"], r["path"]))
|
|
355
|
+
|
|
356
|
+
contributors = [
|
|
357
|
+
{"name": name, "commits": n, "lines": contributor_lines[name]}
|
|
358
|
+
for name, n in contributor_commits.most_common(top)
|
|
359
|
+
]
|
|
360
|
+
|
|
361
|
+
ts = [c.timestamp for c in commits]
|
|
362
|
+
return Report(
|
|
363
|
+
repo=os.path.basename(root), commits=len(commits), authors=len(contributor_commits),
|
|
364
|
+
first_ts=min(ts, default=0), last_ts=max(ts, default=0), files=len(files),
|
|
365
|
+
hotspots=scored[:top], ownership=ownership[:top], coupling=coupling[:top],
|
|
366
|
+
stale=stale[:top], orphaned=orphaned[:top], contributors=contributors,
|
|
367
|
+
)
|
git_xray/cli.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Command line entry point: `git-xray` (also usable as `git xray`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .analysis import GitError, analyze
|
|
11
|
+
from .render import ICON_MODES, detect_icons, render_markdown, render_terminal, use_color
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
15
|
+
ap = argparse.ArgumentParser(
|
|
16
|
+
prog="git-xray",
|
|
17
|
+
description="X-ray a git repository: hotspots, bus factor, hidden coupling, stale code.",
|
|
18
|
+
epilog="Examples:\n"
|
|
19
|
+
" git xray # analyse the current repo\n"
|
|
20
|
+
" git xray --since '6 months ago'\n"
|
|
21
|
+
" git xray src/ --top 20\n"
|
|
22
|
+
" git xray --md > XRAY.md # markdown for PRs / wikis\n"
|
|
23
|
+
" git xray --json | jq .hotspots",
|
|
24
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
25
|
+
)
|
|
26
|
+
ap.add_argument("paths", nargs="*", help="limit analysis to these paths")
|
|
27
|
+
ap.add_argument("-C", dest="repo", default=".", metavar="DIR",
|
|
28
|
+
help="run as if started in DIR (like git -C)")
|
|
29
|
+
ap.add_argument("--since", metavar="WHEN",
|
|
30
|
+
help="only consider commits newer than WHEN, e.g. '1 year ago', 2024-01-01")
|
|
31
|
+
ap.add_argument("-n", "--top", type=int, default=10, help="rows per section (default 10)")
|
|
32
|
+
ap.add_argument("--depth", type=int, default=1,
|
|
33
|
+
help="directory depth for bus-factor grouping (default 1)")
|
|
34
|
+
ap.add_argument("--min-coupling", type=int, default=5, metavar="N",
|
|
35
|
+
help="minimum shared commits to report a coupling (default 5)")
|
|
36
|
+
ap.add_argument("--stale-days", type=int, default=365, metavar="N",
|
|
37
|
+
help="a file is stale after N days without changes (default 365)")
|
|
38
|
+
ap.add_argument("-x", "--exclude", action="append", default=[], metavar="GLOB",
|
|
39
|
+
help="exclude files matching GLOB (repeatable)")
|
|
40
|
+
ap.add_argument("--no-default-excludes", action="store_true",
|
|
41
|
+
help="do not skip lockfiles, vendored and generated files")
|
|
42
|
+
ap.add_argument("--include-bots", action="store_true",
|
|
43
|
+
help="count commits from dependabot, renovate and other bots")
|
|
44
|
+
fmt = ap.add_mutually_exclusive_group()
|
|
45
|
+
fmt.add_argument("--json", action="store_true", help="machine readable output")
|
|
46
|
+
fmt.add_argument("--md", "--markdown", dest="md", action="store_true",
|
|
47
|
+
help="markdown output")
|
|
48
|
+
ap.add_argument("--color", choices=["auto", "always", "never"], default="auto")
|
|
49
|
+
ap.add_argument("--icons", choices=["auto", *ICON_MODES], default="auto",
|
|
50
|
+
help="emoji, plain (no emoji) or ascii. Use plain/ascii if you see "
|
|
51
|
+
"garbled symbols. Also settable via GIT_XRAY_ICONS")
|
|
52
|
+
ap.add_argument("-V", "--version", action="version", version=f"git-xray {__version__}")
|
|
53
|
+
return ap
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv: list[str] | None = None) -> int:
|
|
57
|
+
args = build_parser().parse_args(argv)
|
|
58
|
+
for stream in (sys.stdout, sys.stderr):
|
|
59
|
+
if not hasattr(stream, "reconfigure"):
|
|
60
|
+
continue
|
|
61
|
+
if stream.isatty():
|
|
62
|
+
# Keep the console's own encoding (e.g. GBK); forcing UTF-8 there
|
|
63
|
+
# turns every non-ASCII glyph into mojibake. Never crash, though.
|
|
64
|
+
stream.reconfigure(errors="replace")
|
|
65
|
+
else:
|
|
66
|
+
# Files and pipes: write UTF-8 so --md / --json are portable.
|
|
67
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
68
|
+
try:
|
|
69
|
+
report = analyze(
|
|
70
|
+
args.repo, since=args.since, paths=args.paths or None, excludes=args.exclude,
|
|
71
|
+
use_default_excludes=not args.no_default_excludes, top=args.top,
|
|
72
|
+
depth=args.depth, min_coupling=args.min_coupling, stale_days=args.stale_days,
|
|
73
|
+
include_bots=args.include_bots,
|
|
74
|
+
)
|
|
75
|
+
except GitError as exc:
|
|
76
|
+
print(f"git-xray: {exc}", file=sys.stderr)
|
|
77
|
+
return 2
|
|
78
|
+
if args.json:
|
|
79
|
+
print(json.dumps(report.to_dict(), indent=2, ensure_ascii=False))
|
|
80
|
+
elif args.md:
|
|
81
|
+
print(render_markdown(report))
|
|
82
|
+
else:
|
|
83
|
+
force = {"always": True, "never": False}.get(args.color)
|
|
84
|
+
icons = args.icons if args.icons != "auto" else detect_icons(sys.stdout)
|
|
85
|
+
print(render_terminal(report, color=use_color(sys.stdout, force), icons=icons))
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__": # pragma: no cover
|
|
90
|
+
sys.exit(main())
|
git_xray/render.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""Render a Report as a colourful terminal page or as Markdown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from .analysis import Report
|
|
12
|
+
|
|
13
|
+
RESET = "\x1b[0m"
|
|
14
|
+
BOLD = "\x1b[1m"
|
|
15
|
+
DIM = "\x1b[2m"
|
|
16
|
+
RED = "\x1b[31m"
|
|
17
|
+
GREEN = "\x1b[32m"
|
|
18
|
+
YELLOW = "\x1b[33m"
|
|
19
|
+
BLUE = "\x1b[34m"
|
|
20
|
+
MAGENTA = "\x1b[35m"
|
|
21
|
+
CYAN = "\x1b[36m"
|
|
22
|
+
|
|
23
|
+
BAR_BLOCKS = " ββββββββ"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
ICON_MODES = ("emoji", "plain", "ascii")
|
|
27
|
+
|
|
28
|
+
EMOJI = re.compile("[\U0001F300-\U0001FAFF]\ufe0f? ?")
|
|
29
|
+
|
|
30
|
+
# Unicode glyphs the renderer uses -> ASCII stand-ins of the same width.
|
|
31
|
+
ASCII_MAP = str.maketrans({
|
|
32
|
+
"β": "#", "β": " ", "β": " ", "β": " ", "β": " ", "β": " ", "β": " ", "β": " ",
|
|
33
|
+
"β": "-", "β": "<->", "β ": "!", "β¦": "~", "β": ">", "Β·": "|", "Β±": "+",
|
|
34
|
+
})
|
|
35
|
+
GLYPH_PROBE = "ββββββββββ¦βΒ·Β±" # needed for "plain"; β β are swapped out there
|
|
36
|
+
PLAIN_MAP = str.maketrans({"β": "<->", "β ": "!"})
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
CJK_LANGS = ("ja", "zh", "ko")
|
|
40
|
+
CJK_ENCODINGS = {
|
|
41
|
+
"cp932", "shiftjis", "sjis", "eucjp", "iso2022jp", "cp936", "gbk", "gb2312",
|
|
42
|
+
"gb18030", "big5", "cp950", "big5hkscs", "cp949", "euckr", "johab",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _norm(enc: str) -> str:
|
|
47
|
+
return enc.lower().replace("-", "").replace("_", "")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_cjk_terminal(stream_encoding: str, env, preferred_encoding: str = "") -> bool:
|
|
51
|
+
"""True when the terminal probably draws East-Asian *ambiguous* characters
|
|
52
|
+
(box lines, block bars, arrows, ellipsis...) two columns wide, which wrecks
|
|
53
|
+
column alignment. That is the default in Japanese, Chinese and Korean setups.
|
|
54
|
+
"""
|
|
55
|
+
for var in ("LC_ALL", "LC_CTYPE", "LANG"):
|
|
56
|
+
value = env.get(var)
|
|
57
|
+
if value: # first one set wins, like setlocale()
|
|
58
|
+
if value.lower()[:2] in CJK_LANGS:
|
|
59
|
+
return True
|
|
60
|
+
break
|
|
61
|
+
return any(_norm(e) in CJK_ENCODINGS for e in (stream_encoding, preferred_encoding) if e)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def detect_icons(stream=sys.stdout, env=None, platform: str = sys.platform,
|
|
65
|
+
preferred_encoding: str | None = None) -> str:
|
|
66
|
+
"""Pick the richest glyph set this terminal can show correctly.
|
|
67
|
+
|
|
68
|
+
* ascii: encoding cannot represent the glyphs, or a CJK terminal that draws
|
|
69
|
+
ambiguous-width glyphs double-wide
|
|
70
|
+
* plain: glyphs work but emoji probably do not (legacy Windows console, Linux VT)
|
|
71
|
+
* emoji: everything else
|
|
72
|
+
"""
|
|
73
|
+
env = os.environ if env is None else env
|
|
74
|
+
forced = env.get("GIT_XRAY_ICONS", "").lower()
|
|
75
|
+
if forced in ICON_MODES:
|
|
76
|
+
return forced
|
|
77
|
+
if preferred_encoding is None:
|
|
78
|
+
try:
|
|
79
|
+
import locale
|
|
80
|
+
preferred_encoding = locale.getpreferredencoding(False) or ""
|
|
81
|
+
except Exception: # pragma: no cover
|
|
82
|
+
preferred_encoding = ""
|
|
83
|
+
enc = getattr(stream, "encoding", None) or "ascii"
|
|
84
|
+
if is_cjk_terminal(enc, env, preferred_encoding):
|
|
85
|
+
return "ascii"
|
|
86
|
+
try:
|
|
87
|
+
GLYPH_PROBE.encode(enc)
|
|
88
|
+
except (UnicodeEncodeError, LookupError):
|
|
89
|
+
return "ascii"
|
|
90
|
+
try:
|
|
91
|
+
"π₯".encode(enc)
|
|
92
|
+
except (UnicodeEncodeError, LookupError):
|
|
93
|
+
return "plain"
|
|
94
|
+
if platform == "win32" and not (env.get("WT_SESSION") or env.get("TERM_PROGRAM")):
|
|
95
|
+
return "plain" # conhost / old cmd.exe draws emoji as boxes
|
|
96
|
+
if env.get("TERM") == "linux":
|
|
97
|
+
return "plain" # Linux virtual console
|
|
98
|
+
return "emoji"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def apply_icons(text: str, mode: str) -> str:
|
|
102
|
+
if mode == "emoji":
|
|
103
|
+
return text
|
|
104
|
+
text = EMOJI.sub("", text).translate(PLAIN_MAP)
|
|
105
|
+
if mode == "ascii":
|
|
106
|
+
text = text.translate(ASCII_MAP)
|
|
107
|
+
return text
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def use_color(stream=sys.stdout, force: bool | None = None) -> bool:
|
|
111
|
+
if force is not None:
|
|
112
|
+
return force
|
|
113
|
+
if os.environ.get("NO_COLOR"):
|
|
114
|
+
return False
|
|
115
|
+
if os.environ.get("FORCE_COLOR"):
|
|
116
|
+
return True
|
|
117
|
+
return hasattr(stream, "isatty") and stream.isatty()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Painter:
|
|
121
|
+
def __init__(self, enabled: bool):
|
|
122
|
+
self.enabled = enabled
|
|
123
|
+
|
|
124
|
+
def __call__(self, text: str, *styles: str) -> str:
|
|
125
|
+
if not self.enabled or not styles:
|
|
126
|
+
return text
|
|
127
|
+
return "".join(styles) + text + RESET
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def bar(fraction: float, width: int) -> str:
|
|
131
|
+
fraction = max(0.0, min(1.0, fraction))
|
|
132
|
+
total = fraction * width
|
|
133
|
+
full = int(total)
|
|
134
|
+
rest = int((total - full) * 8)
|
|
135
|
+
out = "β" * full
|
|
136
|
+
if full < width and rest:
|
|
137
|
+
out += BAR_BLOCKS[rest]
|
|
138
|
+
return out.ljust(width)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def heat_color(fraction: float) -> str:
|
|
142
|
+
if fraction >= 0.66:
|
|
143
|
+
return RED
|
|
144
|
+
if fraction >= 0.33:
|
|
145
|
+
return YELLOW
|
|
146
|
+
return GREEN
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def ago(ts: int, now: float) -> str:
|
|
150
|
+
days = int((now - ts) // 86400)
|
|
151
|
+
if days < 1:
|
|
152
|
+
return "today"
|
|
153
|
+
if days < 60:
|
|
154
|
+
return f"{days}d ago"
|
|
155
|
+
if days < 730:
|
|
156
|
+
return f"{days // 30}mo ago"
|
|
157
|
+
return f"{days // 365}y ago"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def shorten(path: str, width: int) -> str:
|
|
161
|
+
if len(path) <= width:
|
|
162
|
+
return path
|
|
163
|
+
keep = width - 1
|
|
164
|
+
return "β¦" + path[-keep:]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def human(n: int) -> str:
|
|
168
|
+
if n >= 1_000_000:
|
|
169
|
+
return f"{n / 1_000_000:.1f}M"
|
|
170
|
+
if n >= 10_000:
|
|
171
|
+
return f"{n / 1000:.0f}k"
|
|
172
|
+
if n >= 1000:
|
|
173
|
+
return f"{n / 1000:.1f}k"
|
|
174
|
+
return str(n)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def render_terminal(report: Report, color: bool = True, width: int | None = None,
|
|
178
|
+
now: float | None = None, icons: str = "emoji") -> str:
|
|
179
|
+
p = Painter(color)
|
|
180
|
+
now = time.time() if now is None else now
|
|
181
|
+
width = width or min(shutil.get_terminal_size((100, 24)).columns, 120)
|
|
182
|
+
path_w = max(24, width - 52)
|
|
183
|
+
lines: list[str] = []
|
|
184
|
+
add = lines.append
|
|
185
|
+
|
|
186
|
+
def header(icon: str, title: str, hint: str) -> None:
|
|
187
|
+
add("")
|
|
188
|
+
add(p(f"{icon} {title}", BOLD) + " " + p(hint, DIM))
|
|
189
|
+
add(p("β" * min(width, 100), DIM))
|
|
190
|
+
|
|
191
|
+
span = ""
|
|
192
|
+
if report.first_ts:
|
|
193
|
+
span = f"{time.strftime('%Y-%m-%d', time.localtime(report.first_ts))} β " \
|
|
194
|
+
f"{time.strftime('%Y-%m-%d', time.localtime(report.last_ts))}"
|
|
195
|
+
add("")
|
|
196
|
+
add(p(" git-xray ", BOLD, "\x1b[7m") + " " + p(report.repo, BOLD, CYAN))
|
|
197
|
+
add(p(f"{report.commits} commits Β· {report.authors} authors Β· "
|
|
198
|
+
f"{report.files} files Β· {span}", DIM))
|
|
199
|
+
|
|
200
|
+
# Hotspots
|
|
201
|
+
header("π₯", "Hotspots", "files that change often AND are big. Refactor these first.")
|
|
202
|
+
if not report.hotspots:
|
|
203
|
+
add(p(" no history to analyse", DIM))
|
|
204
|
+
for i, h in enumerate(report.hotspots, 1):
|
|
205
|
+
frac = h["score"]
|
|
206
|
+
rank = p("%2d" % i, DIM)
|
|
207
|
+
heat = p(bar(frac, 10), heat_color(frac))
|
|
208
|
+
name = shorten(h["path"], path_w).ljust(path_w)
|
|
209
|
+
commits = p("%4d commits" % h["commits"], BOLD)
|
|
210
|
+
loc = p("%6s loc" % human(h["loc"]), DIM)
|
|
211
|
+
authors = p("%2d authors" % h["authors"], DIM)
|
|
212
|
+
add(" ".join([rank, heat, name, commits, loc, authors]))
|
|
213
|
+
|
|
214
|
+
# Ownership
|
|
215
|
+
header("π", "Bus factor", "how many people must leave before nobody knows this code.")
|
|
216
|
+
for o in report.ownership:
|
|
217
|
+
bf = o["bus_factor"]
|
|
218
|
+
style = RED if bf <= 1 else YELLOW if bf == 2 else GREEN
|
|
219
|
+
share = o["main_author_share"]
|
|
220
|
+
warn = p(" β ", RED, BOLD) if bf <= 1 and o["authors"] > 1 else " "
|
|
221
|
+
name = shorten(o["directory"] + "/", path_w).ljust(path_w)
|
|
222
|
+
add(" " + p("bus=%d" % bf, style, BOLD) + warn + " " + name + " "
|
|
223
|
+
+ p(bar(share, 8), style) + " %4.0f%% " % (share * 100)
|
|
224
|
+
+ p(o["main_author"], MAGENTA))
|
|
225
|
+
|
|
226
|
+
# Coupling
|
|
227
|
+
header("π", "Hidden coupling", "files that always change together. Missing abstraction?")
|
|
228
|
+
if not report.coupling:
|
|
229
|
+
add(p(" nothing above threshold (use --min-coupling to lower it)", DIM))
|
|
230
|
+
half = max(16, (path_w + 10) // 2)
|
|
231
|
+
for c in report.coupling:
|
|
232
|
+
degree = p("%3.0f%%" % (c["degree"] * 100), BOLD, heat_color(c["degree"]))
|
|
233
|
+
add(" " + degree + " " + shorten(c["a"], half) + " " + p("β", CYAN) + " "
|
|
234
|
+
+ shorten(c["b"], half) + " " + p("(%d commits)" % c["shared_commits"], DIM))
|
|
235
|
+
|
|
236
|
+
# Stale
|
|
237
|
+
header("π§", "Stale code", "big files nobody has touched in a long time.")
|
|
238
|
+
if not report.stale:
|
|
239
|
+
add(p(" nothing stale. Everything was touched recently.", DIM))
|
|
240
|
+
for s in report.stale:
|
|
241
|
+
when = p("%8s" % ago(s["last_change"], now), BLUE)
|
|
242
|
+
name = shorten(s["path"], path_w).ljust(path_w)
|
|
243
|
+
add(" " + when + " " + name + " " + p("%6s loc" % human(s["loc"]), DIM) + " "
|
|
244
|
+
+ p(s["main_author"], MAGENTA))
|
|
245
|
+
|
|
246
|
+
# Orphaned
|
|
247
|
+
header("π»", "Orphaned code", "main author has gone quiet. Knowledge may have left with them.")
|
|
248
|
+
if not report.orphaned:
|
|
249
|
+
add(p(" no orphaned files. Main authors are still around.", DIM))
|
|
250
|
+
for o in report.orphaned:
|
|
251
|
+
gone = p("%8s" % ("%dd" % o["author_inactive_days"] if o["author_inactive_days"] < 730
|
|
252
|
+
else "%dy" % (o["author_inactive_days"] // 365)), BLUE)
|
|
253
|
+
name = shorten(o["path"], path_w).ljust(path_w)
|
|
254
|
+
add(" " + gone + " " + name + " " + p("%6s loc" % human(o["loc"]), DIM) + " "
|
|
255
|
+
+ p(o["main_author"], MAGENTA) + p(" (%d%%)" % round(o["main_author_share"] * 100), DIM))
|
|
256
|
+
|
|
257
|
+
# Contributors
|
|
258
|
+
header("π₯", "Top contributors", "by commits in the analysed range.")
|
|
259
|
+
max_c = max((c["commits"] for c in report.contributors), default=1) or 1
|
|
260
|
+
for c in report.contributors:
|
|
261
|
+
add(" " + p(bar(c["commits"] / max_c, 16), CYAN) + " %5d " % c["commits"]
|
|
262
|
+
+ c["name"] + " " + p("(Β±%s lines)" % human(c["lines"]), DIM))
|
|
263
|
+
add("")
|
|
264
|
+
return apply_icons("\n".join(lines), icons)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def render_markdown(report: Report, now: float | None = None) -> str:
|
|
268
|
+
now = time.time() if now is None else now
|
|
269
|
+
out = [f"# git-xray report: `{report.repo}`", "",
|
|
270
|
+
f"{report.commits} commits Β· {report.authors} authors Β· {report.files} files", ""]
|
|
271
|
+
|
|
272
|
+
out += ["## π₯ Hotspots", "", "| # | File | Score | Commits | LOC | Authors |",
|
|
273
|
+
"|---|------|-------|---------|-----|---------|"]
|
|
274
|
+
for i, h in enumerate(report.hotspots, 1):
|
|
275
|
+
out.append(f"| {i} | `{h['path']}` | {h['score']:.2f} | {h['commits']} | "
|
|
276
|
+
f"{h['loc']} | {h['authors']} |")
|
|
277
|
+
|
|
278
|
+
out += ["", "## π Bus factor", "", "| Directory | Bus factor | Main author | Share |",
|
|
279
|
+
"|-----------|------------|-------------|-------|"]
|
|
280
|
+
for o in report.ownership:
|
|
281
|
+
out.append(f"| `{o['directory']}/` | {o['bus_factor']} | {o['main_author']} | "
|
|
282
|
+
f"{o['main_author_share']:.0%} |")
|
|
283
|
+
|
|
284
|
+
out += ["", "## π Hidden coupling", ""]
|
|
285
|
+
if report.coupling:
|
|
286
|
+
out += ["| File A | File B | Degree | Shared commits |",
|
|
287
|
+
"|--------|--------|--------|----------------|"]
|
|
288
|
+
for c in report.coupling:
|
|
289
|
+
out.append(f"| `{c['a']}` | `{c['b']}` | {c['degree']:.0%} | {c['shared_commits']} |")
|
|
290
|
+
else:
|
|
291
|
+
out.append("_Nothing above threshold._")
|
|
292
|
+
|
|
293
|
+
out += ["", "## π§ Stale code", ""]
|
|
294
|
+
if report.stale:
|
|
295
|
+
out += ["| File | LOC | Last change | Main author |", "|------|-----|-------------|-------------|"]
|
|
296
|
+
for s in report.stale:
|
|
297
|
+
out.append(f"| `{s['path']}` | {s['loc']} | {ago(s['last_change'], now)} | "
|
|
298
|
+
f"{s['main_author']} |")
|
|
299
|
+
else:
|
|
300
|
+
out.append("_Nothing stale._")
|
|
301
|
+
|
|
302
|
+
out += ["", "## π» Orphaned code", ""]
|
|
303
|
+
if report.orphaned:
|
|
304
|
+
out += ["| File | LOC | Main author | Share | Author last seen |",
|
|
305
|
+
"|------|-----|-------------|-------|------------------|"]
|
|
306
|
+
for o in report.orphaned:
|
|
307
|
+
out.append(f"| `{o['path']}` | {o['loc']} | {o['main_author']} | "
|
|
308
|
+
f"{o['main_author_share']:.0%} | {ago(o['author_last_seen'], now)} |")
|
|
309
|
+
else:
|
|
310
|
+
out.append("_No orphaned files._")
|
|
311
|
+
out.append("")
|
|
312
|
+
return "\n".join(out)
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: git-xray-tool
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: X-ray any git repo in one command: hotspots, bus factor, hidden coupling, stale code. Zero dependencies.
|
|
5
|
+
Project-URL: Homepage, https://github.com/ckh0at/git-xray
|
|
6
|
+
Project-URL: Source, https://github.com/ckh0at/git-xray
|
|
7
|
+
Project-URL: Issues, https://github.com/ckh0at/git-xray/issues
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: bus-factor,cli,code-analysis,code-quality,git,hotspots,technical-debt
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
15
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
<div align="center">
|
|
20
|
+
|
|
21
|
+
# git-xray π©»
|
|
22
|
+
|
|
23
|
+
**X-ray any git repository in one command.**
|
|
24
|
+
Find the code that hurts: hotspots, bus factor, hidden coupling, stale and orphaned files.
|
|
25
|
+
|
|
26
|
+
[](https://pypi.org/project/git-xray-tool/)
|
|
27
|
+
[](https://pypi.org/project/git-xray-tool/)
|
|
28
|
+
[](LICENSE)
|
|
29
|
+
|
|
30
|
+
<img src="https://raw.githubusercontent.com/ckh0at/git-xray/main/docs/demo.svg" alt="git-xray running on the Flask repository" width="820">
|
|
31
|
+
|
|
32
|
+
</div>
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pipx install git-xray-tool # or: pip install git-xray-tool
|
|
36
|
+
# one-off run: uvx --from git-xray-tool git-xray
|
|
37
|
+
cd your-repo
|
|
38
|
+
git xray
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The package is called `git-xray-tool` on PyPI; the command is `git-xray`, or just
|
|
42
|
+
`git xray`. No config, no server, no dependencies. Pure Python and `git`. It analyses Flask's
|
|
43
|
+
3,800 commits in **under a second**.
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Why?
|
|
48
|
+
|
|
49
|
+
Your git history already knows where the problems are. The files that change
|
|
50
|
+
all the time *and* are large are where bugs pile up and velocity goes to die.
|
|
51
|
+
Directories that only one person understands are a risk. Files that always change
|
|
52
|
+
together hint at a missing abstraction.
|
|
53
|
+
|
|
54
|
+
Tools like [code-maat](https://github.com/adamtornhill/code-maat) pioneered this
|
|
55
|
+
analysis (see *Your Code as a Crime Scene*), but they need a JVM, a log export
|
|
56
|
+
step and a spreadsheet. `git-xray` gives you the answers in one command.
|
|
57
|
+
|
|
58
|
+
## What it shows
|
|
59
|
+
|
|
60
|
+
| Section | Question it answers |
|
|
61
|
+
|---|---|
|
|
62
|
+
| π₯ **Hotspots** | Which files change most often *and* are big? Your best refactoring targets. |
|
|
63
|
+
| π **Bus factor** | How many people would have to leave before nobody knows a directory? |
|
|
64
|
+
| π **Hidden coupling** | Which files keep changing in the same commits, even though nothing says they're related? |
|
|
65
|
+
| π§ **Stale code** | Which big files has nobody touched in a year? |
|
|
66
|
+
| π» **Orphaned code** | Which files were mostly written by someone who is no longer active? |
|
|
67
|
+
| π₯ **Contributors** | Who did the work in this time range? |
|
|
68
|
+
|
|
69
|
+
## Usage
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
git xray # whole history of the current repo
|
|
73
|
+
git xray --since "6 months ago" # recent activity only
|
|
74
|
+
git xray src/ lib/ # limit to some paths
|
|
75
|
+
git xray -n 25 # show 25 rows per section
|
|
76
|
+
git xray --depth 2 # bus factor per src/foo instead of src/
|
|
77
|
+
git xray -x "*.generated.ts" # extra excludes (repeatable)
|
|
78
|
+
git xray -C ~/code/other-repo # analyse another repo
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Output formats
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
git xray --md > XRAY.md # Markdown: paste into a PR, wiki or issue
|
|
85
|
+
git xray --json | jq '.hotspots' # JSON: build your own dashboards or CI checks
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
<details>
|
|
89
|
+
<summary>All options</summary>
|
|
90
|
+
|
|
91
|
+
```text
|
|
92
|
+
usage: git-xray [-h] [-C DIR] [--since WHEN] [-n TOP] [--depth DEPTH]
|
|
93
|
+
[--min-coupling N] [--stale-days N] [-x GLOB]
|
|
94
|
+
[--no-default-excludes] [--include-bots] [--json | --md]
|
|
95
|
+
[--color {auto,always,never}] [-V]
|
|
96
|
+
[paths ...]
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
| Option | Default | Meaning |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `--since WHEN` | all history | Only commits newer than `WHEN` (anything `git log --since` accepts) |
|
|
102
|
+
| `-n, --top` | 10 | Rows per section |
|
|
103
|
+
| `--depth` | 1 | Directory depth used for bus-factor grouping |
|
|
104
|
+
| `--min-coupling` | 5 | Minimum shared commits before a pair is reported |
|
|
105
|
+
| `--stale-days` | 365 | Days without change before a file counts as stale / an author as inactive |
|
|
106
|
+
| `-x, --exclude` | | Glob to skip, repeatable |
|
|
107
|
+
| `--no-default-excludes` | | Keep lockfiles, `vendor/`, `dist/`, changelogs, minified files⦠|
|
|
108
|
+
| `--include-bots` | | Count dependabot, renovate and other bots |
|
|
109
|
+
| `--color` | auto | Respects `NO_COLOR` and `FORCE_COLOR` |
|
|
110
|
+
| `--icons` | auto | `emoji`, `plain` (no emoji) or `ascii`. Also `GIT_XRAY_ICONS` |
|
|
111
|
+
|
|
112
|
+
</details>
|
|
113
|
+
|
|
114
|
+
## How the numbers are computed
|
|
115
|
+
|
|
116
|
+
- **Hotspot score** = `commits / max_commits Γ log(loc) / log(max_loc)`. Change frequency
|
|
117
|
+
matters most; size is log-scaled so one giant file does not drown out everything else.
|
|
118
|
+
- **Bus factor** = the smallest number of authors who together wrote more than 50% of the
|
|
119
|
+
changed lines in a directory.
|
|
120
|
+
- **Coupling degree** = `shared_commits / average(commits of A, commits of B)`. Commits
|
|
121
|
+
touching more than 30 files (mass renames, formatting) are ignored.
|
|
122
|
+
- **Orphaned** = the main author wrote at least 50% of the file and has made no commit in
|
|
123
|
+
`--stale-days`.
|
|
124
|
+
- Renames are followed (`git log -M`), so history survives `git mv`. Merge commits are skipped.
|
|
125
|
+
Author identities respect your `.mailmap`.
|
|
126
|
+
|
|
127
|
+
These are heuristics, not verdicts. A hotspot can be a healthy, central module; the
|
|
128
|
+
point is to know *where to look*.
|
|
129
|
+
|
|
130
|
+
## FAQ
|
|
131
|
+
|
|
132
|
+
**Is it fast on big repos?** It runs `git log` once and parses it in a single pass.
|
|
133
|
+
Most repos take a second or two. On huge monorepos, narrow it down with `--since` or a path.
|
|
134
|
+
|
|
135
|
+
**Does it send my code anywhere?** No. It runs `git` locally and prints to your terminal.
|
|
136
|
+
|
|
137
|
+
**I see boxes, garbled symbols or broken columns.** git-xray picks a glyph set
|
|
138
|
+
from your terminal. In Japanese, Chinese and Korean locales it uses plain ASCII,
|
|
139
|
+
because those terminals draw box and block characters double-wide. Some other
|
|
140
|
+
terminals still can't draw emoji. Use
|
|
141
|
+
`git xray --icons plain` (no emoji) or `--icons ascii`, or set it once with
|
|
142
|
+
`export GIT_XRAY_ICONS=plain` (PowerShell: `$env:GIT_XRAY_ICONS="plain"`).
|
|
143
|
+
|
|
144
|
+
**Why `git xray` and not `git-xray`?** Both work. git treats any `git-<name>`
|
|
145
|
+
executable on your `PATH` as a subcommand.
|
|
146
|
+
|
|
147
|
+
## Contributing
|
|
148
|
+
|
|
149
|
+
Issues and PRs are welcome! Ideas we would love help with:
|
|
150
|
+
an HTML report, `--fail-on` thresholds for CI, and per-author knowledge maps.
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
git clone https://github.com/ckh0at/git-xray && cd git-xray
|
|
154
|
+
python -m venv .venv && .venv/bin/pip install -e . pytest
|
|
155
|
+
.venv/bin/pytest
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
git_xray/__init__.py,sha256=CRQjCt7gZHxGnYQjH4uGnOaIAIRwSd1TVQN_etXAbtc,94
|
|
2
|
+
git_xray/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
git_xray/analysis.py,sha256=1lGTpALO9OwGz3Ho6L06731J93vECfL1IqE4-qOWE-4,12887
|
|
4
|
+
git_xray/cli.py,sha256=bSbmXdwUIWfuI_heRMjxNyAYTW3eZvh4zZG8Ym2-QL8,4447
|
|
5
|
+
git_xray/render.py,sha256=K6f8iP9G7xnjbeRDvT8VpfV2hZBouRl4dUnVHKhRgh8,11727
|
|
6
|
+
git_xray_tool-0.1.0.dist-info/METADATA,sha256=j8K8foIE9yhg50v01fBZlXkQLofJp2l_TjS_FOiPtg8,6745
|
|
7
|
+
git_xray_tool-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
git_xray_tool-0.1.0.dist-info/entry_points.txt,sha256=gglMBJow3Vu8Hr4aHFiuArxeCp0RPQKBihTFohNvbCo,47
|
|
9
|
+
git_xray_tool-0.1.0.dist-info/licenses/LICENSE,sha256=6xr53dVny5qEpzL8ZM5csr1fD4AFrQfnX7OyCcnIliE,1063
|
|
10
|
+
git_xray_tool-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ckh0at
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|