branch: fix die_if_checked_out() when ignore_current_worktree

In 8d9fdd7 (worktree.c: check whether branch is rebased in another worktree, 2016-04-22) die_if_checked_out() learned a new option ignore_current_worktree, to modify the operation from "die() if the branch is checked out in any worktree" to "die() if the branch is checked out in any worktree other than the current one". Unfortunately we implemented it by checking the flag is_current in the worktree that find_shared_symref() returns. When the same branch is checked out in several worktrees simultaneously, find_shared_symref() will return the first matching worktree in the list composed by get_worktrees(). If one of the worktrees with the checked out branch is the current worktree, find_shared_symref() may or may not return it, depending on the order in the list. Instead of find_shared_symref(), let's do the search using use the recently introduced API is_shared_symref(), and consider ignore_current_worktree when necessary. Signed-off-by: Rubén Justo <rjusto@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Rubén Justo committed Feb 25, 2023 at 15:22 UTC faa4d5983bc1739351f49269660285a2628a3d72
2 files changed +10 -7
branch.c
+9 -5
@@ -820,12 +820,16 @@ void remove_branch_state(struct repository *r, int verbose)
820 void die_if_checked_out(const char *branch, int ignore_current_worktree)
821 {
822 struct worktree **worktrees = get_worktrees();
823 - const struct worktree *wt;
823
825 - wt = find_shared_symref(worktrees, "HEAD", branch);
826 - if (wt && (!ignore_current_worktree || !wt->is_current)) {
827 - skip_prefix(branch, "refs/heads/", &branch);
828 - die(_("'%s' is already checked out at '%s'"), branch, wt->path);
824 + for (int i = 0; worktrees[i]; i++) {
825 + if (worktrees[i]->is_current && ignore_current_worktree)
826 + continue;
827 +
828 + if (is_shared_symref(worktrees[i], "HEAD", branch)) {
829 + skip_prefix(branch, "refs/heads/", &branch);
830 + die(_("'%s' is already checked out at '%s'"),
831 + branch, worktrees[i]->path);
832 + }
833 }
834
835 free_worktrees(worktrees);
worktree.c
+1 -2
@@ -435,10 +435,9 @@ const struct worktree *find_shared_symref(struct worktree **worktrees,
435 const char *target)
436 {
437
438 - for (int i = 0; worktrees[i]; i++) {
438 + for (int i = 0; worktrees[i]; i++)
439 if (is_shared_symref(worktrees[i], symref, target))
440 return worktrees[i];
441 - }
441
442 return NULL;
443 }