branch: rename orphan branches in any worktree
In cfaff3aac (branch -m: allow renaming a yet-unborn branch, 2020-12-13) we added support for renaming an orphan branch when that branch is checked out in the current worktree. Let's also allow renaming an orphan branch checked out in a worktree different than the current one. Signed-off-by: Rubén Justo <rjusto@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Rubén Justo committed
Mar 27, 2023 at 00:33 UTC
a675ad1708383f47883d0bb0b2dada827a295acd
2 files changed
+18
-2
builtin/branch.c
+4
-2
@@ -539,6 +539,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
539
}
540
541
#define IS_HEAD 1
542
+#define IS_ORPHAN 2
543
544
static void copy_or_rename_branch(const char *oldname, const char *newname, int copy, int force)
545
{
@@ -565,6 +566,8 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int
566
567
if (wt->head_ref && !strcmp(oldref.buf, wt->head_ref)) {
568
oldref_usage |= IS_HEAD;
569
+ if (is_null_oid(&wt->head_oid))
570
+ oldref_usage |= IS_ORPHAN;
571
break;
572
}
573
}
@@ -599,8 +602,7 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int
602
strbuf_addf(&logmsg, "Branch: renamed %s to %s",
603
oldref.buf, newref.buf);
604
602
- if (!copy &&
603
- (!head || strcmp(oldname, head) || !is_null_oid(&head_oid)) &&
605
+ if (!copy && !(oldref_usage & IS_ORPHAN) &&
606
rename_ref(oldref.buf, newref.buf, logmsg.buf))
607
die(_("Branch rename failed"));
608
if (copy && copy_existing_ref(oldref.buf, newref.buf, logmsg.buf))
t/t3200-branch.sh
+14
@@ -294,6 +294,20 @@ test_expect_success 'git branch -M and -C fail on detached HEAD' '
294
test_cmp expect err
295
'
296
297
+test_expect_success 'git branch -m should work with orphan branches' '
298
+ test_when_finished git checkout - &&
299
+ test_when_finished git worktree remove -f wt &&
300
+ git worktree add wt --detach &&
301
+ # rename orphan in another worktreee
302
+ git -C wt checkout --orphan orphan-foo-wt &&
303
+ git branch -m orphan-foo-wt orphan-bar-wt &&
304
+ test orphan-bar-wt=$(git -C orphan-worktree branch --show-current) &&
305
+ # rename orphan in the current worktree
306
+ git checkout --orphan orphan-foo &&
307
+ git branch -m orphan-foo orphan-bar &&
308
+ test orphan-bar=$(git branch --show-current)
309
+'
310
+
311
test_expect_success 'git branch -d on orphan HEAD (merged)' '
312
test_when_finished git checkout main &&
313
git checkout --orphan orphan &&