Skip to content

Commit bd67660

Browse files
committed
fix(git): normalize git_log schema across filtered and unfiltered branches
git_log emitted two different string shapes depending on whether start_timestamp or end_timestamp was passed: Unfiltered branch used commit.hexsha!r / commit.author!r, producing repr()-quoted values with leading single quotes and Actor angle brackets, and included the full commit body via commit.message. Filtered branch used git log --format=%H%n%an%n%ad%n%s%n, producing raw unquoted values, and dropped the commit body entirely (%s is subject only). Downstream parsers that split on "\n" and ":" have to special-case which branch produced the entry. Reported in #4469. Collapse both branches onto repo.iter_commits() with since/until kwargs, so there is exactly one code path. Drop the repr() formatting so both branches emit raw values (bare commit hash, author name/email, full message). Add a regression test asserting the two branches produce the same key order and neither emits repr artefacts. Closes #4469
1 parent 7097923 commit bd67660

2 files changed

Lines changed: 43 additions & 39 deletions

File tree

‎src/git/src/mcp_server_git/server.py‎

Lines changed: 21 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -157,45 +157,27 @@ def git_reset(repo: git.Repo) -> str:
157157
return "All staged changes reset"
158158

159159
def git_log(repo: git.Repo, max_count: int = 10, start_timestamp: Optional[str] = None, end_timestamp: Optional[str] = None) -> list[str]:
160-
if start_timestamp or end_timestamp:
161-
# Defense in depth: reject timestamps starting with '-' to prevent flag injection
162-
if start_timestamp and start_timestamp.startswith("-"):
163-
raise ValueError(f"Invalid start_timestamp: '{start_timestamp}' - cannot start with '-'")
164-
if end_timestamp and end_timestamp.startswith("-"):
165-
raise ValueError(f"Invalid end_timestamp: '{end_timestamp}' - cannot start with '-'")
166-
# Use git log command with date filtering
167-
args = []
168-
if start_timestamp:
169-
args.extend(['--since', start_timestamp])
170-
if end_timestamp:
171-
args.extend(['--until', end_timestamp])
172-
args.extend(['--format=%H%n%an%n%ad%n%s%n'])
173-
174-
log_output = repo.git.log(*args).split('\n')
175-
176-
log = []
177-
# Process commits in groups of 4 (hash, author, date, message)
178-
for i in range(0, len(log_output), 4):
179-
if i + 3 < len(log_output) and len(log) < max_count:
180-
log.append(
181-
f"Commit: {log_output[i]}\n"
182-
f"Author: {log_output[i+1]}\n"
183-
f"Date: {log_output[i+2]}\n"
184-
f"Message: {log_output[i+3]}\n"
185-
)
186-
return log
187-
else:
188-
# Use existing logic for simple log without date filtering
189-
commits = list(repo.iter_commits(max_count=max_count))
190-
log = []
191-
for commit in commits:
192-
log.append(
193-
f"Commit: {commit.hexsha!r}\n"
194-
f"Author: {commit.author!r}\n"
195-
f"Date: {commit.authored_datetime}\n"
196-
f"Message: {commit.message!r}\n"
197-
)
198-
return log
160+
# Defense in depth: reject timestamps starting with '-' to prevent flag injection
161+
if start_timestamp and start_timestamp.startswith("-"):
162+
raise ValueError(f"Invalid start_timestamp: '{start_timestamp}' - cannot start with '-'")
163+
if end_timestamp and end_timestamp.startswith("-"):
164+
raise ValueError(f"Invalid end_timestamp: '{end_timestamp}' - cannot start with '-'")
165+
166+
rev_kwargs: dict[str, str] = {}
167+
if start_timestamp:
168+
rev_kwargs["since"] = start_timestamp
169+
if end_timestamp:
170+
rev_kwargs["until"] = end_timestamp
171+
172+
log = []
173+
for commit in repo.iter_commits(max_count=max_count, **rev_kwargs):
174+
log.append(
175+
f"Commit: {commit.hexsha}\n"
176+
f"Author: {commit.author}\n"
177+
f"Date: {commit.authored_datetime}\n"
178+
f"Message: {commit.message}\n"
179+
)
180+
return log
199181

200182
def git_create_branch(repo: git.Repo, branch_name: str, base_branch: str | None = None) -> str:
201183
# Defense in depth: reject names starting with '-' to prevent flag injection

‎src/git/tests/test_server.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,28 @@ def test_git_log_default(test_repository):
234234
assert len(result) >= 1
235235
assert "initial commit" in result[0]
236236

237+
238+
def test_git_log_schema_matches_across_filter_branches(test_repository):
239+
"""git_log emits the same string schema whether or not timestamp filters are supplied."""
240+
for i in range(2):
241+
file_path = Path(test_repository.working_dir) / f"schema_test_{i}.txt"
242+
file_path.write_text(f"content {i}")
243+
test_repository.index.add([f"schema_test_{i}.txt"])
244+
test_repository.index.commit(f"schema commit {i}")
245+
246+
unfiltered = git_log(test_repository, max_count=1)
247+
filtered = git_log(test_repository, max_count=1, start_timestamp="1970-01-01")
248+
249+
assert len(unfiltered) == 1
250+
assert len(filtered) == 1
251+
# Same keys, same order — parsers that split on "\n" and ":" must not care which branch produced the entry.
252+
assert [line.split(":", 1)[0] for line in unfiltered[0].splitlines()] == \
253+
[line.split(":", 1)[0] for line in filtered[0].splitlines()]
254+
# And no repr() artefacts (leading quotes, angle brackets) that used to appear only in the unfiltered branch.
255+
for entry in (unfiltered[0], filtered[0]):
256+
commit_line = entry.splitlines()[0]
257+
assert not commit_line.startswith("Commit: '"), f"Commit hash should not be repr-quoted: {commit_line!r}"
258+
237259
def test_git_create_branch(test_repository):
238260
result = git_create_branch(test_repository, "new-feature-branch")
239261

0 commit comments

Comments
 (0)