Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Every tool's `repo_path` is taken literally: neither a leading `~` nor `$NAME` o
- `source_branch` (string): Branch, tag or commit to merge into the current branch (check out the branch to merge into first with `git_checkout`)
- `fast_forward_only` (boolean, optional): Only fast-forward, failing if the branches have diverged (default `true`). `false` lets Git create a merge commit when they have
- Returns: `Fast-forwarded`, `Merged ... with merge commit <short sha>`, or `Already up to date`
- Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, and a merge that would overwrite an ignored local file, whether it fast-forwards or makes a merge commit. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was
- Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, a merge that would overwrite an ignored local file, whether it fast-forwards or makes a merge commit, and a source whose tree names a path Git refuses to write (one with an empty, `.`, `..` or `.git` component), before any such path is looked up on disk. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was
- Directory renames are not followed: a file the source adds in a directory the current branch renamed is merged at the path the source gave it
12. `git_show`
- Shows the contents of a commit, or of a file or directory at a revision
Expand Down
51 changes: 47 additions & 4 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -888,16 +888,48 @@ def _on_disk_spelling(root: Path, path: str) -> str:
names = os.listdir(parent)
if name not in names:
wanted = os.lstat(parent / name)
name = next(
entry
for entry in names
if os.path.samestat(os.lstat(parent / entry), wanted)
listed = next(
(
entry
for entry in names
if os.path.samestat(os.lstat(parent / entry), wanted)
),
None,
)
if listed is None:
# `name` exists but is no entry of `parent` (`..` or `.`);
# the caller refuses such paths first, so this is a backstop.
raise ValueError(f"Invalid path {path!r} in the working tree")
name = listed
spelled.append(name)
parent = parent / name
return "/".join(spelled)


def _unsafe_source_path(repo: git.Repo, head: str, source: str) -> str | None:
"""The first path a merge of `source` would write that git refuses, if any.

A source's tree can name what git never writes itself (an entry `..`,
`.git`, or on Windows `x:`), and git refuses it only once the merge runs,
after it has looked on disk for an untracked file in its way: git's reply,
and the tool's own checks (`_ignored_files_overwritten`), would then tell
the caller whether something exists outside the working tree. So every
path the source adds or changes is checked first, by name alone, the way
`_unsafe_index_entry` checks an index entry.
"""
changed = repo.git.diff_tree(
"-r", "-z", "--no-renames", "--name-only", "--diff-filter=d", head, source
).split("\0")
return next(
(
path
for path in sorted(changed)
if path and _unsafe_index_entry(os.fsencode(path))
),
None,
)


def _ignored_files_overwritten(repo: git.Repo, head: str, source: str) -> list[str]:
"""The ignored files in the working tree a merge of `source` would replace.

Expand Down Expand Up @@ -941,6 +973,8 @@ def _ignored_files_overwritten(repo: git.Repo, head: str, source: str) -> list[s
written.add(f"{prefix}~HEAD")
if path in deleted_dirs:
written.add(f"{path}~{source}")
# `git_merge` refused any added path that leaves the working tree
# (`_unsafe_source_path`), so none reaches the lookups below.
in_the_way: set[str] = set()
for path in written:
parts = path.split("/")
Expand Down Expand Up @@ -1041,6 +1075,15 @@ def git_merge(
# names what the caller asked for.
mode = "--ff-only" if fast_forward_only else "--ff"
what = f"Merge of '{source_branch}' into '{target}'"
invalid = _unsafe_source_path(repo, head.hexsha, source.hexsha)
if invalid is not None:
# Fast-forward or not, before git or any check looks on disk. repr:
# escaped, the source's own name carries no line breaks or control
# sequences into the result.
raise ValueError(
f"{what} refused: the source tracks an invalid path {invalid!r}. "
"Nothing was changed."
)
if not fast_forward:
ignored = _ignored_files_overwritten(repo, head.hexsha, source.hexsha)
if ignored:
Expand Down
91 changes: 90 additions & 1 deletion src/git/tests/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import os
import subprocess
import unicodedata
from pathlib import Path
from typing import Any
Expand All @@ -17,7 +18,7 @@
import pytest
from conftest import connect, text_result, tool_error, wire

from mcp_server_git.server import _merge_failure
from mcp_server_git.server import _merge_failure, _on_disk_spelling


def root_of(repo: git.Repo) -> Path:
Expand Down Expand Up @@ -461,6 +462,94 @@ async def test_merge_commit_refuses_an_ignored_file_spelled_differently(
assert (root_of(repo) / local).read_text() == "LOCAL\n"


def git_input(repo: git.Repo, text: str, *args: str) -> str:
"""Run `git <args>` in `repo` with `text` on its standard input."""
# Bytes, not text: a text-mode pipe on Windows would write each "\n" as
# "\r\n", which git would take as part of a name.
return (
subprocess.run(
["git", *args],
cwd=root_of(repo),
input=text.encode(),
capture_output=True,
check=True,
)
.stdout.decode()
.strip()
)


def forged_source(repo: git.Repo, entries: str, *, diverged: bool = True) -> str:
"""Branch `feature` at a commit whose tree is `entries` (mktree input).

No git command writes a tree like this, but `git mktree` stores whatever
it is given, and a fetched commit can carry one. The tree keeps HEAD's
`test.txt`. With `diverged`, `main` gets a commit of its own, so merging
`feature` needs a merge commit; otherwise it fast-forwards. Returns HEAD's
sha.
"""
test_blob = repo.git.rev_parse("HEAD:test.txt")
tree = git_input(repo, f"100644 blob {test_blob}\ttest.txt\n{entries}", "mktree")
forged = repo.git.commit_tree(tree, "-p", "HEAD", "-m", "forged")
repo.git.branch("feature", forged)
if not diverged:
return repo.head.commit.hexsha
return commit_file(repo, "main.txt", "main\n").hexsha


def invalid_path(path: str) -> dict[str, Any]:
return tool_error(
"git_merge",
"Merge of 'feature' into 'main' refused: the source tracks an invalid "
f"path {path!r}. Nothing was changed.",
)


async def test_merge_commit_refuses_a_source_path_with_a_dot_dot_component(
repo: git.Repo,
):
# The check for ignored files refuses such a path before it touches the
# filesystem, instead of crashing while looking up its on-disk spelling.
blob = git_input(repo, "forged\n", "hash-object", "-w", "--stdin")
head = forged_source(repo, f"100644 blob {blob}\t..\n")

assert await merge(repo, "feature", fast_forward_only=False) == invalid_path("..")
assert_untouched(repo, head)


@pytest.mark.parametrize(
("diverged", "fast_forward_only"),
[(True, False), (False, False), (False, True)],
ids=["merge-commit", "fast-forward", "fast-forward-only"],
)
@pytest.mark.parametrize("present", [True, False], ids=["present", "absent"])
async def test_merge_answers_the_same_whatever_exists_outside(
repo: git.Repo, present: bool, diverged: bool, fast_forward_only: bool
):
# A `..` directory in the source names a path outside the working tree.
# The reply must be the same whether or not anything is there, whether
# the tool's own check or git's would look first.
outside = root_of(repo).parent / "outside-name"
if present:
outside.write_text("outside\n")
blob = git_input(repo, "forged\n", "hash-object", "-w", "--stdin")
inner = git_input(repo, f"100644 blob {blob}\toutside-name\n", "mktree")
head = forged_source(repo, f"040000 tree {inner}\t..\n", diverged=diverged)

result = await merge(repo, "feature", fast_forward_only=fast_forward_only)

assert result == invalid_path("../outside-name")
assert_untouched(repo, head)
assert outside.exists() is present


def test_on_disk_spelling_refuses_a_name_no_listing_holds(tmp_path: Path):
# `..` exists but is no entry of the directory: a clear error, not the
# bare StopIteration of an exhausted search.
with pytest.raises(ValueError, match=r"Invalid path '\.\./x'"):
_on_disk_spelling(tmp_path, "../x")


@pytest.mark.parametrize("options", ["--no-commit", "--squash"])
async def test_configured_merge_options_still_complete_the_merge(
repo: git.Repo, options: str
Expand Down