diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index b94af84661..f8f978cd42 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -126,7 +126,15 @@ def git_diff(repo: git.Repo, target: str, context_lines: int = DEFAULT_CONTEXT_L return repo.git.diff(f"--unified={context_lines}", target) def git_commit(repo: git.Repo, message: str) -> str: - commit = repo.index.commit(message) + # During a merge, keep the merged-in commits as parents and clear the merge state, like `git commit`. + merge_head = Path(repo.git_dir) / "MERGE_HEAD" + if merge_head.exists(): + parents = [repo.head.commit, *(repo.commit(sha) for sha in merge_head.read_text().split())] + commit = repo.index.commit(message, parent_commits=parents) + for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"): + (Path(repo.git_dir) / name).unlink(missing_ok=True) + else: + commit = repo.index.commit(message) return f"Changes committed successfully with hash {commit.hexsha}" def git_add(repo: git.Repo, files: list[str]) -> str: diff --git a/src/git/tests/test_server.py b/src/git/tests/test_server.py index 05d5931466..8eea776066 100644 --- a/src/git/tests/test_server.py +++ b/src/git/tests/test_server.py @@ -236,6 +236,30 @@ def test_git_log_default(test_repository): assert len(result) >= 1 assert "initial commit" in result[0] +def test_git_commit_concludes_a_merge(test_repository): + with test_repository.config_writer() as config: + config.set_value("user", "name", "Test User") + config.set_value("user", "email", "test@example.com") + main = test_repository.active_branch + test_repository.git.checkout("-b", "feature") + Path(test_repository.working_dir, "test.txt").write_text("feature") + test_repository.index.add(["test.txt"]) + feature_commit = test_repository.index.commit("feature change") + main.checkout() + Path(test_repository.working_dir, "test.txt").write_text("main") + test_repository.index.add(["test.txt"]) + main_commit = test_repository.index.commit("main change") + with pytest.raises(git.GitCommandError): + test_repository.git.merge("feature") + + Path(test_repository.working_dir, "test.txt").write_text("resolved") + test_repository.git.add("test.txt") + git_commit(test_repository, "merge feature") + + merge_commit = test_repository.head.commit + assert merge_commit.parents == (main_commit, feature_commit) + assert not Path(test_repository.git_dir, "MERGE_HEAD").exists() + def test_git_create_branch(test_repository): result = git_create_branch(test_repository, "new-feature-branch")