Skip to content

Commit e79a0c8

Browse files
Amar K PAmar K P
authored andcommitted
refactor: extract chunking and chunk summarization into src/gitmate/chunking.py
- Move chunk_patch_text and summarize_omitted_diffs to src/gitmate/chunking.py to cleanly separate LLM-dependent chunking logic from deterministic zero-LLM fallback.py - Re-export helpers in fallback.py for backward compatibility - Add dedicated test suite in tests/test_chunking.py (4 new tests, 163 total passing)
1 parent 8d333db commit e79a0c8

3 files changed

Lines changed: 171 additions & 64 deletions

File tree

‎src/gitmate/chunking.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""Chunking abstractions: split oversized diffs and summarize via LLMProvider."""
2+
3+
from __future__ import annotations
4+
5+
from typing import TYPE_CHECKING
6+
7+
if TYPE_CHECKING:
8+
from gitmate.diff_extractor import FileDiff
9+
from gitmate.providers.base import LLMProvider
10+
11+
12+
def chunk_patch_text(patch: str, max_chars: int = 8_000) -> list[str]:
13+
"""Split large patch text into chunks if needed to avoid blowing per-call limits."""
14+
if len(patch) <= max_chars:
15+
return [patch]
16+
lines = patch.splitlines(keepends=True)
17+
chunks: list[str] = []
18+
current: list[str] = []
19+
current_len = 0
20+
for line in lines:
21+
if current_len + len(line) > max_chars and current:
22+
chunks.append("".join(current))
23+
current = [line]
24+
current_len = len(line)
25+
else:
26+
current.append(line)
27+
current_len += len(line)
28+
if current:
29+
chunks.append("".join(current))
30+
return chunks
31+
32+
33+
# Compatibility alias for internal callers
34+
_chunk_patch_text = chunk_patch_text
35+
36+
37+
def summarize_omitted_diffs(
38+
omitted_diffs: list[FileDiff],
39+
provider: LLMProvider,
40+
model: str,
41+
) -> tuple[str, int, int]:
42+
"""Summarize omitted diffs per file/chunk and return merged notes and token usage.
43+
44+
Consumes BudgetDecision.omitted_diffs (which preserves untruncated patches),
45+
prompts the provider for concise per-file summaries, and aggregates token usage.
46+
"""
47+
summaries: list[str] = []
48+
total_in = 0
49+
total_out = 0
50+
51+
for diff in omitted_diffs:
52+
if diff.is_binary or not diff.patch_text.strip():
53+
summaries.append(f"- {diff.path}: [binary or empty file]")
54+
continue
55+
56+
chunks = chunk_patch_text(diff.patch_text)
57+
file_part_summaries: list[str] = []
58+
for i, chunk in enumerate(chunks, start=1):
59+
part_suffix = f" (part {i}/{len(chunks)})" if len(chunks) > 1 else ""
60+
prompt = (
61+
f"Summarize the following git diff for {diff.path}{part_suffix} in 1-2 concise bullet points "
62+
f"(focus on WHAT changed and WHY):\n\n"
63+
f"{chunk}"
64+
)
65+
resp = provider.generate(prompt=prompt, model=model)
66+
if resp.input_tokens is not None:
67+
total_in += resp.input_tokens
68+
if resp.output_tokens is not None:
69+
total_out += resp.output_tokens
70+
text = resp.text.strip()
71+
if text:
72+
file_part_summaries.append(text)
73+
74+
joined_file_summary = "; ".join(file_part_summaries) if file_part_summaries else "Updated"
75+
summaries.append(f"- {diff.path}: {joined_file_summary}")
76+
77+
return "\n".join(summaries), total_in, total_out

‎src/gitmate/fallback.py‎

Lines changed: 1 addition & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from typing import TYPE_CHECKING
99

1010
from gitmate import config as config_mod
11+
from gitmate.chunking import summarize_omitted_diffs
1112
from gitmate.config import API_KEY_ACCOUNT, GitmateConfig
1213
from gitmate.diff_extractor import FileDiff
1314
from gitmate.prompt import load_template, render_commit_prompt
@@ -213,70 +214,6 @@ def _multi_file_fallback(diffs: list[FileDiff], style: str) -> str:
213214
return f"{header}\n\n{body}"
214215

215216

216-
def _chunk_patch_text(patch: str, max_chars: int = 8_000) -> list[str]:
217-
"""Split large patch text into chunks if needed to avoid blowing per-call limits."""
218-
if len(patch) <= max_chars:
219-
return [patch]
220-
lines = patch.splitlines(keepends=True)
221-
chunks: list[str] = []
222-
current: list[str] = []
223-
current_len = 0
224-
for line in lines:
225-
if current_len + len(line) > max_chars and current:
226-
chunks.append("".join(current))
227-
current = [line]
228-
current_len = len(line)
229-
else:
230-
current.append(line)
231-
current_len += len(line)
232-
if current:
233-
chunks.append("".join(current))
234-
return chunks
235-
236-
237-
def summarize_omitted_diffs(
238-
omitted_diffs: list[FileDiff],
239-
provider: LLMProvider,
240-
model: str,
241-
) -> tuple[str, int, int]:
242-
"""Summarize omitted diffs per file/chunk and return merged notes and token usage.
243-
244-
Consumes BudgetDecision.omitted_diffs (which preserves untruncated patches),
245-
prompts the provider for concise per-file summaries, and aggregates token usage.
246-
"""
247-
summaries: list[str] = []
248-
total_in = 0
249-
total_out = 0
250-
251-
for diff in omitted_diffs:
252-
if diff.is_binary or not diff.patch_text.strip():
253-
summaries.append(f"- {diff.path}: [binary or empty file]")
254-
continue
255-
256-
chunks = _chunk_patch_text(diff.patch_text)
257-
file_part_summaries: list[str] = []
258-
for i, chunk in enumerate(chunks, start=1):
259-
part_suffix = f" (part {i}/{len(chunks)})" if len(chunks) > 1 else ""
260-
prompt = (
261-
f"Summarize the following git diff for {diff.path}{part_suffix} in 1-2 concise bullet points "
262-
f"(focus on WHAT changed and WHY):\n\n"
263-
f"{chunk}"
264-
)
265-
resp = provider.generate(prompt=prompt, model=model)
266-
if resp.input_tokens is not None:
267-
total_in += resp.input_tokens
268-
if resp.output_tokens is not None:
269-
total_out += resp.output_tokens
270-
text = resp.text.strip()
271-
if text:
272-
file_part_summaries.append(text)
273-
274-
joined_file_summary = "; ".join(file_part_summaries) if file_part_summaries else "Updated"
275-
summaries.append(f"- {diff.path}: {joined_file_summary}")
276-
277-
return "\n".join(summaries), total_in, total_out
278-
279-
280217
def generate_commit_message(
281218
diffs: list[FileDiff],
282219
cfg: GitmateConfig,

‎tests/test_chunking.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
"""Tests for diff chunking and omitted diff summarization."""
2+
3+
from __future__ import annotations
4+
5+
from gitmate.chunking import chunk_patch_text, summarize_omitted_diffs
6+
from gitmate.diff_extractor import FileDiff
7+
from gitmate.providers.base import LLMResponse
8+
9+
10+
class FakeChunkProvider:
11+
"""Mock LLMProvider recording chunk summarization calls."""
12+
13+
def __init__(self, response: str = "Added feature X") -> None:
14+
self.response = response
15+
self.prompts: list[str] = []
16+
17+
def generate(self, prompt: str, model: str) -> LLMResponse:
18+
self.prompts.append(prompt)
19+
return LLMResponse(text=self.response, model=model, input_tokens=40, output_tokens=10)
20+
21+
22+
def test_chunk_patch_text_small() -> None:
23+
patch = "@@ -1,3 +1,3 @@\n-old\n+new\n"
24+
chunks = chunk_patch_text(patch, max_chars=100)
25+
assert chunks == [patch]
26+
27+
28+
def test_chunk_patch_text_splits_at_lines() -> None:
29+
lines = [f"+line {i}\n" for i in range(20)]
30+
patch = "".join(lines)
31+
chunks = chunk_patch_text(patch, max_chars=50)
32+
assert len(chunks) > 1
33+
assert "".join(chunks) == patch
34+
35+
36+
def test_summarize_omitted_diffs_binary_and_empty() -> None:
37+
binary_diff = FileDiff(
38+
path="assets/logo.png",
39+
old_path=None,
40+
status="modified",
41+
additions=0,
42+
deletions=0,
43+
patch_text="",
44+
is_binary=True,
45+
)
46+
empty_diff = FileDiff(
47+
path="empty.txt",
48+
old_path=None,
49+
status="modified",
50+
additions=0,
51+
deletions=0,
52+
patch_text=" ",
53+
is_binary=False,
54+
)
55+
provider = FakeChunkProvider()
56+
merged, total_in, total_out = summarize_omitted_diffs(
57+
[binary_diff, empty_diff], provider, "gemini-3.5-flash-lite"
58+
)
59+
assert "- assets/logo.png: [binary or empty file]" in merged
60+
assert "- empty.txt: [binary or empty file]" in merged
61+
assert provider.prompts == []
62+
assert total_in == 0
63+
assert total_out == 0
64+
65+
66+
def test_summarize_omitted_diffs_calls_provider_and_aggregates_tokens() -> None:
67+
diff1 = FileDiff(
68+
path="src/auth.py",
69+
old_path=None,
70+
status="modified",
71+
additions=10,
72+
deletions=2,
73+
patch_text="@@ -1,5 +1,10 @@\n+auth logic\n",
74+
is_binary=False,
75+
)
76+
diff2 = FileDiff(
77+
path="src/db.py",
78+
old_path=None,
79+
status="modified",
80+
additions=5,
81+
deletions=1,
82+
patch_text="@@ -1,5 +1,5 @@\n+db connection\n",
83+
is_binary=False,
84+
)
85+
provider = FakeChunkProvider(response="Updated service logic")
86+
merged, total_in, total_out = summarize_omitted_diffs(
87+
[diff1, diff2], provider, "gemini-3.5-flash-lite"
88+
)
89+
assert len(provider.prompts) == 2
90+
assert "- src/auth.py: Updated service logic" in merged
91+
assert "- src/db.py: Updated service logic" in merged
92+
assert total_in == 80
93+
assert total_out == 20

0 commit comments

Comments
 (0)