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 <andersk@mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Anders Kaseorg committed
Dec 1, 2021 at 14:15 UTC
593a2a5d0639b4b4f91ff6e6ffb64e72020f8fd8
2 files changed
+16
-4
branch.c
+9
-4
@@ -199,7 +199,8 @@ int validate_branchname(const char *name, struct strbuf *ref)
199
*/
200
int validate_new_branchname(const char *name, struct strbuf *ref, int force)
201
{
202
- const char *head;
202
+ struct worktree **worktrees;
203
+ const struct worktree *wt;
204
205
if (!validate_branchname(name, ref))
206
return 0;
@@ -208,9 +209,13 @@ int validate_new_branchname(const char *name, struct strbuf *ref, int force)
209
die(_("a branch named '%s' already exists"),
210
ref->buf + strlen("refs/heads/"));
211
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);
219
220
return 1;
221
}
t/t3200-branch.sh
+7
@@ -168,6 +168,13 @@ test_expect_success 'git branch -M foo bar should fail when bar is checked out'
168
test_must_fail git branch -M bar foo
169
'
170
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
+
178
test_expect_success 'git branch -M baz bam should succeed when baz is checked out' '
179
git checkout -b baz &&
180
git branch bam &&