git-archaeology-mcp 0.1.0__tar.gz

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.
@@ -0,0 +1,25 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ push:
7
+ tags: ["v*"]
8
+
9
+ jobs:
10
+ publish:
11
+ runs-on: ubuntu-latest
12
+ environment: pypi
13
+ permissions:
14
+ id-token: write
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.12"
20
+ - name: Build distributions
21
+ run: |
22
+ python -m pip install --upgrade build
23
+ python -m build
24
+ - name: Publish to PyPI
25
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .pytest_cache/
5
+ dist/
6
+ build/
7
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zhihang Liu
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.
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.5
2
+ Name: git-archaeology-mcp
3
+ Version: 0.1.0
4
+ Summary: An MCP server that lets your AI agent do git archaeology: answer 'why is this code written this way?' by tracing blame, file history, commit stories, code ownership, hotspots, and co-change coupling — local git only, strictly read-only.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: mcp<2,>=1.2
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest>=8.0; extra == 'dev'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # git-archaeology-mcp
14
+
15
+ <p align="center">
16
+ <img src="https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white" alt="Python 3.11+">
17
+ <img src="https://img.shields.io/badge/git-local%20CLI-F05032?logo=git&logoColor=white" alt="Local git CLI">
18
+ <img src="https://img.shields.io/badge/tests-28%20passing-brightgreen" alt="28 tests passing">
19
+ <img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license">
20
+ <img src="https://img.shields.io/badge/MCP-server-purple" alt="MCP server">
21
+ </p>
22
+
23
+ <p align="center"><b>Every line of code has a past.</b></p>
24
+
25
+ **One call. The story behind any line of code.** An MCP server that lets
26
+ Claude, Cursor, or any MCP client answer *"Why is this function written
27
+ this way?"* — by digging through your local git history: blame grouped by
28
+ commit, file timelines with rename chains, commit deep-dives, code
29
+ ownership, churn hotspots, and co-change coupling.
30
+
31
+ > Ask your agent: **"Why is this function written this way?"** — and watch
32
+ > it run `why_code` instead of guessing.
33
+
34
+ ## How it works
35
+
36
+ The server shells out to the **local `git` CLI only** — `log`, `blame`,
37
+ `show`, `diff-tree` — against a clone you already have. No network, no
38
+ GitHub token, no API keys. It works on any repository: public, private,
39
+ or never pushed anywhere.
40
+
41
+ **Read-only by design.** Only history-reading git commands are ever run.
42
+ The server cannot modify your working tree, index, or refs — there is no
43
+ write path to disable.
44
+
45
+ ## The headline: `why_code`
46
+
47
+ Most git MCP servers hand the agent raw `log` output and let it improvise.
48
+ `why_code` does the archaeology in one call: it blames a line range,
49
+ groups the lines by commit, and returns each commit's author, date,
50
+ subject, and message excerpt — plus the **single most relevant commit**
51
+ (the one that owns the most lines in the range), spelled out in one
52
+ sentence the agent can quote back to you.
53
+
54
+ Sample output (abridged, from a real run against the
55
+ [db-health-mcp](https://github.com/ekss1121/db-health-mcp) repository —
56
+ the `slow_queries` tool, lines 287–297):
57
+
58
+ ```json
59
+ {
60
+ "file": "src/db_health_mcp/server.py",
61
+ "total_lines": 11,
62
+ "most_relevant_commit": {
63
+ "short_sha": "c1ab42b70c",
64
+ "summary": "Most relevant commit: c1ab42b70c by Zhihang Liu (2026-12-05) — \"health_report: cut slow-query noise, skip own queries, name index columns\" — it owns 9 of 11 lines in this range. Its message says: A live run against PostgreSQL 16 scored a demo database D (46/100) mostly on noise: 10 of 13 findings were \"slow queries\", the category hit its 30-point cap, and the missing-index fix still said `<column>`. …"
65
+ }
66
+ }
67
+ ```
68
+
69
+ That commit is a real merged PR whose message explains *why* the code
70
+ changed — exactly the answer "why is this written this way?" needs.
71
+
72
+ ## All six tools
73
+
74
+ | Tool | What it answers |
75
+ | --- | --- |
76
+ | `why_code(file, start_line, end_line)` | "Why is this code written this way?" — blame grouped by commit, most relevant commit called out |
77
+ | `file_story(file)` | "Where did this file come from?" — created when/by whom, rename chain, total commits, top authors, latest change |
78
+ | `commit_story(sha)` | "What happened in this commit?" — full message, diff stat, parents, PR/issue/URL references extracted |
79
+ | `who_knows(path)` | "Who should I ask about this code?" — contributors ranked by commits and by lines currently owned, with last-active dates |
80
+ | `hotspots(since?, path?)` | "Where does this codebase churn?" — most-changed files in a period (default: last 90 days), with distinct-author counts |
81
+ | `coupled_files(file, limit?)` | "What secretly changes together?" — co-change counts and Jaccard similarity for files changed in the same commits |
82
+
83
+ Every tool returns structured JSON, and every failure mode — missing
84
+ file, binary file, empty repository, shallow history, uncommitted lines —
85
+ comes back as a clear result, never a crashed server.
86
+
87
+ ## Quick start
88
+
89
+ ```bash
90
+ pip install git-archaeology-mcp # or: pip install -e . from a clone
91
+ ```
92
+
93
+ ### Claude Code
94
+
95
+ ```bash
96
+ claude mcp add git-archaeology \
97
+ -e GIT_ARCHAEOLOGY_REPO=/path/to/your/repo \
98
+ -- git-archaeology-mcp
99
+ ```
100
+
101
+ ### Cursor / other MCP clients
102
+
103
+ ```json
104
+ {
105
+ "mcpServers": {
106
+ "git-archaeology": {
107
+ "command": "git-archaeology-mcp",
108
+ "env": {
109
+ "GIT_ARCHAEOLOGY_REPO": "/path/to/your/repo"
110
+ }
111
+ }
112
+ }
113
+ }
114
+ ```
115
+
116
+ Every tool also accepts an optional `repo_path` argument, so one server
117
+ instance can dig through several repositories.
118
+
119
+ Then just ask:
120
+
121
+ - "Why is this function written this way?"
122
+ - "Who should I ask about the billing module?"
123
+ - "What's the story of this file — has it been renamed?"
124
+ - "Which files change most often, and what changes together with them?"
125
+
126
+ ## Notes
127
+
128
+ - Requires `git` on PATH and Python 3.11+. The only runtime dependency
129
+ is the official `mcp` SDK.
130
+ - Paths are relative to the repository root (absolute paths inside the
131
+ repo work too).
132
+ - `why_code` caps a single call at 500 lines; ownership blame in
133
+ `who_knows` is skipped for files over 20,000 lines or binary files.
134
+ - Uncommitted working-tree lines are reported as `"uncommitted"` rather
135
+ than attributed to a commit.
136
+ - Shallow clones are detected and flagged in results — the creation
137
+ commit and rename chain may be incomplete there.
138
+ - Merge commits contribute no file list to `coupled_files` (matching
139
+ `git show` behavior), so coupling through merges is not counted.
140
+
141
+ ## Development
142
+
143
+ ```bash
144
+ python -m venv .venv && source .venv/bin/activate
145
+ pip install -e ".[dev]"
146
+ pytest # fixture-repo tests, no network needed
147
+ python scripts/selftest.py # MCP handshake + tool list + error paths
148
+ ```
149
+
150
+ ## Roadmap
151
+
152
+ - [ ] `why_deleted`: find the commit that removed a line or function
153
+ - [ ] Pickaxe search (`git log -S`) as a tool: "when was this string introduced?"
154
+ - [ ] Author identity merging (same person, several emails)
155
+ - [ ] Blame ignore-revs support (`.git-blame-ignore-revs`) for mass-reformat commits
156
+
157
+ ## License
158
+
159
+ MIT
@@ -0,0 +1,147 @@
1
+ # git-archaeology-mcp
2
+
3
+ <p align="center">
4
+ <img src="https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white" alt="Python 3.11+">
5
+ <img src="https://img.shields.io/badge/git-local%20CLI-F05032?logo=git&logoColor=white" alt="Local git CLI">
6
+ <img src="https://img.shields.io/badge/tests-28%20passing-brightgreen" alt="28 tests passing">
7
+ <img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license">
8
+ <img src="https://img.shields.io/badge/MCP-server-purple" alt="MCP server">
9
+ </p>
10
+
11
+ <p align="center"><b>Every line of code has a past.</b></p>
12
+
13
+ **One call. The story behind any line of code.** An MCP server that lets
14
+ Claude, Cursor, or any MCP client answer *"Why is this function written
15
+ this way?"* — by digging through your local git history: blame grouped by
16
+ commit, file timelines with rename chains, commit deep-dives, code
17
+ ownership, churn hotspots, and co-change coupling.
18
+
19
+ > Ask your agent: **"Why is this function written this way?"** — and watch
20
+ > it run `why_code` instead of guessing.
21
+
22
+ ## How it works
23
+
24
+ The server shells out to the **local `git` CLI only** — `log`, `blame`,
25
+ `show`, `diff-tree` — against a clone you already have. No network, no
26
+ GitHub token, no API keys. It works on any repository: public, private,
27
+ or never pushed anywhere.
28
+
29
+ **Read-only by design.** Only history-reading git commands are ever run.
30
+ The server cannot modify your working tree, index, or refs — there is no
31
+ write path to disable.
32
+
33
+ ## The headline: `why_code`
34
+
35
+ Most git MCP servers hand the agent raw `log` output and let it improvise.
36
+ `why_code` does the archaeology in one call: it blames a line range,
37
+ groups the lines by commit, and returns each commit's author, date,
38
+ subject, and message excerpt — plus the **single most relevant commit**
39
+ (the one that owns the most lines in the range), spelled out in one
40
+ sentence the agent can quote back to you.
41
+
42
+ Sample output (abridged, from a real run against the
43
+ [db-health-mcp](https://github.com/ekss1121/db-health-mcp) repository —
44
+ the `slow_queries` tool, lines 287–297):
45
+
46
+ ```json
47
+ {
48
+ "file": "src/db_health_mcp/server.py",
49
+ "total_lines": 11,
50
+ "most_relevant_commit": {
51
+ "short_sha": "c1ab42b70c",
52
+ "summary": "Most relevant commit: c1ab42b70c by Zhihang Liu (2026-12-05) — \"health_report: cut slow-query noise, skip own queries, name index columns\" — it owns 9 of 11 lines in this range. Its message says: A live run against PostgreSQL 16 scored a demo database D (46/100) mostly on noise: 10 of 13 findings were \"slow queries\", the category hit its 30-point cap, and the missing-index fix still said `<column>`. …"
53
+ }
54
+ }
55
+ ```
56
+
57
+ That commit is a real merged PR whose message explains *why* the code
58
+ changed — exactly the answer "why is this written this way?" needs.
59
+
60
+ ## All six tools
61
+
62
+ | Tool | What it answers |
63
+ | --- | --- |
64
+ | `why_code(file, start_line, end_line)` | "Why is this code written this way?" — blame grouped by commit, most relevant commit called out |
65
+ | `file_story(file)` | "Where did this file come from?" — created when/by whom, rename chain, total commits, top authors, latest change |
66
+ | `commit_story(sha)` | "What happened in this commit?" — full message, diff stat, parents, PR/issue/URL references extracted |
67
+ | `who_knows(path)` | "Who should I ask about this code?" — contributors ranked by commits and by lines currently owned, with last-active dates |
68
+ | `hotspots(since?, path?)` | "Where does this codebase churn?" — most-changed files in a period (default: last 90 days), with distinct-author counts |
69
+ | `coupled_files(file, limit?)` | "What secretly changes together?" — co-change counts and Jaccard similarity for files changed in the same commits |
70
+
71
+ Every tool returns structured JSON, and every failure mode — missing
72
+ file, binary file, empty repository, shallow history, uncommitted lines —
73
+ comes back as a clear result, never a crashed server.
74
+
75
+ ## Quick start
76
+
77
+ ```bash
78
+ pip install git-archaeology-mcp # or: pip install -e . from a clone
79
+ ```
80
+
81
+ ### Claude Code
82
+
83
+ ```bash
84
+ claude mcp add git-archaeology \
85
+ -e GIT_ARCHAEOLOGY_REPO=/path/to/your/repo \
86
+ -- git-archaeology-mcp
87
+ ```
88
+
89
+ ### Cursor / other MCP clients
90
+
91
+ ```json
92
+ {
93
+ "mcpServers": {
94
+ "git-archaeology": {
95
+ "command": "git-archaeology-mcp",
96
+ "env": {
97
+ "GIT_ARCHAEOLOGY_REPO": "/path/to/your/repo"
98
+ }
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ Every tool also accepts an optional `repo_path` argument, so one server
105
+ instance can dig through several repositories.
106
+
107
+ Then just ask:
108
+
109
+ - "Why is this function written this way?"
110
+ - "Who should I ask about the billing module?"
111
+ - "What's the story of this file — has it been renamed?"
112
+ - "Which files change most often, and what changes together with them?"
113
+
114
+ ## Notes
115
+
116
+ - Requires `git` on PATH and Python 3.11+. The only runtime dependency
117
+ is the official `mcp` SDK.
118
+ - Paths are relative to the repository root (absolute paths inside the
119
+ repo work too).
120
+ - `why_code` caps a single call at 500 lines; ownership blame in
121
+ `who_knows` is skipped for files over 20,000 lines or binary files.
122
+ - Uncommitted working-tree lines are reported as `"uncommitted"` rather
123
+ than attributed to a commit.
124
+ - Shallow clones are detected and flagged in results — the creation
125
+ commit and rename chain may be incomplete there.
126
+ - Merge commits contribute no file list to `coupled_files` (matching
127
+ `git show` behavior), so coupling through merges is not counted.
128
+
129
+ ## Development
130
+
131
+ ```bash
132
+ python -m venv .venv && source .venv/bin/activate
133
+ pip install -e ".[dev]"
134
+ pytest # fixture-repo tests, no network needed
135
+ python scripts/selftest.py # MCP handshake + tool list + error paths
136
+ ```
137
+
138
+ ## Roadmap
139
+
140
+ - [ ] `why_deleted`: find the commit that removed a line or function
141
+ - [ ] Pickaxe search (`git log -S`) as a tool: "when was this string introduced?"
142
+ - [ ] Author identity merging (same person, several emails)
143
+ - [ ] Blame ignore-revs support (`.git-blame-ignore-revs`) for mass-reformat commits
144
+
145
+ ## License
146
+
147
+ MIT
@@ -0,0 +1 @@
1
+ {"$schema":"https://glama.ai/mcp/schemas/server.json","maintainers":["ekss1121"]}
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "git-archaeology-mcp"
7
+ version = "0.1.0"
8
+ description = "An MCP server that lets your AI agent do git archaeology: answer 'why is this code written this way?' by tracing blame, file history, commit stories, code ownership, hotspots, and co-change coupling — local git only, strictly read-only."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.11"
12
+ dependencies = [
13
+ "mcp>=1.2,<2",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ dev = ["pytest>=8.0"]
18
+
19
+ [project.scripts]
20
+ git-archaeology-mcp = "git_archaeology_mcp.server:main"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/git_archaeology_mcp"]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env python3
2
+ """Self-test: launch the server over stdio, do the MCP handshake, list
3
+ the tools, and verify both the error path (no repo configured) and a
4
+ real call against a throwaway git repository created on the fly.
5
+
6
+ Usage:
7
+ python scripts/selftest.py
8
+ """
9
+
10
+ import asyncio
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+
16
+ from mcp import ClientSession, StdioServerParameters
17
+ from mcp.client.stdio import stdio_client
18
+
19
+ EXPECTED_TOOLS = {
20
+ "why_code",
21
+ "file_story",
22
+ "commit_story",
23
+ "who_knows",
24
+ "hotspots",
25
+ "coupled_files",
26
+ }
27
+
28
+
29
+ def make_repo() -> str:
30
+ root = tempfile.mkdtemp(prefix="git-archaeology-selftest-")
31
+ env = {
32
+ **os.environ,
33
+ "GIT_AUTHOR_NAME": "Self Test",
34
+ "GIT_AUTHOR_EMAIL": "selftest@example.com",
35
+ "GIT_COMMITTER_NAME": "Self Test",
36
+ "GIT_COMMITTER_EMAIL": "selftest@example.com",
37
+ }
38
+ subprocess.run(["git", "-C", root, "init", "-q", "-b", "main"],
39
+ check=True, env=env)
40
+ with open(os.path.join(root, "hello.py"), "w") as fh:
41
+ fh.write("print('hello')\n")
42
+ subprocess.run(["git", "-C", root, "add", "-A"], check=True, env=env)
43
+ subprocess.run(["git", "-C", root, "commit", "-q", "-m", "Initial commit"],
44
+ check=True, env=env)
45
+ return root
46
+
47
+
48
+ async def main() -> int:
49
+ repo = make_repo()
50
+ base_env = {
51
+ k: v for k, v in os.environ.items() if k != "GIT_ARCHAEOLOGY_REPO"
52
+ }
53
+
54
+ # 1. No repo configured: tools must return a clean error, not crash.
55
+ params = StdioServerParameters(
56
+ command=sys.executable,
57
+ args=["-m", "git_archaeology_mcp.server"],
58
+ env={**base_env, "PYTHONPATH": "src"},
59
+ )
60
+ async with stdio_client(params) as (read, write):
61
+ async with ClientSession(read, write) as session:
62
+ await session.initialize()
63
+ tools = await session.list_tools()
64
+ names = {t.name for t in tools.tools}
65
+ print("Tools exposed:", ", ".join(sorted(names)))
66
+ missing = EXPECTED_TOOLS - names
67
+ if missing:
68
+ print("FAIL: missing tools:", ", ".join(sorted(missing)))
69
+ return 1
70
+ result = await session.call_tool("file_story", {"file": "x.py"})
71
+ text = result.content[0].text if result.content else ""
72
+ print("file_story without repo config ->", text[:120])
73
+ if "GIT_ARCHAEOLOGY_REPO" not in text:
74
+ print("FAIL: expected a configuration error mentioning "
75
+ "GIT_ARCHAEOLOGY_REPO")
76
+ return 1
77
+
78
+ # 2. With a repo configured: a real call must succeed.
79
+ params = StdioServerParameters(
80
+ command=sys.executable,
81
+ args=["-m", "git_archaeology_mcp.server"],
82
+ env={**base_env, "PYTHONPATH": "src", "GIT_ARCHAEOLOGY_REPO": repo},
83
+ )
84
+ async with stdio_client(params) as (read, write):
85
+ async with ClientSession(read, write) as session:
86
+ await session.initialize()
87
+ result = await session.call_tool(
88
+ "file_story", {"file": "hello.py"}
89
+ )
90
+ text = result.content[0].text if result.content else ""
91
+ print("file_story on selftest repo ->", text[:160])
92
+ if "Initial commit" not in text:
93
+ print("FAIL: expected the fixture commit in file_story")
94
+ return 1
95
+
96
+ print("OK: handshake, tool list, error path, and live call all work.")
97
+ return 0
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(asyncio.run(main()))
@@ -0,0 +1 @@
1
+ {"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","description":"Git archaeology MCP server: why_code traces any line range to the commits that wrote it and why; plus file stories, commit deep-dives, code ownership, churn hotspots and co-change analysis. Local git only, read-only.","name":"io.github.ekss1121/git-archaeology-mcp","packages":[{"environmentVariables":[{"description":"Path to the local git repository to analyze","format":"string","isRequired":true,"isSecret":false,"name":"GIT_ARCHAEOLOGY_REPO"}],"identifier":"git-archaeology-mcp","registryType":"pypi","transport":{"type":"stdio"},"version":"0.1.0"}],"repository":{"source":"github","url":"https://github.com/ekss1121/git-archaeology-mcp"},"title":"git-archaeology-mcp","version":"0.1.0"}
@@ -0,0 +1,23 @@
1
+ # Smithery configuration file: https://smithery.ai/docs/build/publish
2
+
3
+ startCommand:
4
+ type: stdio
5
+ configSchema:
6
+ # JSON Schema defining the configuration options for the MCP.
7
+ type: object
8
+ required:
9
+ - repoPath
10
+ properties:
11
+ repoPath:
12
+ type: string
13
+ description: Path to the local git repository to analyze
14
+ commandFunction:
15
+ # A JS function that produces the CLI command based on the given config to start the MCP on Smithery.
16
+ |-
17
+ (config) => ({
18
+ command: 'git-archaeology-mcp',
19
+ args: [],
20
+ env: { GIT_ARCHAEOLOGY_REPO: config.repoPath }
21
+ })
22
+ exampleConfig:
23
+ repoPath: /path/to/your/repo
@@ -0,0 +1,4 @@
1
+ """git-archaeology-mcp: an MCP server that answers "why is this code
2
+ written this way?" by tracing git history."""
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,103 @@
1
+ """Pure analysis helpers: blame grouping, reference extraction from
2
+ commit messages, and co-change math. No git calls here — everything is
3
+ unit-testable on plain data structures."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections import OrderedDict
9
+
10
+ from .gitlog import ZERO_SHA
11
+
12
+ BODY_EXCERPT_CHARS = 500
13
+
14
+
15
+ def body_excerpt(body: str, limit: int = BODY_EXCERPT_CHARS) -> str:
16
+ body = (body or "").strip()
17
+ if len(body) <= limit:
18
+ return body
19
+ return body[:limit].rstrip() + "…"
20
+
21
+
22
+ def short_sha(sha: str) -> str:
23
+ return sha[:10]
24
+
25
+
26
+ def group_blame_by_commit(lines: list[dict]) -> list[dict]:
27
+ """Group blamed lines by commit, preserving first-appearance order.
28
+ Returns groups sorted by lines owned (desc), then most recent date."""
29
+ groups: "OrderedDict[str, dict]" = OrderedDict()
30
+ for line in lines:
31
+ sha = line["sha"]
32
+ group = groups.get(sha)
33
+ if group is None:
34
+ uncommitted = sha == ZERO_SHA
35
+ group = {
36
+ "sha": None if uncommitted else sha,
37
+ "short_sha": None if uncommitted else short_sha(sha),
38
+ "uncommitted": uncommitted,
39
+ "author": "uncommitted" if uncommitted else line.get("author", ""),
40
+ "author_email": None if uncommitted else line.get("author_email"),
41
+ "date": None if uncommitted else line.get("date"),
42
+ "subject": None if uncommitted else line.get("summary"),
43
+ "lines_owned": 0,
44
+ "line_numbers": [],
45
+ }
46
+ groups[sha] = group
47
+ group["lines_owned"] += 1
48
+ group["line_numbers"].append(line["line"])
49
+ result = list(groups.values())
50
+ for group in result:
51
+ group["line_ranges"] = _ranges(group.pop("line_numbers"))
52
+ result.sort(
53
+ key=lambda g: (g["lines_owned"], g["date"] or ""), reverse=True
54
+ )
55
+ return result
56
+
57
+
58
+ def _ranges(numbers: list[int]) -> list[list[int]]:
59
+ if not numbers:
60
+ return []
61
+ numbers = sorted(numbers)
62
+ ranges: list[list[int]] = []
63
+ start = prev = numbers[0]
64
+ for n in numbers[1:]:
65
+ if n == prev + 1:
66
+ prev = n
67
+ continue
68
+ ranges.append([start, prev])
69
+ start = prev = n
70
+ ranges.append([start, prev])
71
+ return ranges
72
+
73
+
74
+ _PR_RE = re.compile(r"(?:pull request|PR|MR|merge request)\s*#(\d+)", re.I)
75
+ _HASH_RE = re.compile(r"#(\d+)")
76
+ _URL_RE = re.compile(r"https?://[^\s<>()\[\]\"']+")
77
+
78
+
79
+ def extract_refs(message: str) -> dict:
80
+ """Pull PR numbers, issue references, and URLs out of a commit
81
+ message. `#123` mentioned next to 'pull request'/'PR' counts as a
82
+ PR; other `#123`s count as issue references."""
83
+ pr_numbers = sorted({int(n) for n in _PR_RE.findall(message or "")})
84
+ hash_numbers = {int(n) for n in _HASH_RE.findall(message or "")}
85
+ issue_numbers = sorted(hash_numbers - set(pr_numbers))
86
+ urls = []
87
+ for url in _URL_RE.findall(message or ""):
88
+ url = url.rstrip(".,;:")
89
+ if url not in urls:
90
+ urls.append(url)
91
+ return {
92
+ "pull_requests": pr_numbers,
93
+ "issues": issue_numbers,
94
+ "urls": urls,
95
+ }
96
+
97
+
98
+ def jaccard_pct(co_changes: int, total_a: int, total_b: int) -> float:
99
+ """Jaccard similarity of two files' commit sets, as a percentage."""
100
+ union = total_a + total_b - co_changes
101
+ if union <= 0:
102
+ return 0.0
103
+ return round(100.0 * co_changes / union, 1)