Skip to content

Commit 593a2a5

Browse files
anderskgitster
authored andcommitted
branch: protect branches checked out in all worktrees
Refuse to force-move a branch over the currently checked out branch of any working tree, not just the current one. Signed-off-by: Anders Kaseorg <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 9fdf4f1 commit 593a2a5

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

branch.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,8 @@ int validate_branchname(const char *name, struct strbuf *ref)
199199
*/
200200
int validate_new_branchname(const char *name, struct strbuf *ref, int force)
201201
{
202-
const char *head;
202+
struct worktree **worktrees;
203+
const struct worktree *wt;
203204

204205
if (!validate_branchname(name, ref))
205206
return 0;
@@ -208,9 +209,13 @@ int validate_new_branchname(const char *name, struct strbuf *ref, int force)
208209
die(_("a branch named '%s' already exists"),
209210
ref->buf + strlen("refs/heads/"));
210211

211-
head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
212-
if (!is_bare_repository() && head && !strcmp(head, ref->buf))
213-
die(_("cannot force update the current branch"));
212+
worktrees = get_worktrees();
213+
wt = find_shared_symref(worktrees, "HEAD", ref->buf);
214+
if (wt && !wt->is_bare)
215+
die(_("cannot force update the branch '%s'"
216+
"checked out at '%s'"),
217+
ref->buf + strlen("refs/heads/"), wt->path);
218+
free_worktrees(worktrees);
214219

215220
return 1;
216221
}

t/t3200-branch.sh

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,13 @@ test_expect_success 'git branch -M foo bar should fail when bar is checked out'
168168
test_must_fail git branch -M bar foo
169169
'
170170

171+
test_expect_success 'git branch -M foo bar should fail when bar is checked out in worktree' '
172+
git branch -f bar &&
173+
test_when_finished "git worktree remove wt && git branch -D wt" &&
174+
git worktree add wt &&
175+
test_must_fail git branch -M bar wt
176+
'
177+
171178
test_expect_success 'git branch -M baz bam should succeed when baz is checked out' '
172179
git checkout -b baz &&
173180
git branch bam &&

0 commit comments

Comments
 (0)