Skip to content

Commit a12eb29

Browse files
committed
fix(git): create a branch from a detached HEAD
git_create_branch without base_branch used repo.active_branch, which raises TypeError when HEAD is detached. Branch from the current commit instead, like git switch -c does.
1 parent f46d957 commit a12eb29

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,11 +188,17 @@ def git_create_branch(repo: git.Repo, branch_name: str, base_branch: str | None
188188
raise BadName(f"Invalid base branch: '{base_branch}' - cannot start with '-'")
189189
if base_branch:
190190
base = repo.references[base_branch]
191+
base_name = base.name
192+
elif repo.head.is_detached:
193+
# No active branch to start from; branch from the current commit.
194+
base = repo.head.commit.hexsha
195+
base_name = base
191196
else:
192197
base = repo.active_branch
198+
base_name = base.name
193199

194200
repo.create_head(branch_name, base)
195-
return f"Created branch '{branch_name}' from '{base.name}'"
201+
return f"Created branch '{branch_name}' from '{base_name}'"
196202

197203
def git_checkout(repo: git.Repo, branch_name: str) -> str:
198204
# Defense in depth: reject branch names starting with '-' to prevent flag injection,

‎src/git/tests/test_server.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,17 @@ def test_git_create_branch_from_base(test_repository):
255255

256256
assert "Created branch 'derived-branch' from 'base-branch'" in result
257257

258+
def test_git_create_branch_detached_head(test_repository):
259+
# `git switch -c <name>` from a detached HEAD branches from the current commit.
260+
detached_sha = test_repository.head.commit.hexsha
261+
test_repository.git.checkout(detached_sha)
262+
assert test_repository.head.is_detached
263+
264+
result = git_create_branch(test_repository, "rescued-branch")
265+
266+
assert "Created branch 'rescued-branch'" in result
267+
assert test_repository.heads["rescued-branch"].commit.hexsha == detached_sha
268+
258269
def test_git_show(test_repository):
259270
file_path = Path(test_repository.working_dir) / "show_test.txt"
260271
file_path.write_text("show content")

0 commit comments

Comments
 (0)