In cfaff3aac (branch -m: allow renaming a yet-unborn branch, 2020-12-13) we added support for renaming an orphan branch in the current working tree, avoiding the rename_ref() error because an orphan branch does not point to any ref. We did this with two checks (note that head cannot be null due to a precondition in cmd_branch): if (branch_is_not_head) // Only HEAD can be orphan. Do the rename_ref else if (head_ref_is_valid) // There is a valid ref. Do the rename_ref else // Nothing to do here. Continue With worktrees, we can try to rename an orphan branch while we are in a different worktree, and so the orphan branch we want to rename is not the HEAD in the current worktree: $ git worktree add orphan-worktree --detach $ git -C orphan-worktree checkout --orphan orphn-branch $ git branch -m orphn-branch orphan-branch fatal: No branch named 'orphn-branch'. Lets fix this considering all HEADs in all worktrees in the repository, changing the checks introduced in cfaff3aac8 to: if (branch_is_not_head_in_any_worktree) // Only HEADs can be orphan. Do the rename_ref else if (branch_ref_is_valid) // There is a valid ref. Do the rename_ref else // Nothing to do here. Continue Let's also add to t3200-branch tests for this and for normal renames of orphan branches (other than the initial branch) for which we did not yet have tests. Signed-off-by: Rubén Justo <rjusto@xxxxxxxxx> --- builtin/branch.c | 2 +- t/t3200-branch.sh | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/builtin/branch.c b/builtin/branch.c index 954008e51d..151541e1c2 100644 --- a/builtin/branch.c +++ b/builtin/branch.c @@ -559,7 +559,7 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int oldref.buf, newref.buf); if (!copy && - (!head || strcmp(oldname, head) || !is_null_oid(&head_oid)) && + (!branch_checked_out(oldref.buf) || ref_exists(oldref.buf)) && rename_ref(oldref.buf, newref.buf, logmsg.buf)) die(_("Branch rename failed")); if (copy && copy_existing_ref(oldref.buf, newref.buf, logmsg.buf)) diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh index 5a169b68d6..01d616af05 100755 --- a/t/t3200-branch.sh +++ b/t/t3200-branch.sh @@ -279,6 +279,18 @@ test_expect_success 'git branch -M and -C fail on detached HEAD' ' test_cmp expect err ' +test_expect_success 'git branch -m should work with orphan branches' ' + test_when_finished git worktree remove -f orphan-worktree && + test_when_finished git checkout - && + git worktree add orphan-worktree --detach && + git -C orphan-worktree checkout --orphan orphan-foo && + git branch -m orphan-foo orphan-bar-wt && + test orphan-bar-wt=$(git -C orphan-worktree branch --show-current) && + git checkout --orphan orphan-foo && + git branch -m orphan-foo orphan-bar && + test orphan-bar=$(git branch --show-current) +' + test_expect_success 'git branch -d on orphan HEAD (merged)' ' test_when_finished git checkout main && git checkout --orphan orphan && -- 2.39.0