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
3 changes: 2 additions & 1 deletion src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ Please note that mcp-server-git is currently in early development. The functiona
- `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. 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, 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
- 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
- Inputs:
Expand Down
112 changes: 110 additions & 2 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -663,9 +663,12 @@ def _rewrite_tree(
command: str,
*args: str,
allowed_repository: Path | None = None,
config: str | None = None,
) -> str:
"""Run `git <command> <args>`, which writes the working tree, then re-check.

`config`, a `name=value`, is passed as `git -c` for this command only.

`harden_repo` reads the repository's configuration when the call opens
the repository, but that configuration can depend on the working tree: an
`[include]` or `[includeIf]` path into it (git skips one whose file is
Expand Down Expand Up @@ -694,7 +697,8 @@ def _rewrite_tree(
stay inside, the cleanup included, so the tree stays as written.
"""
try:
return getattr(repo.git, command)(*args)
runner = repo.git(c=config) if config is not None else repo.git
return getattr(runner, command)(*args)
finally:
try:
harden_repo(repo)
Expand Down Expand Up @@ -787,6 +791,98 @@ def _merge_failure(
return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}"


def _on_disk_spelling(root: Path, path: str) -> str:
"""`path`, an existing entry under `root`, as the directory listings spell it.

On a case-insensitive or normalization-insensitive filesystem (macOS,
Windows) the path a source tracks can name an entry whose name is spelled
differently (`.ENV` for `.env`, or decomposed for precomposed Unicode).
Git matches a pathspec to its own spelling, so each component is replaced
with the listed name of the same file (by device and inode).
"""
parent = root
spelled: list[str] = []
for name in path.split("/"):
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)
)
spelled.append(name)
parent = parent / name
return "/".join(spelled)


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.

Git does not honor `--no-overwrite-ignore` when it makes a merge commit (a
fast-forward does), so `git_merge` checks before it runs. The tree is
clean, so every untracked path is one HEAD does not track, and the merge
writes only such a path when it is one of:

- a path the source tracks and HEAD does not. This includes one HEAD
deleted since the merge base: if the source changed it, the
modify/delete conflict writes the source's version, so it must be
counted, not filtered out against the merge base. (The merge runs with
`merge.directoryRenames=false`, so git does not move a path the source
adds into a directory HEAD renamed, a path in neither tree.)
- the side name of a file/directory conflict: HEAD's file `<path>` moved
to `<path>~HEAD`, or the source's to `<path>~<source sha>`.

For each, what is in the way is whatever exists there (a file, a link, or
a directory and everything in it) or the nearest existing ancestor that is
not a directory. The ignored files among those are returned; an untracked
file that is not ignored is left for git to refuse, as it does.
"""
root = Path(repo.working_dir)
changes = repo.git.diff_tree(
"-r", "-z", "--no-renames", "--name-status", "--diff-filter=AD", head, source
).split("\0")
added: set[str] = set()
deleted: set[str] = set()
for status, path in zip(changes[0::2], changes[1::2]):
(added if status == "A" else deleted).add(path)
deleted_dirs = {
"/".join(parts[:depth])
for parts in (path.split("/") for path in deleted)
for depth in range(1, len(parts))
}
written = set(added)
for path in added:
parts = path.split("/")
for depth in range(1, len(parts)):
if (prefix := "/".join(parts[:depth])) in deleted:
written.add(f"{prefix}~HEAD")
if path in deleted_dirs:
written.add(f"{path}~{source}")
in_the_way: set[str] = set()
for path in written:
parts = path.split("/")
for depth in range(1, len(parts) + 1):
prefix = "/".join(parts[:depth])
target = root / prefix
if not os.path.lexists(target):
break
if depth == len(parts) or target.is_symlink() or not target.is_dir():
in_the_way.add(_on_disk_spelling(root, prefix))
break
if not in_the_way:
return []
listed = repo.git.ls_files(
"-z",
"--others",
"--ignored",
"--exclude-standard",
"--",
*(f":(top,literal){path}" for path in sorted(in_the_way)),
)
return sorted(filter(None, listed.split("\0")))


def git_merge(
repo: git.Repo,
source_branch: str,
Expand Down Expand Up @@ -852,13 +948,25 @@ def git_merge(
# for it (see `_LISTED_KEYS`). --no-overwrite-ignore refuses to
# replace an ignored local file (a `.env`, say) that the source tracks:
# `is_dirty()` cannot see one, and git would overwrite it unrecoverably.
# Git honors it only on a fast-forward, so a merge commit is checked
# first (`_ignored_files_overwritten`), and runs with directory-rename
# detection off, so it writes no path that check cannot predict.
#
# Git is given the commit validated above, not the name: a name can stand
# for more than one commit (`git merge FETCH_HEAD` merges every head
# FETCH_HEAD lists, as an octopus), and only the one checked is merged.
# With a sha, git's default message would name the sha, so the message
# names what the caller asked for.
mode = "--ff-only" if fast_forward_only else "--ff"
what = f"Merge of '{source_branch}' into '{target}'"
if not fast_forward:
ignored = _ignored_files_overwritten(repo, head.hexsha, source.hexsha)
if ignored:
raise ValueError(
f"{what} refused: it would overwrite ignored local files: "
f"{', '.join(ignored)}. Nothing was changed. Move or remove "
"them first."
)
try:
_rewrite_tree(
repo,
Expand All @@ -874,9 +982,9 @@ def git_merge(
f"Merge '{source_branch}' into '{target}'",
source.hexsha,
allowed_repository=allowed_repository,
config="merge.directoryRenames=false",
)
except git.GitCommandError as e:
what = f"Merge of '{source_branch}' into '{target}'"
raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e
merged = repo.head.commit
if fast_forward:
Expand Down
196 changes: 196 additions & 0 deletions src/git/tests/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
and the repository afterwards.
"""

import os
import unicodedata
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -265,6 +267,200 @@ async def test_ignored_file_the_source_tracks_is_not_overwritten(repo: git.Repo)
assert (root_of(repo) / ".env").read_text() == "SECRET=local\n"


def ignored_local(repo: git.Repo, ignore: str, tracked: dict[str, str]) -> str:
"""Ignore `ignore` on main, track `tracked` on a diverged `feature`.
Leaves `main` checked out with one commit of its own, so merging
`feature` makes a merge commit. Returns main's head sha.
"""
commit_file(repo, ".gitignore", ignore)
repo.git.checkout("-b", "feature")
for name, content in tracked.items():
path = root_of(repo) / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, newline="\n")
repo.git.add("-f", name)
repo.index.commit("track ignored paths")
repo.git.checkout("main")
return commit_file(repo, "main.txt", "main\n").hexsha


async def test_merge_commit_refuses_to_overwrite_an_ignored_file(repo: git.Repo):
# Git does not honor --no-overwrite-ignore when it makes a merge commit,
# so the tool checks the incoming paths itself before git runs.
head = ignored_local(repo, ".env\n", {".env": "tracked\n"})
(root_of(repo) / ".env").write_text("SECRET=local\n")

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

assert result == tool_error(
"git_merge",
"Merge of 'feature' into 'main' refused: it would overwrite ignored "
"local files: .env. Nothing was changed. Move or remove them first.",
)
assert repo.head.commit.hexsha == head
assert not (Path(repo.git_dir) / "MERGE_HEAD").exists()
assert (root_of(repo) / ".env").read_text() == "SECRET=local\n"


async def test_merge_commit_refuses_ignored_files_in_a_directory_it_replaces(
repo: git.Repo,
):
# The source tracks a file where an ignored directory is, and a file
# under an ignored file: both would destroy the ignored content.
head = ignored_local(
repo, "cache\nlocal.cfg\n", {"cache": "file\n", "local.cfg/x": "x\n"}
)
(root_of(repo) / "cache").mkdir()
(root_of(repo) / "cache" / "data").write_text("keep\n")
(root_of(repo) / "local.cfg").write_text("keep\n")

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

assert result == tool_error(
"git_merge",
"Merge of 'feature' into 'main' refused: it would overwrite ignored "
"local files: cache/data, local.cfg. Nothing was changed. Move or "
"remove them first.",
)
assert repo.head.commit.hexsha == head
assert (root_of(repo) / "cache" / "data").read_text() == "keep\n"
assert (root_of(repo) / "local.cfg").read_text() == "keep\n"


async def test_merge_commit_into_an_ignored_directory_is_allowed(repo: git.Repo):
# A new file inside an ignored directory replaces nothing that is there.
ignored_local(repo, "build/\n", {"build/tracked.txt": "tracked\n"})
(root_of(repo) / "build").mkdir()
(root_of(repo) / "build" / "local.txt").write_text("keep\n")

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

assert result == text_result(
f"Merged 'feature' into 'main' with merge commit {repo.head.commit.hexsha[:7]}"
)
assert (root_of(repo) / "build" / "local.txt").read_text() == "keep\n"
assert (root_of(repo) / "build" / "tracked.txt").read_text() == "tracked\n"


def refused(*paths: str) -> dict[str, Any]:
return tool_error(
"git_merge",
"Merge of 'feature' into 'main' refused: it would overwrite ignored "
f"local files: {', '.join(paths)}. Nothing was changed. Move or remove "
"them first.",
)


@pytest.mark.parametrize("renames", [None, "true"])
async def test_merge_commit_does_not_follow_a_directory_rename_onto_an_ignored_file(
repo: git.Repo, renames: str | None
):
# HEAD renamed d/ to e/ since the fork, and the source adds d/new. With
# directory-rename detection git would write e/new, a path in neither
# tree; the tool turns it off, so the file lands at d/new.
commit_file(repo, ".gitignore", "new\n")
(root_of(repo) / "d").mkdir()
commit_file(repo, "d/kept.txt", "kept\n")
repo.git.checkout("-b", "feature")
commit_file(repo, "d/new", "feature\n")
repo.git.checkout("main")
repo.git.mv("d", "e")
repo.index.commit("rename d to e")
if renames is not None:
with repo.config_writer() as config:
config.set_value("merge", "directoryRenames", renames)
(root_of(repo) / "e" / "new").write_text("LOCAL\n")

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

assert result == text_result(
f"Merged 'feature' into 'main' with merge commit {repo.head.commit.hexsha[:7]}"
)
assert (root_of(repo) / "e" / "new").read_text() == "LOCAL\n"
assert (root_of(repo) / "d" / "new").read_text() == "feature\n"


async def test_merge_commit_refuses_an_ignored_file_at_a_file_directory_side_name(
repo: git.Repo,
):
# HEAD tracks a file p where the source tracks a directory p/: git moves
# HEAD's file to p~HEAD, which would replace an ignored file of that name.
commit_file(repo, ".gitignore", "*~*\n")
repo.git.checkout("-b", "feature")
(root_of(repo) / "p").mkdir()
commit_file(repo, "p/x", "feature\n")
repo.git.checkout("main")
head = commit_file(repo, "p", "main\n").hexsha
(root_of(repo) / "p~HEAD").write_text("LOCAL\n")

assert await merge(repo, "feature", fast_forward_only=False) == refused("p~HEAD")
assert repo.head.commit.hexsha == head
assert (root_of(repo) / "p~HEAD").read_text() == "LOCAL\n"


async def test_merge_commit_refuses_an_ignored_file_at_the_source_side_name(
repo: git.Repo,
):
# The other way round: the source's file q moves to q~<source sha>.
commit_file(repo, ".gitignore", "*~*\n")
repo.git.checkout("-b", "feature")
sha = commit_file(repo, "q", "feature\n").hexsha
repo.git.checkout("main")
(root_of(repo) / "q").mkdir()
head = commit_file(repo, "q/y", "main\n").hexsha
(root_of(repo) / f"q~{sha}").write_text("LOCAL\n")

assert await merge(repo, "feature", fast_forward_only=False) == refused(f"q~{sha}")
assert repo.head.commit.hexsha == head
assert (root_of(repo) / f"q~{sha}").read_text() == "LOCAL\n"


def spelling_insensitive(directory: Path, stored: str, other: str) -> bool:
"""Whether the filesystem under `directory` finds `stored` as `other`."""
probe = directory / stored
probe.write_text("")
try:
return (directory / other).exists() and other not in os.listdir(directory)
finally:
probe.unlink()


NFC = unicodedata.normalize("NFC", "caf\u00e9.env")
NFD = unicodedata.normalize("NFD", NFC)


@pytest.mark.parametrize(
("local", "tracked"), [(".env", ".ENV"), (NFC, NFD)], ids=["case", "unicode"]
)
async def test_merge_commit_refuses_an_ignored_file_spelled_differently(
repo: git.Repo, local: str, tracked: str
):
# On a case- or normalization-insensitive filesystem the source's spelling
# names the same file; the check matches it by identity, not by name.
if not spelling_insensitive(root_of(repo), local, tracked):
pytest.skip("the filesystem tells these spellings apart")
commit_file(repo, ".gitignore", "*.env\n.env\n")
repo.git.checkout("-b", "feature")
(root_of(repo) / tracked).write_text("feature\n")
repo.git.add("-f", "--", tracked)
repo.index.commit("track")
(root_of(repo) / tracked).unlink()
repo.git.checkout("main")
head = commit_file(repo, "main.txt", "main\n").hexsha
(root_of(repo) / local).write_text("LOCAL\n")

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

assert result["isError"] is True
assert (
"refused: it would overwrite ignored local files"
in (result["content"][0]["text"])
)
assert repo.head.commit.hexsha == head
assert (root_of(repo) / local).read_text() == "LOCAL\n"


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