gitsaga 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.
- gitsaga/__init__.py +1 -0
- gitsaga/__main__.py +5 -0
- gitsaga/cli.py +97 -0
- gitsaga/export.py +80 -0
- gitsaga/history.py +160 -0
- gitsaga/langs.py +37 -0
- gitsaga/milestones.py +207 -0
- gitsaga/model.py +246 -0
- gitsaga/ownership.py +103 -0
- gitsaga/render.py +17 -0
- gitsaga/web/player.html +151 -0
- gitsaga-0.1.0.dist-info/METADATA +141 -0
- gitsaga-0.1.0.dist-info/RECORD +16 -0
- gitsaga-0.1.0.dist-info/WHEEL +4 -0
- gitsaga-0.1.0.dist-info/entry_points.txt +2 -0
- gitsaga-0.1.0.dist-info/licenses/LICENSE +21 -0
gitsaga/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
gitsaga/__main__.py
ADDED
gitsaga/cli.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""gitsaga [REPO] -o story.html [--gif story.gif] [--mp4 story.mp4]"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
import webbrowser
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .export import ExportError, export_gif, export_mp4
|
|
12
|
+
from .history import GitError, git, read_commits, read_tags, repo_name
|
|
13
|
+
from .model import Options, build_story
|
|
14
|
+
from .render import player_html
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _err(msg: str) -> None:
|
|
18
|
+
print(msg, file=sys.stderr, flush=True)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
22
|
+
p = argparse.ArgumentParser(prog="gitsaga", description="The story of your repo in 60 seconds: an animated, narrated timeline of its git history.")
|
|
23
|
+
p.add_argument("repo", nargs="?", default=".", help="path to a git repository (default: .)")
|
|
24
|
+
p.add_argument("-o", "--output", default="story.html", help="HTML player to write (default: story.html)")
|
|
25
|
+
p.add_argument("--open", action="store_true", help="open the result in a browser")
|
|
26
|
+
p.add_argument("--gif", metavar="FILE", help="also render a GIF (needs: pip install 'gitsaga[video]' && playwright install chromium)")
|
|
27
|
+
p.add_argument("--mp4", metavar="FILE", help="also render an MP4 (needs the video extra and ffmpeg)")
|
|
28
|
+
p.add_argument("--theme", choices=("dark", "light"), default="dark", help="colour theme of the player and exports (default dark)")
|
|
29
|
+
p.add_argument("--view", choices=("language", "ownership"), default="language", help="what the player opens with: language colours, or who owns which code (bus factor, orphaned areas)")
|
|
30
|
+
p.add_argument("--duration", type=float, help="length in seconds, captions included (default 60; 30 for --gif)")
|
|
31
|
+
p.add_argument("--milestones", type=int, default=12, metavar="N", help="captions to show (default 12)")
|
|
32
|
+
p.add_argument("--title", help="name shown in the player (default: the repository folder)")
|
|
33
|
+
p.add_argument("--rev", default="HEAD", help="branch, tag or commit to tell the story of (default HEAD)")
|
|
34
|
+
p.add_argument("--since", metavar="DATE", help="only history since this date, e.g. 2024-01-01 or '1 year ago'")
|
|
35
|
+
p.add_argument("--depth", type=int, default=3, help="directory depth shown (default 3)")
|
|
36
|
+
p.add_argument("--max-dirs", type=int, default=110, help="most directories drawn (default 110)")
|
|
37
|
+
p.add_argument("--max-commits", type=int, default=200_000, help="safety limit on commits read")
|
|
38
|
+
p.add_argument("--include-bots", action="store_true", help="keep commits by bots (dependabot, renovate, ...)")
|
|
39
|
+
p.add_argument("--include-vendor", action="store_true", help="keep lock files, vendored and generated files")
|
|
40
|
+
p.add_argument("--width", type=int, help="GIF/MP4 width in pixels (default 800 for GIF, 1280 for MP4)")
|
|
41
|
+
p.add_argument("--height", type=int, help="GIF/MP4 height in pixels (default 450 for GIF, 720 for MP4)")
|
|
42
|
+
p.add_argument("--fps", type=int, help="GIF/MP4 frames per second (default 10 for GIF, 30 for MP4)")
|
|
43
|
+
p.add_argument("--list", action="store_true", help="print the detected milestones instead of writing files")
|
|
44
|
+
p.add_argument("-q", "--quiet", action="store_true")
|
|
45
|
+
p.add_argument("-V", "--version", action="version", version=f"gitsaga {__version__}")
|
|
46
|
+
return p
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def main(argv: list[str] | None = None) -> int:
|
|
50
|
+
a = build_parser().parse_args(argv)
|
|
51
|
+
say = (lambda *_: None) if a.quiet else _err
|
|
52
|
+
try:
|
|
53
|
+
commits = read_commits(a.repo, a.rev, a.include_bots, a.include_vendor, a.max_commits, a.since)
|
|
54
|
+
tags = read_tags(a.repo)
|
|
55
|
+
name = a.title or repo_name(a.repo)
|
|
56
|
+
shallow = git(a.repo, "rev-parse", "--is-shallow-repository").strip() == "true"
|
|
57
|
+
except GitError as e:
|
|
58
|
+
_err(f"gitsaga: {e}")
|
|
59
|
+
return 2
|
|
60
|
+
if not commits:
|
|
61
|
+
_err("gitsaga: no commits found (empty repository, or everything was filtered out)")
|
|
62
|
+
return 2
|
|
63
|
+
if shallow:
|
|
64
|
+
say("gitsaga: this is a shallow clone, so the story starts at its oldest available commit. Run `git fetch --unshallow` for the full history.")
|
|
65
|
+
duration = a.duration or (30.0 if a.gif and not a.mp4 else 60.0) # a GIF that is too long gets huge
|
|
66
|
+
story = build_story(commits, tags, name, Options(depth=a.depth, max_dirs=a.max_dirs, duration=duration, milestones=a.milestones, view=a.view))
|
|
67
|
+
if a.list:
|
|
68
|
+
for m in story["milestones"]:
|
|
69
|
+
print(f"{m['s']:>4} {m['k']:<12} {m['title']} | {m['detail']}")
|
|
70
|
+
return 0
|
|
71
|
+
html = player_html(story, a.theme)
|
|
72
|
+
out = Path(a.output)
|
|
73
|
+
out.write_text(html, encoding="utf-8")
|
|
74
|
+
meta = story["meta"]
|
|
75
|
+
say(f"gitsaga: {meta['commits']:,} commits, {meta['authors']:,} contributors, {len(story['milestones'])} milestones -> {out} ({len(html) // 1024} KB)")
|
|
76
|
+
|
|
77
|
+
def progress(k: int, n: int) -> None:
|
|
78
|
+
if not a.quiet and (k == n or k % 25 == 0):
|
|
79
|
+
print(f"\r rendering frames {k}/{n}", end="" if k < n else "\n", file=sys.stderr, flush=True)
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
if a.gif:
|
|
83
|
+
size = export_gif(html, a.gif, a.width or 800, a.height or 450, a.fps or 10, progress)
|
|
84
|
+
say(f"gitsaga: wrote {a.gif} ({size / 1e6:.1f} MB)" + (" (large: try --duration 20 or --width 640)" if size > 10e6 else ""))
|
|
85
|
+
if a.mp4:
|
|
86
|
+
size = export_mp4(html, a.mp4, a.width or 1280, a.height or 720, a.fps or 30, progress)
|
|
87
|
+
say(f"gitsaga: wrote {a.mp4} ({size / 1e6:.1f} MB)")
|
|
88
|
+
except ExportError as e:
|
|
89
|
+
_err(f"gitsaga: {e}")
|
|
90
|
+
return 3
|
|
91
|
+
if a.open:
|
|
92
|
+
webbrowser.open(out.resolve().as_uri())
|
|
93
|
+
return 0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
if __name__ == "__main__":
|
|
97
|
+
sys.exit(main())
|
gitsaga/export.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""GIF / MP4 export: step the HTML player frame by frame in headless Chromium (needs the `video` extra)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import tempfile
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
HINT = "GIF/MP4 export needs the video extra and a browser: pip install 'gitsaga[video]' && playwright install chromium"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ExportError(RuntimeError):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _frames(html: str, width: int, height: int, fps: int, progress: Callable[[int, int], None] | None) -> list[bytes]:
|
|
20
|
+
try:
|
|
21
|
+
from playwright.sync_api import sync_playwright
|
|
22
|
+
except ImportError as e:
|
|
23
|
+
raise ExportError(HINT) from e
|
|
24
|
+
out: list[bytes] = []
|
|
25
|
+
with tempfile.TemporaryDirectory() as tmp, sync_playwright() as pw:
|
|
26
|
+
page_path = Path(tmp) / "story.html"
|
|
27
|
+
page_path.write_text(html, encoding="utf-8")
|
|
28
|
+
try:
|
|
29
|
+
browser = pw.chromium.launch()
|
|
30
|
+
except Exception as e:
|
|
31
|
+
raise ExportError(f"could not start Chromium ({str(e).splitlines()[0]}). {HINT}") from e
|
|
32
|
+
page = browser.new_page(viewport={"width": width, "height": height})
|
|
33
|
+
page.goto(page_path.as_uri() + "?export=1")
|
|
34
|
+
page.wait_for_function("window.__gitsaga && window.__gitsaga.ready")
|
|
35
|
+
total_ms = page.evaluate("__gitsaga.total")
|
|
36
|
+
count = max(2, int(total_ms / 1000 * fps) + 1)
|
|
37
|
+
for k in range(count):
|
|
38
|
+
page.evaluate(f"__gitsaga.seek({min(total_ms, k * 1000 / fps)})")
|
|
39
|
+
out.append(page.screenshot(type="png"))
|
|
40
|
+
if progress:
|
|
41
|
+
progress(k + 1, count)
|
|
42
|
+
browser.close()
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def export_gif(html: str, path: str, width: int = 800, height: int = 450, fps: int = 10,
|
|
47
|
+
progress: Callable[[int, int], None] | None = None) -> int:
|
|
48
|
+
try:
|
|
49
|
+
from PIL import Image
|
|
50
|
+
except ImportError as e:
|
|
51
|
+
raise ExportError(HINT) from e
|
|
52
|
+
frames = [Image.open(io.BytesIO(b)).convert("RGB") for b in _frames(html, width, height, fps, progress)]
|
|
53
|
+
# one shared palette built from a sample of frames: smaller files and no colour flicker between frames
|
|
54
|
+
sample = frames[:: max(1, len(frames) // 24)]
|
|
55
|
+
sheet = Image.new("RGB", (width, height * len(sample)))
|
|
56
|
+
for k, im in enumerate(sample):
|
|
57
|
+
sheet.paste(im, (0, k * height))
|
|
58
|
+
pal = sheet.quantize(colors=128, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
|
|
59
|
+
q = [im.quantize(palette=pal, dither=Image.Dither.NONE) for im in frames]
|
|
60
|
+
q[0].save(path, save_all=True, append_images=q[1:], duration=round(1000 / fps), loop=0, optimize=True)
|
|
61
|
+
return Path(path).stat().st_size
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def export_mp4(html: str, path: str, width: int = 1280, height: int = 720, fps: int = 30,
|
|
65
|
+
progress: Callable[[int, int], None] | None = None) -> int:
|
|
66
|
+
ff = shutil.which("ffmpeg")
|
|
67
|
+
if not ff:
|
|
68
|
+
raise ExportError("MP4 export needs ffmpeg on your PATH (https://ffmpeg.org/download.html)")
|
|
69
|
+
width, height = width - width % 2, height - height % 2 # h264 wants even sizes
|
|
70
|
+
frames = _frames(html, width, height, fps, progress)
|
|
71
|
+
p = subprocess.Popen([ff, "-y", "-loglevel", "error", "-f", "image2pipe", "-framerate", str(fps), "-i", "-", "-pix_fmt", "yuv420p",
|
|
72
|
+
"-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-movflags", "+faststart", path],
|
|
73
|
+
stdin=subprocess.PIPE)
|
|
74
|
+
assert p.stdin
|
|
75
|
+
for b in frames:
|
|
76
|
+
p.stdin.write(b)
|
|
77
|
+
p.stdin.close()
|
|
78
|
+
if p.wait() != 0:
|
|
79
|
+
raise ExportError("ffmpeg failed to encode the video")
|
|
80
|
+
return Path(path).stat().st_size
|
gitsaga/history.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Read a git history: commits with per-file changes, release tags, bot filtering and noise filtering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import PurePosixPath
|
|
10
|
+
|
|
11
|
+
RS, US = "\x1e", "\x1f"
|
|
12
|
+
FORMAT = f"{RS}%H{US}%at{US}%aN{US}%aE{US}%s"
|
|
13
|
+
|
|
14
|
+
BOT_RE = re.compile(r"\[bot\]|dependabot|renovate|github-actions|greenkeeper|snyk-bot|pre-commit-ci|allcontributors", re.IGNORECASE)
|
|
15
|
+
NOISE_NAMES = {
|
|
16
|
+
"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "npm-shrinkwrap.json", "cargo.lock", "poetry.lock", "uv.lock",
|
|
17
|
+
"pipfile.lock", "go.sum", "composer.lock", "gemfile.lock", "gradle.lockfile", "bun.lockb", "pubspec.lock",
|
|
18
|
+
}
|
|
19
|
+
NOISE_PARTS = ("node_modules", "vendor", "third_party", "third-party", "site-packages", "__pycache__", ".yarn", "dist", "build")
|
|
20
|
+
NOISE_SUFFIXES = (".min.js", ".min.css", ".map", ".lock", ".svg.map", ".snap", ".pb.go", "_pb2.py")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GitError(RuntimeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Change:
|
|
29
|
+
path: str
|
|
30
|
+
status: str # A M D R C T
|
|
31
|
+
added: int = 0
|
|
32
|
+
deleted: int = 0
|
|
33
|
+
old: str | None = None # source path for renames / copies
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Commit:
|
|
38
|
+
sha: str
|
|
39
|
+
ts: int
|
|
40
|
+
name: str
|
|
41
|
+
email: str
|
|
42
|
+
subject: str
|
|
43
|
+
changes: list[Change] = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def churn(self) -> int:
|
|
47
|
+
return sum(c.added + c.deleted for c in self.changes)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def git(repo: str, *args: str) -> str:
|
|
51
|
+
try:
|
|
52
|
+
p = subprocess.run(["git", "-C", repo, *args], capture_output=True, check=False)
|
|
53
|
+
except FileNotFoundError as e:
|
|
54
|
+
raise GitError("git is not installed or not on PATH") from e
|
|
55
|
+
if p.returncode != 0:
|
|
56
|
+
raise GitError(p.stderr.decode("utf-8", "replace").strip() or f"git {args[0]} failed")
|
|
57
|
+
return p.stdout.decode("utf-8", "replace")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def is_noise(path: str) -> bool:
|
|
61
|
+
low = path.lower()
|
|
62
|
+
p = PurePosixPath(low)
|
|
63
|
+
return p.name in NOISE_NAMES or low.endswith(NOISE_SUFFIXES) or any(part in NOISE_PARTS for part in p.parts[:-1])
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_bot(name: str, email: str) -> bool:
|
|
67
|
+
return bool(BOT_RE.search(name) or BOT_RE.search(email))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def parse_log(raw: str) -> Iterator[Commit]:
|
|
71
|
+
"""Parse `git log --raw --numstat -z` output (see read_commits) into commits."""
|
|
72
|
+
toks = raw.split("\0")
|
|
73
|
+
i, n = 0, len(toks)
|
|
74
|
+
cur: Commit | None = None
|
|
75
|
+
status: list[tuple[str, str | None, str]] = [] # (status letter, old path, path) in raw order
|
|
76
|
+
nums: list[tuple[int, int, str]] = []
|
|
77
|
+
|
|
78
|
+
def finish() -> Commit | None:
|
|
79
|
+
if cur is None:
|
|
80
|
+
return None
|
|
81
|
+
stat = {p: (s, o) for s, o, p in status}
|
|
82
|
+
for a, d, p in nums:
|
|
83
|
+
s, o = stat.get(p, ("M", None))
|
|
84
|
+
cur.changes.append(Change(p, s, a, d, o))
|
|
85
|
+
seen = {c.path for c in cur.changes}
|
|
86
|
+
cur.changes += [Change(p, s, 0, 0, o) for s, o, p in status if p not in seen] # binary files have no numstat counts
|
|
87
|
+
return cur
|
|
88
|
+
|
|
89
|
+
while i < n:
|
|
90
|
+
t = toks[i]
|
|
91
|
+
if t.startswith(RS):
|
|
92
|
+
done = finish()
|
|
93
|
+
if done:
|
|
94
|
+
yield done
|
|
95
|
+
f = t[1:].split(US)
|
|
96
|
+
cur = Commit(f[0], int(f[1] or 0), f[2], f[3].lower(), f[4]) if len(f) >= 5 else None
|
|
97
|
+
status, nums = [], []
|
|
98
|
+
i += 1
|
|
99
|
+
elif t.lstrip("\n").startswith(":"): # raw record: ":100644 100644 a b M" then path(s)
|
|
100
|
+
code = t.split(" ")[-1]
|
|
101
|
+
letter = code[:1]
|
|
102
|
+
if letter in "RC" and i + 2 < n:
|
|
103
|
+
status.append((letter, toks[i + 1], toks[i + 2]))
|
|
104
|
+
i += 3
|
|
105
|
+
else:
|
|
106
|
+
status.append((letter, None, toks[i + 1] if i + 1 < n else ""))
|
|
107
|
+
i += 2
|
|
108
|
+
elif re.match(r"^(\d+|-)\t(\d+|-)\t", t):
|
|
109
|
+
a, d, p = t.split("\t", 2)
|
|
110
|
+
if p == "" and i + 2 < n: # rename in numstat -z: "a\td\t" NUL old NUL new
|
|
111
|
+
p = toks[i + 2]
|
|
112
|
+
i += 3
|
|
113
|
+
else:
|
|
114
|
+
i += 1
|
|
115
|
+
nums.append((int(a) if a.isdigit() else 0, int(d) if d.isdigit() else 0, p))
|
|
116
|
+
else:
|
|
117
|
+
i += 1
|
|
118
|
+
done = finish()
|
|
119
|
+
if done:
|
|
120
|
+
yield done
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def read_commits(repo: str, rev: str = "HEAD", include_bots: bool = False, include_vendor: bool = False,
|
|
124
|
+
max_commits: int = 200_000, since: str | None = None) -> list[Commit]:
|
|
125
|
+
args = ["log", "--reverse", "--no-merges", "-M", "--raw", "--numstat", "-z", f"--format={FORMAT}", f"--max-count={max_commits}"]
|
|
126
|
+
if since:
|
|
127
|
+
args.append(f"--since={since}")
|
|
128
|
+
raw = git(repo, *args, rev, "--")
|
|
129
|
+
out: list[Commit] = []
|
|
130
|
+
last = 0
|
|
131
|
+
for c in parse_log(raw):
|
|
132
|
+
if not include_bots and is_bot(c.name, c.email):
|
|
133
|
+
continue
|
|
134
|
+
if not include_vendor:
|
|
135
|
+
c.changes = [ch for ch in c.changes if not is_noise(ch.path)]
|
|
136
|
+
last = c.ts = max(c.ts, last) # keep time monotonic even with skewed clocks
|
|
137
|
+
out.append(c)
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def read_tags(repo: str) -> dict[str, str]:
|
|
142
|
+
"""tag name -> commit sha (annotated tags are peeled)."""
|
|
143
|
+
try:
|
|
144
|
+
raw = git(repo, "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(*objectname)", "refs/tags")
|
|
145
|
+
except GitError:
|
|
146
|
+
return {}
|
|
147
|
+
tags = {}
|
|
148
|
+
for line in raw.splitlines():
|
|
149
|
+
name, obj, peeled = (line.split("\t") + ["", ""])[:3]
|
|
150
|
+
if name:
|
|
151
|
+
tags[name] = peeled or obj
|
|
152
|
+
return tags
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def repo_name(repo: str) -> str:
|
|
156
|
+
try:
|
|
157
|
+
top = git(repo, "rev-parse", "--show-toplevel").strip()
|
|
158
|
+
except GitError:
|
|
159
|
+
top = repo
|
|
160
|
+
return PurePosixPath(top.replace("\\", "/")).name or "repository"
|
gitsaga/langs.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""File extension -> (language, colour). Only a handful of well-known languages; everything else is grouped."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import PurePosixPath
|
|
6
|
+
|
|
7
|
+
CODE = {
|
|
8
|
+
".py": ("Python", "#3572A5"), ".pyi": ("Python", "#3572A5"), ".js": ("JavaScript", "#f1e05a"), ".mjs": ("JavaScript", "#f1e05a"),
|
|
9
|
+
".cjs": ("JavaScript", "#f1e05a"), ".jsx": ("JavaScript", "#f1e05a"), ".ts": ("TypeScript", "#3178c6"), ".tsx": ("TypeScript", "#3178c6"),
|
|
10
|
+
".go": ("Go", "#00ADD8"), ".rs": ("Rust", "#dea584"), ".java": ("Java", "#b07219"), ".kt": ("Kotlin", "#A97BFF"), ".kts": ("Kotlin", "#A97BFF"),
|
|
11
|
+
".c": ("C", "#8d8d8d"), ".h": ("C", "#8d8d8d"), ".cc": ("C++", "#f34b7d"), ".cpp": ("C++", "#f34b7d"), ".cxx": ("C++", "#f34b7d"),
|
|
12
|
+
".hpp": ("C++", "#f34b7d"), ".cs": ("C#", "#178600"), ".rb": ("Ruby", "#cc342d"), ".php": ("PHP", "#8892bf"), ".swift": ("Swift", "#F05138"),
|
|
13
|
+
".m": ("Objective-C", "#438eff"), ".scala": ("Scala", "#c22d40"), ".sh": ("Shell", "#89e051"), ".bash": ("Shell", "#89e051"),
|
|
14
|
+
".zsh": ("Shell", "#89e051"), ".lua": ("Lua", "#51a0cf"), ".ex": ("Elixir", "#9a6cc0"), ".exs": ("Elixir", "#9a6cc0"), ".dart": ("Dart", "#00B4AB"),
|
|
15
|
+
".vue": ("Vue", "#41b883"), ".svelte": ("Svelte", "#ff3e00"), ".zig": ("Zig", "#ec915c"), ".hs": ("Haskell", "#5e5086"),
|
|
16
|
+
".clj": ("Clojure", "#db5855"), ".r": ("R", "#198CE7"), ".sql": ("SQL", "#e38c00"), ".tf": ("HCL", "#7b42bc"), ".pl": ("Perl", "#0298c3"),
|
|
17
|
+
}
|
|
18
|
+
WEB = {".html": ("HTML", "#e34c26"), ".htm": ("HTML", "#e34c26"), ".css": ("CSS", "#7957d5"), ".scss": ("CSS", "#7957d5"),
|
|
19
|
+
".sass": ("CSS", "#7957d5"), ".less": ("CSS", "#7957d5")}
|
|
20
|
+
DOCS = {".md": "Docs", ".rst": "Docs", ".txt": "Docs", ".adoc": "Docs", ".markdown": "Docs"}
|
|
21
|
+
CONFIG = {".json": 1, ".yml": 1, ".yaml": 1, ".toml": 1, ".xml": 1, ".ini": 1, ".cfg": 1, ".gradle": 1, ".properties": 1}
|
|
22
|
+
DOCS_COLOR, CONFIG_COLOR, OTHER_COLOR = "#8b949e", "#6e7681", "#4b5563"
|
|
23
|
+
# categories that never "lead" a repo when we detect language shifts
|
|
24
|
+
NON_PROGRAMMING = {"Docs", "Config", "Other", "HTML", "CSS"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def classify(path: str) -> tuple[str, str]:
|
|
28
|
+
ext = PurePosixPath(path.lower()).suffix
|
|
29
|
+
if ext in CODE:
|
|
30
|
+
return CODE[ext]
|
|
31
|
+
if ext in WEB:
|
|
32
|
+
return WEB[ext]
|
|
33
|
+
if ext in DOCS:
|
|
34
|
+
return "Docs", DOCS_COLOR
|
|
35
|
+
if ext in CONFIG:
|
|
36
|
+
return "Config", CONFIG_COLOR
|
|
37
|
+
return "Other", OTHER_COLOR
|
gitsaga/milestones.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Find the moments worth a caption: first commit, releases, contributors joining, new areas, big changes, quiet
|
|
2
|
+
periods, language shifts. Everything is rule-based and deterministic."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
|
|
12
|
+
from .history import Commit
|
|
13
|
+
|
|
14
|
+
DAY = 86400
|
|
15
|
+
SEMVER = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[.-]?(rc|alpha|beta|a|b|dev|pre|snapshot).*)?$", re.IGNORECASE)
|
|
16
|
+
# at most this many of each kind survive the final selection
|
|
17
|
+
LIMITS = {"release": 4, "contributor": 2, "author": 2, "area": 2, "big": 2, "refactor": 1, "burst": 1, "silence": 1,
|
|
18
|
+
"language": 2, "count": 2, "first": 1, "last": 1, "orphan": 3, "handover": 2, "bus": 1}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Milestone:
|
|
23
|
+
commit: int # index into the commit list
|
|
24
|
+
ts: int
|
|
25
|
+
kind: str
|
|
26
|
+
score: float
|
|
27
|
+
title: str
|
|
28
|
+
detail: str = ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Context:
|
|
33
|
+
name: str
|
|
34
|
+
size: int
|
|
35
|
+
authors: Counter[str]
|
|
36
|
+
names: dict[str, str]
|
|
37
|
+
first_seen: dict[str, int]
|
|
38
|
+
dir_first: dict[str, int]
|
|
39
|
+
lang_events: list[tuple[int, str, str]]
|
|
40
|
+
depth: int
|
|
41
|
+
keep: set[str] = field(default_factory=set)
|
|
42
|
+
ownership: object | None = None # ownership.Ownership
|
|
43
|
+
view: str = "language"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def month_year(ts: int) -> str:
|
|
47
|
+
return datetime.fromtimestamp(ts, timezone.utc).strftime("%b %Y")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def short(text: str, n: int = 64) -> str:
|
|
51
|
+
text = re.sub(r"\s+", " ", text).strip()
|
|
52
|
+
return text if len(text) <= n else text[: n - 1].rstrip() + "…"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def detect(commits: list[Commit], tags: dict[str, str], ctx: Context) -> list[Milestone]:
|
|
56
|
+
n = len(commits)
|
|
57
|
+
out: list[Milestone] = []
|
|
58
|
+
by_sha = {c.sha: i for i, c in enumerate(commits)}
|
|
59
|
+
c0 = commits[0]
|
|
60
|
+
out.append(Milestone(0, c0.ts, "first", 100, "It begins", f"{c0.name} makes the first commit: “{short(c0.subject, 56)}”"))
|
|
61
|
+
# ---- releases
|
|
62
|
+
releases = []
|
|
63
|
+
for tag, sha in tags.items():
|
|
64
|
+
i = by_sha.get(sha)
|
|
65
|
+
m = SEMVER.match(tag)
|
|
66
|
+
if i is None or not m or m.group(4):
|
|
67
|
+
continue
|
|
68
|
+
major, minor, patch = int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)
|
|
69
|
+
releases.append((i, tag, major, minor, patch))
|
|
70
|
+
releases.sort()
|
|
71
|
+
for k, (i, tag, major, minor, patch) in enumerate(releases):
|
|
72
|
+
score = 80 if (minor == 0 and patch == 0) else 45 if patch == 0 else 14
|
|
73
|
+
if k == 0:
|
|
74
|
+
score += 25
|
|
75
|
+
who = len({c.email for c in commits[: i + 1]}) if i < 5000 else None
|
|
76
|
+
detail = f"{month_year(commits[i].ts)} · {i + 1:,} commits" + (f" by {who:,} people so far" if who else " so far")
|
|
77
|
+
title = f"First release: {tag}" if k == 0 else f"{tag} released"
|
|
78
|
+
out.append(Milestone(i, commits[i].ts, "release", score + (major == 1 and minor == 0 and patch == 0) * 15, title, detail))
|
|
79
|
+
# ---- contributors
|
|
80
|
+
firsts = sorted(ctx.first_seen.items(), key=lambda kv: kv[1])
|
|
81
|
+
for nth in (10, 25, 50, 100, 250, 500, 1000, 2500, 5000):
|
|
82
|
+
if len(firsts) >= nth:
|
|
83
|
+
email, i = firsts[nth - 1]
|
|
84
|
+
out.append(Milestone(i, commits[i].ts, "contributor", 38 + math.log10(nth) * 6, f"The {nth:,}th contributor",
|
|
85
|
+
f"{ctx.names[email]} joins in {month_year(commits[i].ts)}"))
|
|
86
|
+
top = [e for e, _ in ctx.authors.most_common(6)]
|
|
87
|
+
for rank, email in enumerate(top, 1):
|
|
88
|
+
i = ctx.first_seen[email]
|
|
89
|
+
if i > 0:
|
|
90
|
+
out.append(Milestone(i, commits[i].ts, "author", 58 - rank * 3, f"{ctx.names[email]} joins",
|
|
91
|
+
f"will become the #{rank} contributor with {ctx.authors[email]:,} commits"))
|
|
92
|
+
# ---- new areas (top-level directories that grow into something)
|
|
93
|
+
area_files: Counter[str] = Counter()
|
|
94
|
+
for d, i in ctx.dir_first.items():
|
|
95
|
+
top_dir = d.split("/")[0]
|
|
96
|
+
if d == top_dir and d:
|
|
97
|
+
area_files[d] = i
|
|
98
|
+
sizes = Counter(ch.path.split("/")[0] for c in commits for ch in c.changes if ch.status == "A" and "/" in ch.path)
|
|
99
|
+
for d, i in area_files.items():
|
|
100
|
+
if i == 0 or d.startswith("."):
|
|
101
|
+
continue
|
|
102
|
+
out.append(Milestone(i, commits[i].ts, "area", 24 + min(24, math.log2(sizes[d] + 1) * 3), f"{d}/ takes shape",
|
|
103
|
+
f"a new part of the project, {sizes[d]:,} files over time"))
|
|
104
|
+
# ---- biggest changes and refactors
|
|
105
|
+
churn = sorted(((c.churn, i) for i, c in enumerate(commits) if i > 0), reverse=True)[:3]
|
|
106
|
+
for rank, (ch, i) in enumerate(churn):
|
|
107
|
+
if ch < 200:
|
|
108
|
+
continue
|
|
109
|
+
c = commits[i]
|
|
110
|
+
add, dele = sum(x.added for x in c.changes), sum(x.deleted for x in c.changes)
|
|
111
|
+
out.append(Milestone(i, c.ts, "big", 60 - rank * 12, "The biggest change" if rank == 0 else "Another big change",
|
|
112
|
+
f"+{add:,} / −{dele:,} lines in {len(c.changes):,} files: “{short(c.subject, 48)}”"))
|
|
113
|
+
for i, c in enumerate(commits):
|
|
114
|
+
moved = sum(1 for x in c.changes if x.status == "R")
|
|
115
|
+
if moved >= 25 and i > 0:
|
|
116
|
+
out.append(Milestone(i, c.ts, "refactor", 55 + min(20, moved / 10), "A big reorganisation",
|
|
117
|
+
f"{moved:,} files are moved: “{short(c.subject, 48)}”"))
|
|
118
|
+
# ---- busiest 30 days, long silences
|
|
119
|
+
j = 0
|
|
120
|
+
best = (0, 0)
|
|
121
|
+
for i in range(n):
|
|
122
|
+
while commits[i].ts - commits[j].ts > 30 * DAY:
|
|
123
|
+
j += 1
|
|
124
|
+
if i - j + 1 > best[0]:
|
|
125
|
+
best = (i - j + 1, (i + j) // 2)
|
|
126
|
+
if n >= 50 and best[0] >= 20:
|
|
127
|
+
out.append(Milestone(best[1], commits[best[1]].ts, "burst", 46, "The busiest stretch",
|
|
128
|
+
f"{best[0]:,} commits in 30 days, around {month_year(commits[best[1]].ts)}"))
|
|
129
|
+
for i in range(1, n):
|
|
130
|
+
gap = commits[i].ts - commits[i - 1].ts
|
|
131
|
+
if gap >= 180 * DAY:
|
|
132
|
+
months = round(gap / (30.4 * DAY))
|
|
133
|
+
out.append(Milestone(i, commits[i].ts, "silence", 50 + min(15, months / 4), f"{months} quiet months",
|
|
134
|
+
f"then {commits[i].name} picks it up again"))
|
|
135
|
+
# ---- language shifts
|
|
136
|
+
for i, old, new in ctx.lang_events:
|
|
137
|
+
out.append(Milestone(i, commits[i].ts, "language", 66, f"{new} overtakes {old}", "by number of files"))
|
|
138
|
+
# ---- round numbers
|
|
139
|
+
for k in (100, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000):
|
|
140
|
+
if n >= k:
|
|
141
|
+
out.append(Milestone(k - 1, commits[k - 1].ts, "count", 22 + math.log10(k) * 5, f"{k:,} commits", month_year(commits[k - 1].ts)))
|
|
142
|
+
out.extend(ownership_milestones(commits, ctx))
|
|
143
|
+
# ---- today
|
|
144
|
+
who = len(ctx.authors)
|
|
145
|
+
last = commits[-1]
|
|
146
|
+
detail = f"{n:,} commits · {who:,} contributors · latest {month_year(last.ts)}"
|
|
147
|
+
root = ctx.ownership.events.get("") if ctx.ownership is not None and ctx.view == "ownership" else None
|
|
148
|
+
if root and root[-1].owner:
|
|
149
|
+
r = root[-1]
|
|
150
|
+
detail = f"bus factor {r.bus} · {ctx.names.get(r.owner, '?')} wrote {r.share:.0%} of recent changes"
|
|
151
|
+
out.append(Milestone(n - 1, last.ts, "last", 99, "Today", detail))
|
|
152
|
+
return out
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def ownership_milestones(commits: list[Commit], ctx: Context) -> list[Milestone]:
|
|
156
|
+
"""Knowledge-loss moments: an area loses its owner, ownership is handed over, the bus factor falls to one."""
|
|
157
|
+
own = ctx.ownership
|
|
158
|
+
if own is None:
|
|
159
|
+
return []
|
|
160
|
+
boost = 25 if ctx.view == "ownership" else 0
|
|
161
|
+
n = len(commits)
|
|
162
|
+
out: list[Milestone] = []
|
|
163
|
+
bus_done = False
|
|
164
|
+
orphaned: list[str] = []
|
|
165
|
+
allc = sorted((c for evs in own.events.values() for c in evs), key=lambda c: (c.step, c.dir))
|
|
166
|
+
for c in allc:
|
|
167
|
+
i = min(n - 1, c.step * ctx.size)
|
|
168
|
+
ts = commits[i].ts
|
|
169
|
+
depth = c.dir.count("/") + 1 if c.dir else 0
|
|
170
|
+
who = ctx.names.get(c.owner or "", "")
|
|
171
|
+
if c.dir == "" and not bus_done and c.bus == 1 and c.prev_bus >= 2 and who:
|
|
172
|
+
bus_done = True
|
|
173
|
+
out.append(Milestone(i, ts, "bus", 66 + boost, "The bus factor falls to 1",
|
|
174
|
+
f"{who} now accounts for {c.share:.0%} of recent changes"))
|
|
175
|
+
elif 1 <= depth <= 2 and c.orphan and not c.prev_orphan and c.share >= 0.6 and c.weight >= 30 and who \
|
|
176
|
+
and not any(c.dir == o or c.dir.startswith(o + "/") for o in orphaned):
|
|
177
|
+
orphaned.append(c.dir)
|
|
178
|
+
out.append(Milestone(i, ts, "orphan", 44 + min(26, math.log2(c.weight) * 3) + boost, f"{c.dir}/ loses its owner",
|
|
179
|
+
f"{who} wrote {c.share:.0%} of it and last committed in {month_year(c.last_seen)}"))
|
|
180
|
+
elif depth == 1 and c.owner and c.prev_owner and c.owner != c.prev_owner and c.share >= 0.5 and c.prev_share >= 0.5 \
|
|
181
|
+
and c.weight >= 150 and who:
|
|
182
|
+
out.append(Milestone(i, ts, "handover", 40 + min(20, math.log2(c.weight) * 2) + boost, f"{who} takes over {c.dir}/",
|
|
183
|
+
f"from {ctx.names.get(c.prev_owner, 'the previous owner')} · {month_year(ts)}"))
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def select(found: list[Milestone], n: int, k: int) -> list[Milestone]:
|
|
188
|
+
"""Greedy by score with per-kind limits and a minimum spacing, always keeping the first and the last."""
|
|
189
|
+
must = [m for m in found if m.kind in ("first", "last")]
|
|
190
|
+
chosen = list(must)
|
|
191
|
+
taken = Counter(m.kind for m in chosen)
|
|
192
|
+
gap = max(1, int(n * 0.035))
|
|
193
|
+
for m in sorted((m for m in found if m.kind not in ("first", "last")), key=lambda m: (-m.score, m.commit, m.title)):
|
|
194
|
+
if len(chosen) >= k:
|
|
195
|
+
break
|
|
196
|
+
if taken[m.kind] >= LIMITS.get(m.kind, 2):
|
|
197
|
+
continue
|
|
198
|
+
if any(abs(m.commit - o.commit) < gap for o in chosen):
|
|
199
|
+
continue
|
|
200
|
+
chosen.append(m)
|
|
201
|
+
taken[m.kind] += 1
|
|
202
|
+
if not any(m.title == "The biggest change" for m in chosen): # the very biggest one lost out on spacing
|
|
203
|
+
for m in chosen:
|
|
204
|
+
if m.title == "Another big change":
|
|
205
|
+
m.title = "The biggest change"
|
|
206
|
+
break
|
|
207
|
+
return sorted(chosen, key=lambda m: (m.commit, -m.score))
|